<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class ReviewerAssignmentsController extends Controller
{
    public function index(): void
    {
        require_login();
        $orgId = (int) current_org_id();

        $db = Database::getInstance();
        $uid = (int) auth_id();

        // Do NOT join reviews here (schema may vary). We rely on review_assignments.status.
        $st = $db->prepare("
            SELECT ra.*, s.submission_no, s.title, s.abstract, s.status,
                   c.title_en AS conference_title_en, c.title_ar AS conference_title_ar
            FROM review_assignments ra
            INNER JOIN submissions s ON s.id = ra.submission_id
            LEFT JOIN conferences c ON c.id = s.conference_id
            WHERE ra.reviewer_id = :uid
            AND submission_id IN (SELECT id FROM submissions WHERE conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId."))  ORDER BY FIELD(ra.status,'assigned','submitted','withdrawn'), ra.due_date ASC, ra.id DESC
        ");
        $st->execute([':uid' => $uid, ':org_id' => $orgId]);
        $rows = $st->fetchAll();

        $this->view('reviewer/assignments', ['rows' => $rows]);
    }

    public function reviewForm(): void
    {
        require_login();
        $db = Database::getInstance();
        $uid = (int) auth_id();
        $assignmentId = (int) ($_GET['assignment_id'] ?? 0);

        $st = $db->prepare("
            SELECT ra.*, s.submission_no, s.title, s.abstract, s.conference_id,
                   c.title_en AS conference_title_en, c.title_ar AS conference_title_ar
            FROM review_assignments ra
            INNER JOIN submissions s ON s.id = ra.submission_id
            LEFT JOIN conferences c ON c.id = s.conference_id
            WHERE ra.id = :id AND ra.reviewer_id = :uid
            AND submission_id IN (SELECT id FROM submissions WHERE conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId."))  LIMIT 1
        ");
        $st->execute([':id' => $assignmentId, ':uid' => $uid, ':org_id' => $orgId]);
        $a = $st->fetch();
        if (!$a) {
            http_response_code(404);
            exit('Not found');
        }

        // Round instructions
        $rst = $db->prepare("
            SELECT *
            FROM review_rounds
            WHERE conference_id = :cid AND round_no = :rn
            LIMIT 1
        ");
        $rst->execute([
            ':cid' => (int) $a['conference_id'],
            ':rn'  => (int) $a['round_no'],
        ]);
        $round = $rst->fetch() ?: null;

        // Existing review (if any)
        $rv = $db->prepare("SELECT * FROM reviews WHERE assignment_id = :aid AND org_id = :org_id  LIMIT 1");
        $rv->execute([':aid' => $assignmentId]);
        $review = $rv->fetch() ?: null;

        $this->view('reviewer/review_form', [
            'a' => $a,
            'round' => $round,
            'review' => $review,
        ]);
    }

    public function submitReview(): void
    {
        require_login();
        if (!$this->isPost()) {
            redirect('reviewer/assignments');
        }
        csrf_check();

        $db = Database::getInstance();
        $uid = (int) auth_id();

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

        $st = $db->prepare("SELECT * FROM review_assignments WHERE id = :id AND reviewer_id = :uid AND submission_id IN (SELECT id FROM submissions WHERE conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId."))  LIMIT 1");
        $st->execute([':id' => $assignmentId, ':uid' => $uid, ':org_id' => $orgId]);
        $a = $st->fetch();
        if (!$a) {
            http_response_code(403);
            exit('Forbidden');
        }

        $scoreOverall = (int) ($_POST['score_overall'] ?? 0);
        $orig = (int) ($_POST['score_originality'] ?? 0);
        $clar = (int) ($_POST['score_clarity'] ?? 0);
        $rel  = (int) ($_POST['score_relevance'] ?? 0);
        $rec  = trim((string) ($_POST['recommendation'] ?? ''));
        $cta  = trim((string) ($_POST['comments_to_author'] ?? ''));
        $cte  = trim((string) ($_POST['comments_to_editor'] ?? ''));

        if ($scoreOverall < 1 || $scoreOverall > 5 || $rec === '') {
            flash('danger', trans('required_fields'));
            redirect('reviewer/review?assignment_id=' . $assignmentId);
        }

        // Upload review file (optional)
        $filePath = null;
        if (!empty($_FILES['review_file']['tmp_name'])) {
            $tmp = (string) $_FILES['review_file']['tmp_name'];
            $origName = basename((string) $_FILES['review_file']['name']);
            $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));

            if (!in_array($ext, ['pdf', 'doc', 'docx', 'txt'], true)) {
                flash('danger', 'Review file must be pdf/doc/docx/txt');
                redirect('reviewer/review?assignment_id=' . $assignmentId);
            }

            $new = 'rv_' . time() . '_' . bin2hex(random_bytes(3)) . '.' . $ext;
            $destDir = __DIR__ . '/../../storage/uploads/reviews';
            if (!is_dir($destDir)) {
                @mkdir($destDir, 0775, true);
            }
            $dest = $destDir . '/' . $new;

            if (!move_uploaded_file($tmp, $dest)) {
                flash('danger', 'Upload failed');
                redirect('reviewer/review?assignment_id=' . $assignmentId);
            }
            $filePath = 'uploads/reviews/' . $new;
        }

        $ins = $db->prepare("
            INSERT INTO reviews (
                assignment_id,
                score_overall, score_originality, score_clarity, score_relevance,
                recommendation, comments_to_author, comments_to_editor,
                review_file_path, submitted_at
            ) VALUES (
                :aid,
                :so, :o, :c, :r,
                :rec, :cta, :cte,
                :fp, NOW()
            )
            ON DUPLICATE KEY UPDATE
                score_overall=VALUES(score_overall),
                score_originality=VALUES(score_originality),
                score_clarity=VALUES(score_clarity),
                score_relevance=VALUES(score_relevance),
                recommendation=VALUES(recommendation),
                comments_to_author=VALUES(comments_to_author),
                comments_to_editor=VALUES(comments_to_editor),
                review_file_path=COALESCE(VALUES(review_file_path), review_file_path),
                submitted_at=NOW()
        ");
        $ins->execute([
            ':aid' => $assignmentId,
            ':so'  => $scoreOverall,
            ':o'   => $orig ?: null,
            ':c'   => $clar ?: null,
            ':r'   => $rel  ?: null,
            ':rec' => $rec,
            ':cta' => $cta ?: null,
            ':cte' => $cte ?: null,
            ':fp'  => $filePath,
        ]);

        $db->prepare("UPDATE review_assignments SET status='submitted', updated_at=NOW() WHERE id=:id")
           ->execute([':id' => $assignmentId]);

        flash('success', trans('save'));
        redirect('reviewer/assignments');
    }
}
