<?php
namespace App\Controllers;

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

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

class AdminReviewMonitorController
{
    protected function db()
    {
        return Database::getInstance();
    }

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

    private function role(): string
    {
        return strtolower(
            (string)(
                $_SESSION['conference_role']
                ?? $_SESSION['role']
                ?? $_SESSION['user_role']
                ?? ''
            )
        );
    }

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

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

        if (empty($_SESSION['conference_id'])) {
            header("Location: /easychair/select-conference");
            exit;
        }

        $allowed = [
            'superadmin',
            'super_admin',
            'org_admin',
            'admin',
            'organizer',
            'conference_chair',
            'track_chair'
        ];

        if (!in_array($this->role(), $allowed, true)) {
            http_response_code(403);
            exit('Access denied.');
        }
    }

    private function conference(): array
    {
        $stmt = $this->db()->prepare("
            SELECT *
            FROM conferences
            WHERE id=?
            LIMIT 1
        ");

        $stmt->execute([
            (int)$_SESSION['conference_id']
        ]);

        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            exit('Conference not found.');
        }

        if (
            !function_exists('ec_is_superadmin')
            || !ec_is_superadmin()
        ) {
            if (
                isset($c['org_id'])
                &&
                (int)$c['org_id']
                !==
                (int)($_SESSION['org_id'] ?? 0)
            ) {
                http_response_code(403);
                exit('Invalid organization access.');
            }
        }

        return $c;
    }

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

        /*
         * FIX:
         * remove Pack512 redirect
         * allow conference scoped access
         */

        if (
            function_exists('ec_scope_auto_select_conference')
            &&
            empty($_SESSION['conference_id'])
        ) {
            ec_scope_auto_select_conference(true);
        }

        $conference = $this->conference();

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

        $stmt = $this->db()->prepare("
            SELECT
                s.id submission_id,
                s.submission_no,
                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar,
                    CONCAT('Submission #',s.id)
                ) submission_title,
                s.status,
                s.stage,
                COUNT(DISTINCT ra.id) assigned_count,
                SUM(
                    CASE
                        WHEN
                            ra.status='completed'
                            OR ra.completed_at IS NOT NULL
                        THEN 1
                        ELSE 0
                    END
                ) completed_count,
                COALESCE(
                    AVG(rv.overall_score),
                    AVG(rv.score),
                    MAX(s.avg_score),
                    0
                ) avg_score,
                MIN(ra.due_date) nearest_due
            FROM submissions s
            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id
            LEFT JOIN reviews rv
                ON (
                    rv.assignment_id=ra.id
                    OR
                    rv.review_assignment_id=ra.id
                )
            WHERE s.conference_id=? {$trackSql}
            GROUP BY
                s.id,
                s.submission_no,
                s.title,
                s.title_en,
                s.title_ar,
                s.status,
                s.stage
            ORDER BY s.id DESC
        ");

        $params = [
            (int)$conference['id']
        ];

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

        $stmt->execute($params);

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

        $stmt = $this->db()->prepare("
SELECT
    u.id reviewer_id,
    u.email,

    CONCAT(
        COALESCE(u.first_name,''),
        ' ',
        COALESCE(u.last_name,'')
    ) reviewer_name,

    COUNT(DISTINCT ra.id) assigned_count,

    SUM(
        CASE
            WHEN
                ra.status='completed'
                OR ra.completed_at IS NOT NULL
            THEN 1
            ELSE 0
        END
    ) completed_count,

    SUM(
        CASE
            WHEN
                ra.due_date IS NOT NULL
                AND DATE(ra.due_date)<CURDATE()
                AND (
                    ra.status IS NULL
                    OR ra.status<>'completed'
                )
            THEN 1
            ELSE 0
        END
    ) overdue_count

FROM user_conferences uc

JOIN users u
ON u.id=uc.user_id

LEFT JOIN review_assignments ra
ON ra.reviewer_id=u.id
AND ra.conference_id=uc.conference_id

WHERE uc.conference_id=?

GROUP BY
u.id,
u.email,
u.first_name,
u.last_name

ORDER BY
overdue_count DESC,
assigned_count DESC,
reviewer_name
");
        $stmt->execute([
            (int)$conference['id']
        ]);

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

        ob_start();

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

        $content =
            ob_get_clean();

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