<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminReviewerExpertiseController
{
    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 requireAccess(): 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->requireAccess();
        $conference = $this->conference();

        $q = trim((string)($_GET['q'] ?? ''));
        $complete = trim((string)($_GET['complete'] ?? ''));

        $where = "
            WHERE uc.conference_id=?
              AND p.conference_id=?
              AND p.org_id=?
              AND r.code IN ('reviewer','track_chair','conference_chair')
        ";
        $params = [
            (int)$conference['id'],
            (int)$conference['id'],
            (int)$conference['org_id'],
        ];

        if ($complete === '1') {
            $where .= " AND p.is_profile_complete=1 ";
        } elseif ($complete === '0') {
            $where .= " AND p.is_profile_complete=0 ";
        }

        if ($q !== '') {
            $where .= "
                AND (
                    u.email LIKE ?
                    OR u.first_name LIKE ?
                    OR u.last_name LIKE ?
                    OR p.major LIKE ?
                    OR p.specialization LIKE ?
                    OR p.research_interests LIKE ?
                    OR p.keywords LIKE ?
                    OR p.reviewer_expertise LIKE ?
                    OR p.review_keywords LIKE ?
                    OR p.preferred_tracks LIKE ?
                )
            ";
            $like = '%' . $q . '%';
            array_push($params, $like, $like, $like, $like, $like, $like, $like, $like, $like, $like);
        }

        $stmt = $this->db()->prepare("
            SELECT 
                u.id AS user_id,
                u.email,
                u.first_name,
                u.last_name,
                u.mobile,
                u.phone,
                u.reviewer_score,
                r.code AS role_code,
                r.name AS role_name,
                p.id AS profile_id,
                p.major,
                p.specialization,
                p.education_level,
                p.affiliation,
                p.academic_rank,
                p.research_interests,
                p.keywords,
                p.reviewer_expertise,
                p.review_keywords,
                p.preferred_tracks,
                p.reviewer_capacity,
                p.is_profile_complete,
                (
                    SELECT COUNT(*)
                    FROM review_assignments ra
                    WHERE ra.reviewer_id=u.id
                      AND ra.conference_id=?
                      AND ra.org_id=?
                ) AS assignments_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 user_profiles p
                   ON p.user_id=u.id
                  AND p.conference_id=uc.conference_id
            {$where}
            ORDER BY p.is_profile_complete DESC, p.reviewer_capacity DESC, assignments_count ASC, u.email
            LIMIT 300
        ");
        $stmt->execute([
            (int)$conference['id'],
            (int)$conference['org_id'],
            ...$params
        ]);
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        ob_start();
        require BASE_PATH . '/app/views/admin/reviewer_expertise/index.php';
        $content = ob_get_clean();

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