<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class ReviewerDashboardController extends Controller
{

/* =========================
   CORE HELPERS
========================= */

private function requireLogin()
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

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

private function db(): \PDO
{
    return Database::getInstance();
}

private function scope(): array
{
    return [
        'user_id' => (int)($_SESSION['user_id'] ?? 0),
        'conference_id' => (int)($_SESSION['conference_id'] ?? 0),
        'org_id' => (int)($_SESSION['org_id'] ?? 0),
    ];
}

private function renderReviewer($view, $data = [])
{
    extract($data);

    ob_start();
    require BASE_PATH . "/app/views/$view.php";
    $content = ob_get_clean();

    $layout = BASE_PATH . "/app/views/layouts/reviewer_layout.php";

    if (!file_exists($layout)) {
        $layout = BASE_PATH . "/app/views/layouts/admin_layout.php";
    }

    require $layout;
}

/* =========================
   DASHBOARD
========================= */

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

    $db = $this->db();
    $s = $this->scope();

    $stmt = $db->prepare("
        SELECT ra.*, s.title, COALESCE(s.current_round_no,1) AS current_round_no
        FROM review_assignments ra
        JOIN submissions s ON s.id = ra.submission_id
        WHERE ra.reviewer_id = ?
        ORDER BY ra.id DESC
    ");

    $stmt->execute([$s['user_id']]);
    $assignments = $stmt->fetchAll(\PDO::FETCH_ASSOC);

    $stats = [
        'total' => count($assignments),
        'assigned' => 0,
        'completed' => 0
    ];

    foreach ($assignments as $a) {
        if (($a['status'] ?? '') === 'completed') {
            $stats['completed']++;
        } else {
            $stats['assigned']++;
        }
    }

    $this->renderReviewer('reviewer/dashboard', compact('assignments','stats'));
}

/* =========================
   ASSIGNMENTS
========================= */

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

    $db = $this->db();
    $s = $this->scope();

    $stmt = $db->prepare("
        SELECT ra.*, s.title, COALESCE(s.current_round_no,1) AS current_round_no
        FROM review_assignments ra
        JOIN submissions s ON s.id = ra.submission_id
        WHERE ra.reviewer_id = ?
        ORDER BY ra.id DESC
    ");

    $stmt->execute([$s['user_id']]);
    $assignments = $stmt->fetchAll(\PDO::FETCH_ASSOC);

    $stats = [
        'total' => count($assignments),
        'assigned' => 0,
        'completed' => 0
    ];

    foreach ($assignments as $a) {
        if (($a['status'] ?? '') === 'completed') {
            $stats['completed']++;
        } else {
            $stats['assigned']++;
        }
    }

    $this->renderReviewer('reviewer/assignments', compact('assignments','stats'));
}

/* =========================
   REVIEW PAGE (FIXED 🔥)
========================= */

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

    $db = $this->db();
    $s = $this->scope();

    $assignmentId = (int)($_GET['assignment_id'] ?? 0);

    $stmt = $db->prepare("
        SELECT ra.*, s.title, s.current_round_no
        FROM review_assignments ra
        JOIN submissions s ON s.id = ra.submission_id
        WHERE ra.id = ?
        AND ra.reviewer_id = ?
    ");

    $stmt->execute([$assignmentId, $s['user_id']]);
    $assignment = $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$assignment) {
        die("Assignment not found.");
    }

    /* 🔥 FIX: ROUND CHECK */
    if (($assignment['status'] ?? '') === 'completed') {
        die("Review already submitted.");
    }

    /* LOAD CRITERIA */
$stmt = $db->prepare("
    SELECT
        id,
        title_en,
        title_ar,
        max_score,
        weight,
        sort_order
    FROM review_criteria
    WHERE conference_id = ?
    AND is_active = 1
    ORDER BY sort_order ASC, id ASC
");

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

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

//$canEditReview = true;

$canEditReview = ($assignment['status'] ?? '') !== 'completed';
$this->renderReviewer('reviews/form', compact(
    'assignment',
    'criteria',
    'canEditReview'
));

    //$this->renderReviewer('reviews/form', compact('assignment','criteria'));
}

/* =========================
   SUBMIT REVIEW (CLEAN)
========================= */

public function submitReview()
{
    $this->requireLogin();

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        header("Location: /easychair/reviewer/assignments");
        exit;
    }

    $db = $this->db();
    $s  = $this->scope();

    $assignmentId = (int)($_POST['assignment_id'] ?? 0);

    /* =========================
       VALIDATE ASSIGNMENT
    ========================= */

    $stmt = $db->prepare("
        SELECT ra.*, s.conference_id
        FROM review_assignments ra
        JOIN submissions s ON s.id = ra.submission_id
        WHERE ra.id = ?
        AND ra.reviewer_id = ?
        LIMIT 1
    ");

    $stmt->execute([
        $assignmentId,
        $s['user_id']
    ]);

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

    if (!$assignment) {
        die("Invalid assignment.");
    }

    if (($assignment['status'] ?? '') === 'completed') {
        die("Already reviewed.");
    }

/* =========================
   CALCULATE WEIGHTED SCORE
========================= */

$totalWeighted = 0;
$totalWeight   = 0;

/* DEBUG */
error_log("POST CRITERIA: " . print_r($_POST['criteria'] ?? [], true));

$stmt = $db->prepare("
    SELECT
        id,
        weight,
        max_score
    FROM review_criteria
    WHERE conference_id = ?
    AND is_active = 1
    ORDER BY sort_order ASC, id ASC
");

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

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

/* DEBUG */
error_log("CRITERIA LIST: " . print_r($criteriaList, true));

foreach ($criteriaList as $criterion) {

    $cid = (string)$criterion['id'];

    /* MUST EXIST */
    if (!isset($_POST['criteria'][$cid])) {
        continue;
    }

    $score  = (float)$_POST['criteria'][$cid];
    $weight = (float)$criterion['weight'];
    $max    = (float)$criterion['max_score'];

    if ($max <= 0 || $weight <= 0) {
        continue;
    }

    /* normalize to percentage */
    $normalized = ($score / $max) * 100;

    $totalWeighted += ($normalized * $weight);

    $totalWeight += $weight;
}

/* FINAL SCORE */
$finalScore = $totalWeight > 0
    ? round($totalWeighted / $totalWeight, 2)
    : 0;

/* DEBUG */
error_log("FINAL SCORE: " . $finalScore);    


    /* =========================
       REVIEW META
    ========================= */

    $recommendation = trim($_POST['recommendation'] ?? '');
    $comments       = trim($_POST['comments'] ?? '');

    /* =========================
       INSERT REVIEW
    ========================= */

    $stmt = $db->prepare("
        INSERT INTO reviews
        (
            review_assignment_id,
            submission_id,
            reviewer_id,
            overall_score,
            recommendation,
            comments_to_author,
            created_at
        )
        VALUES (?, ?, ?, ?, ?, ?, NOW())
    ");

    $stmt->execute([
        $assignmentId,
        $assignment['submission_id'],
        $s['user_id'],
        $finalScore,
        $recommendation,
        $comments
    ]);

    $reviewId = (int)$db->lastInsertId();

    /* =========================
       SAVE CRITERION SCORES
    ========================= */

    if (!empty($_POST['criteria'])) {

        foreach ($_POST['criteria'] as $criterionId => $value) {

            $criterionId = (int)$criterionId;
            $value       = (float)$value;

            /* validate criterion */
            $stmtCheck = $db->prepare("
                SELECT id
                FROM review_criteria
                WHERE id = ?
                LIMIT 1
            ");

            $stmtCheck->execute([$criterionId]);

            if (!$stmtCheck->fetchColumn()) {
                continue;
            }

            $stmtInsert = $db->prepare("
                INSERT INTO review_criterion_scores
                (
                    review_id,
                    criterion_id,
                    score,
                    created_at
                )
                VALUES (?, ?, ?, NOW())
            ");

            $stmtInsert->execute([
                $reviewId,
                $criterionId,
                $value
            ]);
        }
    }

    /* =========================
       UPDATE ASSIGNMENT STATUS
    ========================= */

    $stmt = $db->prepare("
        UPDATE review_assignments
        SET status = 'completed'
        WHERE id = ?
    ");

    $stmt->execute([$assignmentId]);

\App\Services\SubmissionWorkflowService
    ::onReviewCompleted(
        (int)$assignment['submission_id'],
        $_SESSION['user_id'] ?? null
    );

    /* =========================
       SUCCESS
    ========================= */

    header("Location: /easychair/reviewer/dashboard");
    exit;
}


/* =========================
   HISTORY
========================= */

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

    $db = $this->db();
    $s = $this->scope();

    $stmt = $db->prepare("
        SELECT r.*, s.title
        FROM reviews r
        JOIN submissions s ON s.id = r.submission_id
        WHERE r.reviewer_id = ?
        ORDER BY r.id DESC
    ");

    $stmt->execute([$s['user_id']]);
    $history = $stmt->fetchAll(\PDO::FETCH_ASSOC);

    $this->renderReviewer('reviewer/history', compact('history'));
}

}
