<?php
namespace App\Controllers;

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

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

class ReviewerController extends Controller
{

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

    if (!isset($_SESSION['user_id'])) {

        header("Location: /easychair/login");
        exit;

    }

    /*
    Ensure conference exists
    */

    if (empty($_SESSION['conference_id'])) {

        $db = \App\Core\Database::getInstance();

        $stmt = $db->query("
            SELECT id
            FROM conferences
            ORDER BY id DESC
            LIMIT 1
        ");

        $_SESSION['conference_id'] =
            (int)$stmt->fetchColumn();
    }
}

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

    if (!isset($_SESSION['user_id'])) {

        header("Location: /easychair/login");
        exit;

    }

    /*
    Resolve conference if missing
    */

    if (!isset($_SESSION['conference_id'])
        || !$_SESSION['conference_id']) {

        $db = \App\Core\Database::getInstance();

        $stmt = $db->prepare("
            SELECT id
            FROM conferences
            ORDER BY id DESC
            LIMIT 1
        ");

        $stmt->execute();

        $_SESSION['conference_id'] =
            (int)$stmt->fetchColumn();
    }
}


    public function score()
    {
        $db = Database::getInstance();
        $conf = $_SESSION['conference_id'];

        $stage = $db->query("SELECT status FROM conferences WHERE id=$conf")->fetchColumn();

        if($stage !== 'reviewing'){
            die("Review phase is not active.");
        }

        $db->prepare("INSERT INTO review_scores
        (assignment_id,originality,quality,relevance,comments)
        VALUES (?,?,?,?,?)")
        ->execute([
            $_POST['assignment_id'],
            $_POST['originality'],
            $_POST['quality'],
            $_POST['relevance'],
            $_POST['comments']
        ]);

        $db->prepare("UPDATE assignments SET status='completed' WHERE id=?")
           ->execute([$_POST['assignment_id']]);

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


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

    $db =
        \App\Core\Database::getInstance();

    /*
    Get assignment id
    */

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

    if (!$assignmentId) {

        die(
            "Assignment ID missing."
        );

    }

    /*
    Resolve submission from assignment
    */

    $stmt =
        $db->prepare("
            SELECT
                ra.id,
                ra.submission_id,
                ra.reviewer_id,

                s.title,
                s.title_en,
                s.title_ar,
                s.stage,
                s.status

            FROM review_assignments ra

            JOIN submissions s
                ON s.id = ra.submission_id

            WHERE ra.id = ?
            LIMIT 1
        ");

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

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

    if (!$assignment) {

        die(
            "Assignment not found."
        );

    }

    /*
    Security — ensure reviewer owns assignment
    */

    if (
        (int)$assignment['reviewer_id']
        !==
        (int)$_SESSION['user_id']
    ) {

        die(
            "Unauthorized reviewer."
        );

    }

    $submissionId =
        (int)$assignment['submission_id'];

    /*
    Load submission details
    */

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

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

$submissions = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    /*
    Render review form
    */

    $this->render(
        'reviewer/review',
        [
            'assignment' => $assignment,
            'submission' => $submission,
            'assignment_id' => $assignmentId,
            'submission_id' => $submissionId
        ]
    );
}

public function submitReview()
{
error_log("SUBMIT REVIEW HIT");
error_log("POST DATA: " . json_encode($_POST));
    /*
    Safe session check
    */

     if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

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

    $db = Database::getInstance();

    error_log("SUBMIT REVIEW HIT");

   // $db = \App\Core\Database::getInstance();

    /*
    STEP 1 — Get assignment
    */

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

    if (!$assignmentId) {

        die("Assignment ID missing.");

    }

    /*
    STEP 2 — Resolve submission
    */

    $stmt = $db->prepare("
        SELECT
            submission_id,
            reviewer_id
        FROM review_assignments
        WHERE id = ?
        LIMIT 1
    ");

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

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

if (
    !$assignment ||
    (int)$assignment['reviewer_id'] !== (int)$_SESSION['user_id']
) {
    die("Unauthorized assignment access.");
}

    $submissionId =
        (int)$assignment['submission_id'];

    /*
    STEP 3 — Read review data
    */

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

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

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


$stmt = $db->prepare("
    SELECT id FROM reviews
    WHERE submission_id = ?
    AND reviewer_id = ?
");

$stmt->execute([
    $submissionId,
    $_SESSION['user_id']
]);

if ($stmt->fetch()) {
    die("You already submitted this review.");
}
    /*
    STEP 4 — Insert review
    */

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

    $stmt->execute([

        $submissionId,

        $_SESSION['user_id'],

        $score,

        $recommendation,

        $comments

    ]);

    /*
    STEP 5 — Mark assignment completed
    */

    $db->prepare("
        UPDATE review_assignments
        SET status = 'completed',completed_at = NOW()
        WHERE id = ?
    ")
    ->execute([
        $assignmentId
    ]);

    /*
    Debug log
    */

    error_log(
        "REVIEW SUBMITTED: submission="
        . $submissionId
        . " assignment="
        . $assignmentId
    );

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

    exit;
}

public function switchConference()
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    if (empty($_SESSION['user_id'])) {

        header(
            'Location: /easychair/login'
        );

        exit;
    }

    $conferenceId =
        (int)($_GET['id'] ?? 0);

    if (!$conferenceId) {

        header(
            'Location: /easychair/reviewer/dashboard'
        );

        exit;
    }

    $db =
        \App\Core\Database::getInstance();

    /*
    --------------------------------------------------
    Ensure reviewer belongs to conference
    --------------------------------------------------
    */

    $stmt =
        $db->prepare("
            SELECT id
            FROM conference_reviewers
            WHERE conference_id = ?
            AND user_id = ?
            LIMIT 1
        ");

    $stmt->execute([
        $conferenceId,
        $_SESSION['user_id']
    ]);

    if (!$stmt->fetch()) {

        http_response_code(403);

        exit(
            'Conference reviewer access denied.'
        );
    }

    /*
    --------------------------------------------------
    Apply conference context
    --------------------------------------------------
    */

    $_SESSION['conference_id'] =
        $conferenceId;

    $_SESSION['current_conference_id'] =
        $conferenceId;

    $_SESSION['reviewer_conference_id'] =
        $conferenceId;

    /*
    --------------------------------------------------
    Redirect reviewer dashboard
    --------------------------------------------------
    */

    header(
        'Location: /easychair/reviewer/dashboard'
    );

    exit;
}

}
