<?php
namespace App\Controllers;

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

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

class ReviewerReviewController extends Controller
{
    public function show()
    {
        if (($_SESSION['user']['role'] ?? '') !== 'reviewer') {
            http_response_code(403);
            exit('Forbidden');
        }

        $submissionId = (int)($_GET['id'] ?? 0);
        $reviewerId = $_SESSION['user']['id'];
        $orgId = $_SESSION['user']['org_id'];

        $db = Database::getInstance();

        // Ensure reviewer assigned
        $stmt = $db->prepare("
            SELECT s.id, s.title, s.abstract, s.current_round_no
            FROM submissions s
            JOIN submission_reviewers sr 
              ON sr.submission_id = s.id
            WHERE s.id = ?
              AND sr.reviewer_id = ?
              AND s.org_id = ?
        ");
        $stmt->execute([$submissionId, $reviewerId, $orgId]);
        $submission = $stmt->fetch();

        if (!$submission) {
            exit('Unauthorized');
        }

        // Fetch existing review
        $stmt = $db->prepare("
            SELECT * FROM reviews
            WHERE submission_id = ?
              AND reviewer_id = ?
              AND round_no = ?
        ");
        $stmt->execute([
            $submissionId,
            $reviewerId,
            $submission['current_round_no']
        ]);

        $review = $stmt->fetch();

        $this->view('reviewer/review_form', compact('submission','review'));
    }

    public function save()
    {
        if (($_SESSION['user']['role'] ?? '') !== 'reviewer') {
            http_response_code(403);
            exit('Forbidden');
        }

        $db = Database::getInstance();

        $submissionId = (int)$_POST['submission_id'];
        $reviewerId = $_SESSION['user']['id'];
        $roundNo = (int)$_POST['round_no'];
        $score = (int)$_POST['score'];
        $confidence = (int)$_POST['confidence'];
        $recommendation = $_POST['recommendation'];
        $commentsAuthor = $_POST['comments_author'];
        $commentsCommittee = $_POST['comments_committee'];
        $isSubmit = isset($_POST['final_submit']) ? 1 : 0;

        // Check if exists
        $stmt = $db->prepare("
            SELECT id FROM reviews
            WHERE submission_id = ?
              AND reviewer_id = ?
              AND round_no = ?
        ");
        $stmt->execute([$submissionId, $reviewerId, $roundNo]);

        if ($stmt->fetch()) {
            $db->prepare("
                UPDATE reviews
                SET score=?, confidence=?, recommendation=?,
                    comments_to_author=?, comments_to_committee=?,
                    is_submitted=?, submitted_at=?
                WHERE submission_id=? AND reviewer_id=? AND round_no=?
            ")->execute([
                $score, $confidence, $recommendation,
                $commentsAuthor, $commentsCommittee,
                $isSubmit,
                $isSubmit ? date('Y-m-d H:i:s') : null,
                $submissionId, $reviewerId, $roundNo
            ]);
        } else {
            $db->prepare("
                INSERT INTO reviews
                (submission_id, reviewer_id, round_no,
                 score, confidence, recommendation,
                 comments_to_author, comments_to_committee,
                 is_submitted, submitted_at)
                VALUES (?,?,?,?,?,?,?,?,?,?)
            ")->execute([
                $submissionId, $reviewerId, $roundNo,
                $score, $confidence, $recommendation,
                $commentsAuthor, $commentsCommittee,
                $isSubmit,
                $isSubmit ? date('Y-m-d H:i:s') : null
            ]);
        }

        echo "Review saved successfully.";
    }
}
