<?php
namespace App\Controllers;

use App\Core\Database;

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

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

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

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

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

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

    private function conferenceScopeSql(string $alias = 'ra'): array
    {
        $conferenceId = (int)($_SESSION['conference_id'] ?? 0);
        return [" {$alias}.conference_id = ? ", [$conferenceId]];
    }

    private function assignmentsForUser(bool $history = false): array
    {
        $db = $this->db();
        $userId = (int)$_SESSION['user_id'];
        $conferenceId = (int)$_SESSION['conference_id'];

        $statusCondition = $history
            ? " AND COALESCE(ra.status,'assigned') IN ('submitted','completed') "
            : " AND COALESCE(ra.status,'assigned') NOT IN ('submitted','completed','cancelled') ";

        $queries = [
            "
            SELECT
                ra.*,
                s.submission_no,
                s.title,
                s.title_ar,
                s.status AS submission_status,
                s.stage AS submission_stage,
                rv.id AS review_id,
                rv.total_score,
                rv.recommendation,
                rv.submitted_at
            FROM review_assignments ra
            JOIN submissions s ON s.id = ra.submission_id
            LEFT JOIN reviews rv ON rv.assignment_id = ra.id
            WHERE ra.reviewer_id = ?
              AND ra.conference_id = ?
              {$statusCondition}
            ORDER BY COALESCE(ra.due_date, ra.created_at) DESC, ra.id DESC
            LIMIT 300
            ",
            "
            SELECT
                ra.*,
                s.submission_no,
                s.title,
                s.title_ar,
                s.status AS submission_status,
                s.stage AS submission_stage,
                NULL AS review_id,
                NULL AS total_score,
                NULL AS recommendation,
                NULL AS submitted_at
            FROM reviewer_assignments ra
            JOIN submissions s ON s.id = ra.submission_id
            WHERE ra.reviewer_id = ?
              AND ra.conference_id = ?
              {$statusCondition}
            ORDER BY COALESCE(ra.due_date, ra.created_at) DESC, ra.id DESC
            LIMIT 300
            "
        ];

        foreach ($queries as $sql) {
            try {
                $stmt = $db->prepare($sql);
                $stmt->execute([$userId, $conferenceId]);
                return $stmt->fetchAll(\PDO::FETCH_ASSOC);
            } catch (\Throwable $e) {
                continue;
            }
        }

        return [];
    }

    private function stats(): array
    {
        $allOpen = $this->assignmentsForUser(false);
        $history = $this->assignmentsForUser(true);

        $late = 0;
        foreach ($allOpen as $a) {
            $due = $a['due_date'] ?? null;
            if ($due && strtotime((string)$due) < time()) {
                $late++;
            }
        }

        return [
            'total_assignments' => count($allOpen) + count($history),
            'pending_assignments' => count($allOpen),
            'completed_reviews' => count($history),
            'late_reviews' => $late,
        ];
    }

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

        $assignments = $this->assignmentsForUser(false);
        $stats = $this->stats();

        ob_start();
        require BASE_PATH . '/app/views/reviewer/dashboard.php';
        $content = ob_get_clean();

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

    public function assignments()
    {
        $this->requireReviewer();

        $assignments = $this->assignmentsForUser(false);

        ob_start();
        require BASE_PATH . '/app/views/reviewer/assignments.php';
        $content = ob_get_clean();

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

    public function history()
    {
        $this->requireReviewer();

        $reviews = $this->assignmentsForUser(true);

        ob_start();
        require BASE_PATH . '/app/views/reviewer/history.php';
        $content = ob_get_clean();

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

    public function review()
    {
        $this->requireReviewer();

        $assignmentId = (int)($_GET['assignment_id'] ?? $_GET['id'] ?? 0);
        if ($assignmentId <= 0) {
            http_response_code(400);
            exit("Missing assignment_id.");
        }

        $db = $this->db();

        $assignment = null;
        $queries = [
            "
            SELECT ra.*, s.submission_no, s.title, s.title_ar, s.abstract, s.abstract_ar
            FROM review_assignments ra
            JOIN submissions s ON s.id=ra.submission_id
            WHERE ra.id=? AND ra.reviewer_id=? AND ra.conference_id=?
            LIMIT 1
            ",
            "
            SELECT ra.*, s.submission_no, s.title, s.title_ar, s.abstract, s.abstract_ar
            FROM reviewer_assignments ra
            JOIN submissions s ON s.id=ra.submission_id
            WHERE ra.id=? AND ra.reviewer_id=? AND ra.conference_id=?
            LIMIT 1
            "
        ];

        foreach ($queries as $sql) {
            try {
                $stmt = $db->prepare($sql);
                $stmt->execute([$assignmentId, (int)$_SESSION['user_id'], (int)$_SESSION['conference_id']]);
                $assignment = $stmt->fetch(\PDO::FETCH_ASSOC);
                if ($assignment) break;
            } catch (\Throwable $e) {}
        }

        if (!$assignment) {
            http_response_code(404);
            exit("Assignment not found.");
        }

        $criteria = [];
        try {
            $stmt = $db->prepare("
                SELECT *
                FROM review_criteria
                WHERE conference_id=?
                ORDER BY sort_order, id
            ");
            $stmt->execute([(int)$_SESSION['conference_id']]);
            $criteria = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } catch (\Throwable $e) {
            $criteria = [];
        }

        ob_start();
        require BASE_PATH . '/app/views/reviewer/review.php';
        $content = ob_get_clean();

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