<?php

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';
require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Core\Database;
use App\Core\RoleMatrix;
use App\Services\TrackChairScope;

class AdminSubmissionController extends Controller
{
    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function requireAdmin(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header('Location: /easychair/login');
            exit;
        }

        $role =
            $_SESSION['role']
            ?? '';

        if (
            in_array(
                $role,
                [
                    'superadmin',
                    'super_admin',
                    'admin',
                    'conference_chair',
                    'organizer',
                    'track_chair'
                ],
                true
            )
        ) {
            return;
        }

        if (
            RoleMatrix::can('manage_submissions')
        ) {
            return;
        }

        http_response_code(403);

        exit('Access denied.');
    }

    public function index()
    {
        $this->requireAdmin();

        $db =
            Database::getInstance();

        $role =
            $_SESSION['role']
            ?? '';

        $conferenceId =
            (int)(
                $_SESSION['conference_id']
                ??
                $_SESSION['current_conference_id']
                ??
                0
            );

        $where =
            " WHERE 1=1 ";

        $params = [];

        [$trackSql,$trackParams] =
            TrackChairScope::sql('s');

        if ($role !== 'superadmin') {

            if ($conferenceId <= 0) {

                header(
                    'Location: /easychair/select-conference'
                );

                exit;
            }

            $where .= "
                AND s.conference_id = ?
            ";

            $params[] =
                $conferenceId;

        } elseif ($conferenceId > 0) {

            $where .= "
                AND s.conference_id = ?
            ";

            $params[] =
                $conferenceId;
        }

        $stmt =
            $db->prepare("

SELECT

s.*,

COALESCE(
s.title,
s.title_en,
s.title_ar,
CONCAT('Submission #',s.id)
)
AS display_title,

COALESCE(
c.title_ar,
c.title_en
)
AS conference,

c.short_name
AS conference_short_name,

CONCAT(
COALESCE(u.first_name,''),
' ',
COALESCE(u.last_name,'')
)
AS author_name,

u.email
AS author_email,

COUNT(
DISTINCT ra.id
)
AS assignments_count,

COUNT(
DISTINCT rv.id
)
AS reviews_count,

SUM(
CASE
WHEN ra.status='completed'
THEN 1
ELSE 0
END
)
AS completed_reviews,

COALESCE(
s.current_round_no,
1
)
AS current_round_no,

COALESCE(
s.avg_score,
0
)
AS avg_score,

COALESCE(
s.recommended_decision,
'-'
)
AS recommended_decision,

COALESCE(
t.name_en,
t.name_ar,
CONCAT('Track #',s.track_id)
)
AS track_name

FROM submissions s

LEFT JOIN conferences c
ON c.id=s.conference_id

LEFT JOIN users u
ON u.id=s.author_id

LEFT JOIN tracks t
ON t.id=s.track_id

LEFT JOIN review_assignments ra
ON ra.submission_id=s.id

LEFT JOIN reviews rv
ON rv.submission_id=s.id

{$where}
{$trackSql}

GROUP BY s.id

ORDER BY s.id DESC

");

        $params = array_merge(
            $params,
            $trackParams
        );

        $stmt->execute(
            $params
        );

        $submissions =
            $stmt->fetchAll(
                \PDO::FETCH_ASSOC
            );

        $reviewers = [];

        try {

            $stmtReviewers =
                $db->prepare("

SELECT DISTINCT

u.id,
u.first_name,
u.last_name,
u.email,

COALESCE(loads.load_count,0)
AS load_count

FROM user_conferences uc

JOIN roles r
ON r.id=uc.role_id

JOIN users u
ON u.id=uc.user_id

LEFT JOIN(

SELECT
reviewer_id,
COUNT(*) load_count
FROM review_assignments
WHERE conference_id=?
GROUP BY reviewer_id

) loads

ON loads.reviewer_id=u.id

WHERE

uc.conference_id=?

AND r.code='reviewer'

AND u.is_active=1

ORDER BY

load_count ASC,
u.first_name,
u.last_name

");

            $stmtReviewers->execute([
                $conferenceId,
                $conferenceId
            ]);

            $reviewers =
                $stmtReviewers->fetchAll(
                    \PDO::FETCH_ASSOC
                );

        } catch (\Throwable $e) {

            error_log(
                $e->getMessage()
            );

            $reviewers = [];
        }

        ob_start();

        require
            BASE_PATH
            .
            '/app/views/admin/submissions/index.php';

        $content =
            ob_get_clean();

        require
            BASE_PATH
            .
            '/app/views/layouts/admin_layout.php';
    }
}
