<?php
namespace App\Controllers;

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

use App\Core\Database;

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 (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;
        }

        if (!in_array($this->role(), ['super_admin','org_admin','admin','organizer','conference_chair','track_chair'], 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 ($this->role() !== 'super_admin' && (int)$c['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
            http_response_code(403);
            exit("Invalid organization access.");
        }

        return $c;
    }

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'super_admin') {
            if (function_exists('ec_scope_auto_select_conference')) {
                // ec_scope_auto_select_conference(true);
            }
            $landing = function_exists('ec_scope_landing_url') ? ec_scope_landing_url() : '/easychair/admin/dashboard';
            header("Location: " . $landing);
            exit;
        }

$this->requireAdmin();
        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            SELECT 
                s.id AS submission_id,
                s.submission_no,
                COALESCE(s.title,s.title_en,s.title_ar,CONCAT('Submission #',s.id)) AS submission_title,
                s.status,
                s.stage,
                COUNT(DISTINCT ra.id) AS assigned_count,
                SUM(CASE WHEN ra.status IN ('completed') OR ra.completed_at IS NOT NULL THEN 1 ELSE 0 END) AS completed_count,
                COALESCE(AVG(rv.overall_score), AVG(rv.score), MAX(s.avg_score)) AS avg_score,
                MIN(ra.due_date) AS 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=?
              AND s.org_id=?
            GROUP BY s.id, s.submission_no, s.title, s.title_en, s.title_ar, s.status, s.stage
            ORDER BY s.id DESC
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $submissions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT 
                u.id AS reviewer_id,
                u.email,
                CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS reviewer_name,
                COUNT(ra.id) AS assigned_count,
                SUM(CASE WHEN ra.status='completed' OR ra.completed_at IS NOT NULL THEN 1 ELSE 0 END) AS completed_count,
                SUM(CASE WHEN ra.due_date < CURDATE() AND ra.status NOT IN ('completed') THEN 1 ELSE 0 END) AS overdue_count
            FROM user_conferences uc
            JOIN users u ON u.id=uc.user_id
            JOIN roles r ON r.id=uc.role_id
            LEFT JOIN review_assignments ra ON ra.reviewer_id=u.id AND ra.conference_id=uc.conference_id
            WHERE uc.conference_id=?
              AND r.code='reviewer'
            GROUP BY u.id, u.email, u.first_name, u.last_name
            ORDER BY overdue_count DESC, assigned_count DESC, u.email
        ");
        $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';
    }
}
