<?php
// ══════════════════════════════════════════════════════════
// FIX 1: display_errors OFF so PHP errors don't break JSON
// ══════════════════════════════════════════════════════════
ini_set('display_errors', 0);
error_reporting(0);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_role('admin');
// ══════════════════════════════════════════════════════════
// FIX 2: reviewer_mailer.php included AFTER require_role
// ══════════════════════════════════════════════════════════
require_once __DIR__ . '/config/reviewer_mailer.php';

$sid = (int)($_GET['id'] ?? 0);
if (!$sid) { header('Location: submissions.php'); exit; }

// ══════════════════════════════════════════════════════════
// AJAX HANDLERS
// ══════════════════════════════════════════════════════════
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');

    if ($_GET['ajax'] === 'get_reviewers') {
        try {
            $rows = $pdo->query("
                SELECT r.id AS reviewer_id, r.reviewer_rating, r.total_reviews_completed,
                       r.total_reviews_declined, r.total_reviews_cancelled, r.avg_days_to_complete,
                       r.last_review_assigned, r.is_available, r.reviewing_interests,
                       u.user_id, u.first_name, u.last_name, u.email, u.title,
                       a.name AS affiliation_name, a.country
                FROM reviewers r
                JOIN users u ON r.user_id = u.user_id
                LEFT JOIN affiliations a ON a.affiliation_id = u.affiliation_id
                WHERE u.role IN ('reviewer','both') AND u.is_active = 1
                ORDER BY r.reviewer_rating DESC, r.total_reviews_completed DESC
            ")->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'reviewers' => $rows]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    if ($_GET['ajax'] === 'get_assignments') {
        $sub = (int)($_GET['sub_id'] ?? $sid);
        try {
            $stmt = $pdo->prepare("
                SELECT ra.*, u.first_name, u.last_name, u.email, u.title,
                       rv.reviewer_rating AS reviewer_avg_rating
                FROM review_assignments ra
                JOIN reviewers rv ON ra.reviewer_id = rv.id
                JOIN users u ON rv.user_id = u.user_id
                WHERE ra.submission_id = ?
                ORDER BY ra.request_sent_date DESC
            ");
            $stmt->execute([$sub]);
            echo json_encode(['success' => true, 'assignments' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    if ($_GET['ajax'] === 'get_reviews') {
        $sub = (int)($_GET['sub_id'] ?? $sid);
        try {
            $stmt = $pdo->prepare("
                SELECT rv.*, u.first_name, u.last_name, u.email, u.title,
                       a.name AS affiliation_name, a.country,
                       ra.assignment_status, ra.response_due_date, ra.review_due_date,
                       ra.reviewer_type, ra.request_sent_date, ra.reviewer_rating AS admin_rating
                FROM reviews rv
                JOIN reviewers r ON rv.reviewer_id = r.id
                JOIN users u ON r.user_id = u.user_id
                LEFT JOIN affiliations a ON a.affiliation_id = u.affiliation_id
                JOIN review_assignments ra ON rv.reviewer_id = ra.reviewer_id AND rv.submission_id = ra.submission_id
                WHERE rv.submission_id = ?
                ORDER BY rv.reviewed_at DESC
            ");
            $stmt->execute([$sub]);
            echo json_encode(['success' => true, 'reviews' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    if ($_GET['ajax'] === 'get_decisions') {
        $sub = (int)($_GET['sub_id'] ?? $sid);
        try {
            $stmt = $pdo->prepare("
                SELECT ed.*, u.first_name AS editor_first, u.last_name AS editor_last
                FROM editorial_decisions ed
                JOIN users u ON ed.editor_id = u.user_id
                WHERE ed.submission_id = ?
                ORDER BY ed.created_at DESC
            ");
            $stmt->execute([$sub]);
            echo json_encode(['success' => true, 'decisions' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    if ($_GET['ajax'] === 'get_review' && isset($_GET['review_id'])) {
        try {
            $stmt = $pdo->prepare("
                SELECT rv.*, u.first_name, u.last_name
                FROM reviews rv
                JOIN reviewers r ON rv.reviewer_id = r.id
                JOIN users u ON r.user_id = u.user_id
                WHERE rv.id = ?
            ");
            $stmt->execute([(int)$_GET['review_id']]);
            $rev = $stmt->fetch(PDO::FETCH_ASSOC);
            echo json_encode(['success' => (bool)$rev, 'review' => $rev]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    exit;
}

// ══════════════════════════════════════════════════════════
// POST: Assign EXISTING reviewer
// ══════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_reviewer'])) {
    header('Content-Type: application/json');
    try {
        $reviewer_id = (int)$_POST['reviewer_id'];
        $resp_due    = $_POST['response_due_date'] ?: null;
        $review_due  = $_POST['review_due_date']   ?: null;
        $rev_type    = $_POST['reviewer_type'] ?? 'anonymous_reviewer_anonymous_author';

        if ($reviewer_id <= 0) throw new Exception("Invalid reviewer selected.");

        $chk = $pdo->prepare("SELECT id FROM review_assignments WHERE submission_id=? AND reviewer_id=?");
        $chk->execute([$sid, $reviewer_id]);
        if ($chk->fetch()) throw new Exception("Reviewer already assigned to this submission.");

        do {
            $access_key = bin2hex(random_bytes(32));
            $kc = $pdo->prepare("SELECT id FROM review_assignments WHERE access_key=?");
            $kc->execute([$access_key]);
        } while ($kc->fetch());

        $pdo->prepare("
            INSERT INTO review_assignments
              (submission_id, reviewer_id, review_round, assignment_status,
               request_sent_date, response_due_date, review_due_date, reviewer_type, access_key)
            VALUES (?, ?, 1, 'request_sent', NOW(), ?, ?, ?, ?)
        ")->execute([$sid, $reviewer_id, $resp_due, $review_due, $rev_type, $access_key]);

        $cs = $pdo->prepare("SELECT submission_status FROM submissions WHERE submission_id=?");
        $cs->execute([$sid]);
        $cur = $cs->fetchColumn();
        if (!in_array($cur, ['accepted', 'rejected'])) {
            $pdo->prepare("UPDATE submissions SET submission_status='under_review', updated_at=NOW() WHERE submission_id=?")
                ->execute([$sid]);
        }

        try {
            $pdo->prepare("INSERT INTO submission_activity_log (submission_id, activity_type, activity_description, performed_by) VALUES (?,?,?,?)")
                ->execute([$sid, 'reviewer_assigned', "Reviewer ID $reviewer_id assigned to submission $sid", $_SESSION['user_id'] ?? 1]);
        } catch (PDOException $e) {}

        // ── SEND INVITATION EMAIL ──────────────────────────
        $emailSent = false;
        try {
            $emailStmt = $pdo->prepare("
                SELECT u.first_name, u.last_name, u.email,
                       j.name           AS journal_name,
                       mi.article_title AS title,
                       mi.abstract
                FROM reviewers rv
                JOIN users u        ON rv.user_id = u.user_id
                JOIN submissions s  ON s.submission_id = ?
                LEFT JOIN journals j         ON j.journal_id     = s.journal_id
                LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
                WHERE rv.id = ?
                LIMIT 1
            ");
            $emailStmt->execute([$sid, $reviewer_id]);
            $ed = $emailStmt->fetch(PDO::FETCH_ASSOC);

            if ($ed && !empty($ed['email'])) {
                $emailSent = sendReviewerInvitation(
                    $ed['email'],
                    trim(($ed['first_name'] ?? '') . ' ' . ($ed['last_name'] ?? '')),
                    [
                        'title'             => $ed['title']        ?? '',
                        'abstract'          => $ed['abstract']     ?? '',
                        'journal_name'      => $ed['journal_name'] ?? '',
                        'response_due_date' => $resp_due,
                        'review_due_date'   => $review_due,
                        'access_key'        => $access_key,
                        'submission_id'     => $sid,
                    ]
                );
            }
        } catch (Exception $emailEx) {
            error_log('Reviewer invitation email error: ' . $emailEx->getMessage());
        }
        // ── END EMAIL ──────────────────────────────────────

        $msg = 'Reviewer assigned successfully.';
        $msg .= $emailSent ? ' ✓ Invitation email sent.' : ' (Email not sent — check mail config.)';

        echo json_encode(['success' => true, 'message' => $msg, 'email_sent' => $emailSent]);

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ══════════════════════════════════════════════════════════
// POST: Create NEW reviewer + assign
// ══════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_reviewer'])) {
    header('Content-Type: application/json');
    try {
        $pdo->beginTransaction();

        $email      = trim($_POST['email']      ?? '');
        $first_name = trim($_POST['first_name'] ?? '');
        $last_name  = trim($_POST['last_name']  ?? '');
        $password   = $_POST['password'] ?? 'Reviewer@123';
        $resp_due   = $_POST['response_due_date'] ?: null;
        $review_due = $_POST['review_due_date']   ?: null;
        $rev_type   = $_POST['reviewer_type'] ?? 'anonymous_reviewer_anonymous_author';

        if (!$email || !$first_name || !$last_name) throw new Exception("Name and email are required.");
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) throw new Exception("Invalid email format.");

        $ec = $pdo->prepare("SELECT user_id FROM users WHERE email=?");
        $ec->execute([$email]);
        if ($ec->fetch()) throw new Exception("Email already exists in the system.");

        $username = strtolower($first_name . '.' . $last_name . rand(10, 99));
        $hash     = password_hash($password, PASSWORD_DEFAULT);

        $pdo->prepare("
            INSERT INTO users (email, username, password_hash, first_name, last_name, role, is_active, is_email_verified, created_at)
            VALUES (?, ?, ?, ?, ?, 'reviewer', 1, 1, NOW())
        ")->execute([$email, $username, $hash, $first_name, $last_name]);
        $user_id = (int)$pdo->lastInsertId();

        $pdo->prepare("
            INSERT INTO reviewers (user_id, max_reviews_per_period, preferred_review_duration_days, is_available, created_at)
            VALUES (?, 5, 21, 1, NOW())
        ")->execute([$user_id]);
        $reviewer_id = (int)$pdo->lastInsertId();

        do {
            $access_key = bin2hex(random_bytes(32));
            $kc = $pdo->prepare("SELECT id FROM review_assignments WHERE access_key=?");
            $kc->execute([$access_key]);
        } while ($kc->fetch());

        $pdo->prepare("
            INSERT INTO review_assignments
              (submission_id, reviewer_id, review_round, assignment_status,
               request_sent_date, response_due_date, review_due_date, reviewer_type, access_key)
            VALUES (?, ?, 1, 'request_sent', NOW(), ?, ?, ?, ?)
        ")->execute([$sid, $reviewer_id, $resp_due, $review_due, $rev_type, $access_key]);

        $cs = $pdo->prepare("SELECT submission_status FROM submissions WHERE submission_id=?");
        $cs->execute([$sid]);
        $cur = $cs->fetchColumn();
        if (!in_array($cur, ['accepted', 'rejected'])) {
            $pdo->prepare("UPDATE submissions SET submission_status='under_review', updated_at=NOW() WHERE submission_id=?")
                ->execute([$sid]);
        }

        try {
            $pdo->prepare("INSERT INTO submission_activity_log (submission_id, activity_type, activity_description, performed_by) VALUES (?,?,?,?)")
                ->execute([$sid, 'reviewer_created_assigned', "New reviewer $first_name $last_name created and assigned", $_SESSION['user_id'] ?? 1]);
        } catch (PDOException $e) {}

        $pdo->commit();

        // ── SEND INVITATION EMAIL (after commit) ───────────
        $emailSent = false;
        try {
            $mStmt = $pdo->prepare("
                SELECT mi.article_title AS title, mi.abstract,
                       j.name           AS journal_name
                FROM submissions s
                LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
                LEFT JOIN journals j         ON j.journal_id     = s.journal_id
                WHERE s.submission_id = ?
                LIMIT 1
            ");
            $mStmt->execute([$sid]);
            $md = $mStmt->fetch(PDO::FETCH_ASSOC);

            $emailSent = sendReviewerInvitation(
                $email,
                trim("$first_name $last_name"),
                [
                    'title'             => $md['title']        ?? '',
                    'abstract'          => $md['abstract']     ?? '',
                    'journal_name'      => $md['journal_name'] ?? '',
                    'response_due_date' => $resp_due,
                    'review_due_date'   => $review_due,
                    'access_key'        => $access_key,
                    'submission_id'     => $sid,
                ]
            );
        } catch (Exception $emailEx) {
            error_log('New reviewer invitation email error: ' . $emailEx->getMessage());
        }
        // ── END EMAIL ──────────────────────────────────────

        $msg  = "Reviewer $first_name $last_name created and assigned.";
        $msg .= $emailSent ? " ✓ Invitation email sent to $email." : " (Email not sent — check mail config.)";

        echo json_encode(['success' => true, 'message' => $msg, 'email_sent' => $emailSent]);

    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ══════════════════════════════════════════════════════════
// POST: Rate a reviewer
// ══════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['rate_reviewer'])) {
    header('Content-Type: application/json');
    try {
        $reviewer_id = (int)$_POST['reviewer_id'];
        $rating      = (float)$_POST['rating'];
        if ($rating < 1 || $rating > 5) throw new Exception("Rating must be 1–5.");
        $pdo->prepare("
            UPDATE review_assignments SET reviewer_rating = ?
            WHERE submission_id = ? AND reviewer_id = ? AND assignment_status = 'review_submitted'
        ")->execute([$rating, $sid, $reviewer_id]);
        $stmt = $pdo->prepare("SELECT AVG(reviewer_rating) FROM review_assignments WHERE reviewer_id = ? AND reviewer_rating IS NOT NULL");
        $stmt->execute([$reviewer_id]);
        $avg = (float)$stmt->fetchColumn();
        $cnt = $pdo->prepare("SELECT COUNT(*) FROM review_assignments WHERE reviewer_id = ? AND assignment_status = 'review_submitted'");
        $cnt->execute([$reviewer_id]);
        $total = (int)$cnt->fetchColumn();
        $pdo->prepare("UPDATE reviewers SET reviewer_rating = ?, total_reviews_completed = ? WHERE id = ?")->execute([round($avg,1), $total, $reviewer_id]);
        echo json_encode(['success' => true, 'message' => "Rating saved. New avg: " . number_format($avg,2) . "/5"]);
    } catch(Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ══════════════════════════════════════════════════════════
// POST: Save editorial decision
// ══════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_decision'])) {
    header('Content-Type: application/json');
    try {
        $pdo->beginTransaction();
        $decision       = $_POST['decision'] ?? '';
        $based_on       = !empty($_POST['based_on_review_id']) ? (int)$_POST['based_on_review_id'] : null;
        $originality    = $_POST['originality'] ?? null;
        $presentation   = $_POST['presentation'] ?? null;
        $applicability  = $_POST['applicability'] ?? null;
        $overall        = $_POST['overall_status'] ?? null;
        $strengths      = trim($_POST['strengths'] ?? '');
        $weaknesses     = trim($_POST['weaknesses'] ?? '');
        $suggestions    = trim($_POST['suggestions'] ?? '');
        $recommendation = trim($_POST['recommendation'] ?? '');
        $editor_comments= trim($_POST['editor_comments'] ?? '');
        $internal_notes = trim($_POST['internal_notes'] ?? '');
        $due_date       = $_POST['due_date'] ?: null;
        $review_file    = trim($_POST['review_file'] ?? '');
        if (!$decision) throw new Exception("Please select a decision.");
        $pdo->prepare("
            INSERT INTO editorial_decisions
            (submission_id, editor_id, based_on_review_id, decision, due_date, review_file,
             originality, presentation, applicability, overall_status,
             strengths, weaknesses, suggestions, recommendation, editor_comments, internal_notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ")->execute([$sid, $_SESSION['user_id'] ?? 1, $based_on, $decision, $due_date, $review_file ?: null,
                     $originality, $presentation, $applicability, $overall,
                     $strengths, $weaknesses, $suggestions, $recommendation, $editor_comments, $internal_notes]);
        $statusMap = ['accepted'=>'accepted','accepted_with_changes'=>'accepted','resubmit'=>'under_review','rejected'=>'rejected'];
        $newStatus = $statusMap[$decision] ?? 'under_review';
        $pdo->prepare("UPDATE submissions SET submission_status=?, updated_at=NOW() WHERE submission_id=?")->execute([$newStatus, $sid]);
        try {
            $pdo->prepare("INSERT INTO submission_activity_log (submission_id, activity_type, activity_description, performed_by) VALUES (?,?,?,?)")
                ->execute([$sid, 'editorial_decision', "Decision: $decision saved", $_SESSION['user_id'] ?? 1]);
        } catch(PDOException $e) {}
        $pdo->commit();
        echo json_encode(['success' => true, 'message' => "Editorial decision '$decision' saved successfully."]);
    } catch(Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ══════════════════════════════════════════════════════════
// POST: Update assignment status
// ══════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_assignment_status'])) {
    header('Content-Type: application/json');
    try {
        $assignment_id = (int)$_POST['assignment_id'];
        $new_status    = $_POST['new_status'] ?? '';
        $valid = ['request_sent','accepted','declined','cancelled','review_submitted'];
        if (!in_array($new_status, $valid)) throw new Exception("Invalid status.");
        $pdo->prepare("UPDATE review_assignments SET assignment_status=? WHERE id=? AND submission_id=?")
            ->execute([$new_status, $assignment_id, $sid]);
        echo json_encode(['success' => true, 'message' => "Status updated to $new_status."]);
    } catch(Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ══════════════════════════════════════════════════════════
// LOAD PAGE DATA
// ══════════════════════════════════════════════════════════
try {
    $stmt = $pdo->prepare("
        SELECT s.*, u.first_name, u.last_name, u.email AS author_email,
               j.name AS journal_name, mi.article_title, mi.abstract,
               at.name AS article_type_name
        FROM submissions s
        LEFT JOIN users u ON u.user_id = s.user_id
        LEFT JOIN journals j ON j.journal_id = s.journal_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        LEFT JOIN article_types at ON at.article_type_id = s.article_type_id
        WHERE s.submission_id = ?
    ");
    $stmt->execute([$sid]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$sub) { header('Location: submissions.php'); exit; }
} catch(PDOException $e) {
    die("Error loading submission: " . $e->getMessage());
}

$title      = $sub['article_title'] ?: '<<untitled>>';
$authorName = trim(($sub['first_name']??'') . ' ' . ($sub['last_name']??''));
$status     = $sub['submission_status'] ?? 'draft';

// ══════════════════════════════════════════════════════════
// FIX 3: Capture PHP_SELF once so JS can use the correct URL
// ══════════════════════════════════════════════════════════
$this_url = htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8');

$active_section = 'submissions';
function p($v) { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Review Management – Submission #<?= $sid ?></title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body{font-family:'Roboto',sans-serif;margin:0;height:100vh;overflow:hidden;background:#F1F5F9}
body.dark{background:#0F172A;color:#E2E8F0}
.sidebar{width:250px;background:#1E293B;color:white;transition:all .3s;height:100%;position:fixed;top:0;left:0;z-index:10;overflow-y:auto}
.sidebar.collapsed{width:70px}
.sidebar.collapsed .sidebar-title{display:none}
.content{margin-left:250px;transition:margin-left .3s;height:100vh;overflow-y:auto}
.content.collapsed-sidebar{margin-left:70px}
.nav-item{padding:10px 12px;cursor:pointer;transition:background .2s;display:flex;align-items:center}
.nav-item:hover{background:#334155}
.nav-item.active{background:#334155;border-left:3px solid #3B82F6}
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}
.sbadge{display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700}
.sbadge::before{content:'';width:6px;height:6px;border-radius:50%}
.sb-draft{background:#F1F5F9;color:#64748B}.sb-draft::before{background:#64748B}
.sb-submitted{background:#EFF6FF;color:#2563EB}.sb-submitted::before{background:#2563EB}
.sb-under_review{background:#FEF3C7;color:#D97706}.sb-under_review::before{background:#D97706}
.sb-accepted{background:#F0FDF4;color:#16A34A}.sb-accepted::before{background:#16A34A}
.sb-rejected{background:#FEF2F2;color:#DC2626}.sb-rejected::before{background:#DC2626}
.wf-tab{padding:10px 20px;border-bottom:3px solid transparent;cursor:pointer;font-size:13px;font-weight:600;color:#64748B;transition:all .2s;white-space:nowrap}
.wf-tab.active{border-bottom-color:#3B82F6;color:#1D4ED8}
.wf-panel{display:none}.wf-panel.active{display:block}
.card{background:white;border-radius:12px;border:1px solid #E2E8F0;overflow:hidden;margin-bottom:16px}
body.dark .card{background:#1E293B;border-color:#334155}
.card-hdr{padding:14px 18px;background:#F8FAFC;border-bottom:1px solid #E2E8F0;display:flex;align-items:center;justify-content:space-between}
body.dark .card-hdr{background:#0F172A;border-color:#334155}
.card-body{padding:18px}
.rev-card{border:1px solid #E2E8F0;border-radius:10px;padding:14px;cursor:pointer;transition:all .15s;background:#FAFAFA}
.rev-card:hover{border-color:#93C5FD;background:#EFF6FF}
.rev-card.selected{border-color:#2563EB;background:#EFF6FF;box-shadow:0 0 0 3px rgba(37,99,235,.15)}
body.dark .rev-card{background:#1E293B;border-color:#334155}
body.dark .rev-card.selected{background:#1E3A5F;border-color:#3B82F6}
.modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.5);backdrop-filter:blur(4px);z-index:50;display:none;align-items:center;justify-content:center;padding:16px}
.modal-bg.open{display:flex}
.modal-box{background:white;border-radius:16px;box-shadow:0 25px 60px rgba(0,0,0,.2);width:100%;overflow:hidden;display:flex;flex-direction:column}
body.dark .modal-box{background:#1E293B}
.inner-tab{padding:8px 16px;border-radius:8px;font-size:13px;font-weight:500;cursor:pointer;transition:all .15s;border:none;background:transparent;color:#64748B}
.inner-tab.active{background:#EFF6FF;color:#1D4ED8;font-weight:600}
.inp{width:100%;border:1px solid #D1D5DB;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;outline:none;transition:border-color .15s}
.inp:focus{border-color:#3B82F6;box-shadow:0 0 0 3px rgba(59,130,246,.1)}
body.dark .inp{background:#334155;border-color:#475569;color:#E2E8F0}
label.field-lbl{display:block;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#6B7280;margin-bottom:5px}
.star-btn{cursor:pointer;font-size:24px;color:#D1D5DB;transition:color .1s;line-height:1}
.star-btn.lit{color:#F59E0B}
.star-btn:hover{color:#F59E0B}
.asgn-row{display:flex;align-items:center;gap:10px;padding:12px;border:1px solid #E2E8F0;border-radius:10px;background:#FAFAFA;margin-bottom:8px}
body.dark .asgn-row{background:#1E293B;border-color:#334155}
.asgn-badge{padding:2px 8px;border-radius:20px;font-size:10px;font-weight:700}
.ab-request_sent{background:#DBEAFE;color:#1E40AF}
.ab-accepted{background:#D1FAE5;color:#065F46}
.ab-declined{background:#FEE2E2;color:#991B1B}
.ab-review_submitted{background:#E0F2FE;color:#0369A1}
.ab-cancelled{background:#F3F4F6;color:#374151}
.dec-accepted{background:#F0FDF4;color:#15803D;border:1px solid #86EFAC}
.dec-accepted_with_changes{background:#EFF6FF;color:#1D4ED8;border:1px solid #93C5FD}
.dec-resubmit{background:#FFF7ED;color:#C2410C;border:1px solid #FED7AA}
.dec-rejected{background:#FEF2F2;color:#DC2626;border:1px solid #FECACA}
.score-box{text-align:center;padding:14px;border-radius:10px;border:1px solid #E2E8F0}
.score-box .label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#9CA3AF;margin-bottom:4px}
.score-box .value{font-size:14px;font-weight:700;color:#1F2937}
.toast-box{position:fixed;bottom:24px;right:24px;z-index:9999;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px;box-shadow:0 8px 24px rgba(0,0,0,.15);transform:translateY(80px);opacity:0;transition:all .3s}
.toast-box.show{transform:translateY(0);opacity:1}
.toast-success{background:#ECFDF5;color:#065F46;border:1px solid #A7F3D0}
.toast-error{background:#FEF2F2;color:#991B1B;border:1px solid #FECACA}
::-webkit-scrollbar{width:5px;height:5px}
::-webkit-scrollbar-track{background:transparent}
::-webkit-scrollbar-thumb{background:#CBD5E1;border-radius:3px}
</style>
</head>
<body class="bg-gray-100">

<button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>

<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

  <div class="bg-white border-b border-gray-200 px-6 py-3 flex items-center justify-between sticky top-0 z-10 shadow-sm">
    <div class="flex items-center gap-3">
      <button onclick="toggleSidebar()" class="text-gray-400 hover:text-gray-600 hidden md:block">
        <i class="fas fa-bars"></i>
      </button>
      <a href="submission_view.php?id=<?= $sid ?>" class="text-gray-400 hover:text-blue-600 transition">
        <i class="fas fa-arrow-left text-sm"></i>
      </a>
      <div>
        <h1 class="text-base font-bold text-gray-800 flex items-center gap-2">
          <i class="fas fa-user-check text-purple-500 text-sm"></i>
          Review Management
          <span class="text-gray-300 font-normal">·</span>
          <span class="text-sm text-gray-500 font-normal">#<?= $sid ?></span>
        </h1>
        <p class="text-xs text-gray-400 truncate max-w-md mt-0.5"><?= p($title) ?></p>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <span class="sbadge sb-<?= $status ?>"><?= ucfirst(str_replace('_',' ',$status)) ?></span>
      <button onclick="openAssignModal()" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg text-sm font-semibold flex items-center gap-2 transition">
        <i class="fas fa-user-plus text-xs"></i> Assign Reviewer
      </button>
      <button id="darkModeToggle" class="text-gray-400 hover:text-gray-600 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
        <i class="fas fa-moon text-sm"></i>
      </button>
    </div>
  </div>

  <main class="p-5">
    <div class="grid grid-cols-1 xl:grid-cols-4 gap-5">

      <div class="xl:col-span-1 space-y-4">
        <div class="card">
          <div class="card-hdr">
            <span class="text-xs font-bold text-gray-500 uppercase tracking-wide">Submission Info</span>
          </div>
          <div class="card-body space-y-3">
            <div>
              <div class="text-xs text-gray-400 font-medium mb-1">Tracking Code</div>
              <div class="font-mono text-sm font-bold text-blue-600"><?= p($sub['tracking_code'] ?: 'N/A') ?></div>
            </div>
            <div>
              <div class="text-xs text-gray-400 font-medium mb-1">Journal</div>
              <div class="text-sm text-gray-700 font-medium"><?= p($sub['journal_name'] ?: '—') ?></div>
            </div>
            <div>
              <div class="text-xs text-gray-400 font-medium mb-1">Article Type</div>
              <div class="text-sm text-gray-700"><?= p($sub['article_type_name'] ?: '—') ?></div>
            </div>
            <div>
              <div class="text-xs text-gray-400 font-medium mb-1">Submitting Author</div>
              <div class="text-sm text-gray-700 font-medium"><?= p($authorName) ?></div>
              <div class="text-xs text-gray-400"><?= p($sub['author_email'] ?? '') ?></div>
            </div>
            <div>
              <div class="text-xs text-gray-400 font-medium mb-1">Created</div>
              <div class="text-sm text-gray-700"><?= date('d M Y', strtotime($sub['created_at'])) ?></div>
            </div>
          </div>
        </div>

        <div class="card">
          <div class="card-hdr">
            <span class="text-xs font-bold text-gray-500 uppercase tracking-wide">Quick Actions</span>
          </div>
          <div class="card-body space-y-2">
            <button onclick="openAssignModal()" class="w-full bg-purple-50 hover:bg-purple-100 text-purple-700 border border-purple-200 px-3 py-2 rounded-lg text-sm font-semibold flex items-center gap-2 transition">
              <i class="fas fa-user-plus text-xs"></i> Assign Reviewer
            </button>
            <button onclick="openDecisionForm()" class="w-full bg-green-50 hover:bg-green-100 text-green-700 border border-green-200 px-3 py-2 rounded-lg text-sm font-semibold flex items-center gap-2 transition">
              <i class="fas fa-gavel text-xs"></i> Editorial Decision
            </button>
            <a href="submission_view.php?id=<?= $sid ?>" class="w-full bg-blue-50 hover:bg-blue-100 text-blue-700 border border-blue-200 px-3 py-2 rounded-lg text-sm font-semibold flex items-center gap-2 transition block text-center">
              <i class="fas fa-file-alt text-xs"></i> Full Submission
            </a>
          </div>
        </div>

        <div class="card" id="statsCard">
          <div class="card-hdr">
            <span class="text-xs font-bold text-gray-500 uppercase tracking-wide">Review Stats</span>
            <button onclick="refreshStats()" class="text-gray-400 hover:text-blue-500 text-xs"><i class="fas fa-sync-alt"></i></button>
          </div>
          <div class="card-body" id="statsBody">
            <div class="text-center py-4 text-gray-400 text-xs"><i class="fas fa-spinner fa-spin mr-1"></i> Loading…</div>
          </div>
        </div>
      </div>

      <div class="xl:col-span-3">
        <div class="bg-white rounded-xl border border-gray-200 mb-5 overflow-hidden">
          <div class="flex border-b border-gray-200 overflow-x-auto">
            <button class="wf-tab active" onclick="switchTab('assignments')">
              <i class="fas fa-users mr-1.5 text-blue-400"></i>Assignments
              <span id="badgeAssignments" class="ml-1 bg-blue-100 text-blue-700 rounded-full text-xs px-1.5 py-0.5 hidden"></span>
            </button>
            <button class="wf-tab" onclick="switchTab('reviews')">
              <i class="fas fa-star mr-1.5 text-yellow-400"></i>Reviews
              <span id="badgeReviews" class="ml-1 bg-yellow-100 text-yellow-700 rounded-full text-xs px-1.5 py-0.5 hidden"></span>
            </button>
            <button class="wf-tab" onclick="switchTab('decision')">
              <i class="fas fa-gavel mr-1.5 text-green-500"></i>Editorial Decision
              <span id="badgeDecisions" class="ml-1 bg-green-100 text-green-700 rounded-full text-xs px-1.5 py-0.5 hidden"></span>
            </button>
          </div>

          <div class="wf-panel active p-5" id="panel-assignments">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-bold text-gray-800 flex items-center gap-2">
                <i class="fas fa-users text-blue-500"></i> Reviewer Assignments
              </h3>
              <button onclick="openAssignModal()" class="bg-purple-600 hover:bg-purple-700 text-white px-3 py-1.5 rounded-lg text-xs font-bold flex items-center gap-1 transition">
                <i class="fas fa-plus"></i> Add
              </button>
            </div>
            <div id="assignmentsList">
              <div class="text-center py-10 text-gray-400">
                <i class="fas fa-spinner fa-spin text-2xl mb-2 block"></i>
                <p class="text-sm">Loading assignments…</p>
              </div>
            </div>
          </div>

          <div class="wf-panel p-5" id="panel-reviews">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-bold text-gray-800 flex items-center gap-2">
                <i class="fas fa-star text-yellow-500"></i> Submitted Reviews
              </h3>
              <button onclick="refreshReviews()" class="text-gray-400 hover:text-blue-500 text-sm border border-gray-200 px-3 py-1.5 rounded-lg">
                <i class="fas fa-sync-alt mr-1"></i> Refresh
              </button>
            </div>
            <div id="reviewsList">
              <div class="text-center py-10 text-gray-400">
                <i class="fas fa-spinner fa-spin text-2xl mb-2 block"></i>
                <p class="text-sm">Loading reviews…</p>
              </div>
            </div>
          </div>

          <div class="wf-panel p-5" id="panel-decision">
            <div class="mb-6">
              <div class="flex items-center justify-between mb-3">
                <h3 class="font-bold text-gray-800 flex items-center gap-2">
                  <i class="fas fa-history text-indigo-500"></i> Saved Decisions
                </h3>
                <button onclick="refreshDecisions()" class="text-gray-400 hover:text-blue-500 text-sm border border-gray-200 px-3 py-1.5 rounded-lg">
                  <i class="fas fa-sync-alt mr-1"></i> Refresh
                </button>
              </div>
              <div id="decisionsList">
                <div class="text-center py-6 text-gray-400"><i class="fas fa-spinner fa-spin"></i></div>
              </div>
            </div>

            <hr class="border-gray-200 mb-6">

            <h3 class="font-bold text-gray-800 flex items-center gap-2 mb-4">
              <i class="fas fa-gavel text-green-500"></i> New Editorial Decision
            </h3>
            <form id="decisionForm" class="space-y-5">
              <div>
                <label class="field-lbl">Prefill from Submitted Review (Optional)</label>
                <select id="prefillReviewSel" class="inp" onchange="prefillFromReview(this.value)">
                  <option value="">— Start from scratch —</option>
                </select>
                <p class="text-xs text-gray-400 mt-1">Select a review to auto-fill scores and feedback fields.</p>
              </div>

              <div class="grid grid-cols-2 gap-4">
                <div>
                  <label class="field-lbl">Final Decision <span class="text-red-500">*</span></label>
                  <select name="decision" id="decisionSel" class="inp" required>
                    <option value="">— Select Decision —</option>
                    <option value="accepted">✓ Accepted</option>
                    <option value="accepted_with_changes">✓ Accepted with Changes</option>
                    <option value="resubmit">↻ Resubmit for Review</option>
                    <option value="rejected">✗ Rejected</option>
                  </select>
                </div>
                <div>
                  <label class="field-lbl">Response Due Date <span class="text-red-500">*</span></label>
                  <input type="date" name="due_date" id="dueDateInp" class="inp" required>
                </div>
              </div>

              <div>
                <label class="field-lbl">Evaluation Scores</label>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <?php foreach(['originality'=>'Originality','presentation'=>'Presentation','applicability'=>'Applicability','overall_status'=>'Overall Status'] as $f=>$l): ?>
                  <div>
                    <div class="text-xs text-gray-500 mb-1"><?= $l ?></div>
                    <select name="<?= $f ?>" id="dec_<?= $f ?>" class="inp text-xs">
                      <option value="">—</option>
                      <?php foreach(['Outstanding','Excellent','Very Good','Good','Fair','Poor'] as $o): ?>
                      <option value="<?= $o ?>"><?= $o ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>

              <div class="space-y-4">
                <div>
                  <label class="field-lbl"><i class="fas fa-check-circle text-green-500 mr-1"></i>Strengths</label>
                  <textarea name="strengths" id="dec_strengths" rows="3" class="inp" placeholder="Describe the strengths…"></textarea>
                </div>
                <div>
                  <label class="field-lbl"><i class="fas fa-exclamation-triangle text-red-500 mr-1"></i>Weaknesses</label>
                  <textarea name="weaknesses" id="dec_weaknesses" rows="3" class="inp" placeholder="Areas for improvement…"></textarea>
                </div>
                <div>
                  <label class="field-lbl"><i class="fas fa-lightbulb text-yellow-500 mr-1"></i>Suggestions</label>
                  <textarea name="suggestions" id="dec_suggestions" rows="3" class="inp" placeholder="Specific suggestions…"></textarea>
                </div>
                <div>
                  <label class="field-lbl"><i class="fas fa-thumbs-up text-blue-500 mr-1"></i>Final Recommendation</label>
                  <textarea name="recommendation" id="dec_recommendation" rows="2" class="inp" placeholder="Summarize your recommendation…"></textarea>
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 border-t border-gray-100">
                <div>
                  <label class="field-lbl"><i class="fas fa-comment text-purple-500 mr-1"></i>Comments to Author</label>
                  <textarea name="editor_comments" id="dec_editor_comments" rows="3" class="inp" placeholder="Will be visible to author…"></textarea>
                </div>
                <div>
                  <label class="field-lbl"><i class="fas fa-lock text-gray-500 mr-1"></i>Internal Notes (Confidential)</label>
                  <textarea name="internal_notes" rows="3" class="inp" placeholder="Admin use only, not sent to author…"></textarea>
                </div>
              </div>

              <input type="hidden" name="based_on_review_id" id="basedOnReviewId">
              <input type="hidden" name="save_decision" value="1">

              <div class="flex justify-end gap-3 pt-3 border-t border-gray-100">
                <button type="button" onclick="resetDecisionForm()" class="border border-gray-300 text-gray-600 hover:bg-gray-50 px-4 py-2 rounded-lg text-sm font-medium transition">
                  <i class="fas fa-undo mr-1"></i> Reset
                </button>
                <button type="submit" class="bg-green-600 hover:bg-green-700 text-white px-6 py-2 rounded-lg text-sm font-bold flex items-center gap-2 transition">
                  <i class="fas fa-save"></i> Save Decision
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </main>
</div>

<!-- ASSIGN REVIEWER MODAL -->
<div id="assignModal" class="modal-bg">
  <div class="modal-box" style="max-width:900px;max-height:90vh">
    <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between flex-shrink-0">
      <div class="flex items-center gap-3">
        <div class="w-9 h-9 bg-purple-100 rounded-xl flex items-center justify-center">
          <i class="fas fa-user-check text-purple-600 text-sm"></i>
        </div>
        <div>
          <h2 class="font-bold text-gray-800">Assign Reviewer</h2>
          <p class="text-xs text-gray-400 mt-0.5"><?= p(mb_strimwidth($title,0,55,'…')) ?></p>
        </div>
      </div>
      <button onclick="closeAssignModal()" class="text-gray-400 hover:text-gray-600 w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100">
        <i class="fas fa-times"></i>
      </button>
    </div>

    <div class="px-5 pt-3 pb-0 border-b border-gray-100 flex gap-1 flex-shrink-0">
      <button class="inner-tab active" onclick="switchInnerTab('existing')" id="itab-existing">
        <i class="fas fa-users mr-1 text-blue-500 text-xs"></i> Select Existing
      </button>
      <button class="inner-tab" onclick="switchInnerTab('create')" id="itab-create">
        <i class="fas fa-user-plus mr-1 text-green-500 text-xs"></i> Create New
      </button>
    </div>

    <div class="flex-1 overflow-y-auto p-5">
      <div id="ipanel-existing">
        <div class="flex flex-wrap gap-2 mb-4">
          <div class="relative flex-1 min-w-[160px]">
            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
            <input type="text" id="revSearchInp" placeholder="Search name, email…" oninput="filterRevList()" class="inp pl-8 py-2 text-sm">
          </div>
          <select id="revFilterAvail" onchange="filterRevList()" class="inp py-2 text-sm" style="width:130px">
            <option value="">Availability</option>
            <option value="1">Available</option>
            <option value="0">Busy</option>
          </select>
          <div class="flex items-center gap-2 text-sm text-gray-500">
            <span class="whitespace-nowrap">Rating ≥</span>
            <input type="range" id="revFilterRating" min="0" max="5" step="0.5" value="0" oninput="document.getElementById('rvRatVal').textContent=this.value;filterRevList()" class="w-20">
            <span id="rvRatVal" class="font-bold text-gray-700 w-5">0</span>
          </div>
        </div>

        <div id="revListWrap" class="space-y-2 max-h-56 overflow-y-auto mb-4">
          <div class="text-center py-6 text-gray-400 text-sm">
            <i class="fas fa-spinner fa-spin text-xl mb-2 block"></i>Loading reviewers…
          </div>
        </div>

        <div id="existingAssignForm" class="hidden border-t border-gray-100 pt-4">
          <div class="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-4">
            <div class="text-xs font-bold text-blue-500 uppercase tracking-wide mb-1">Selected Reviewer</div>
            <div class="font-bold text-gray-800" id="selRevName">—</div>
            <div class="text-xs text-gray-500" id="selRevEmail">—</div>
          </div>
          <div class="grid grid-cols-2 gap-4 mb-4">
            <div>
              <label class="field-lbl">Response Due Date</label>
              <input type="date" id="exRespDue" class="inp">
            </div>
            <div>
              <label class="field-lbl">Review Due Date</label>
              <input type="date" id="exRevDue" class="inp">
            </div>
          </div>
          <div class="mb-4">
            <label class="field-lbl">Review Type</label>
            <select id="exRevType" class="inp">
              <option value="anonymous_reviewer_anonymous_author">Anonymous Reviewer, Anonymous Author</option>
              <option value="anonymous_reviewer_known_author">Anonymous Reviewer, Known Author</option>
              <option value="known_reviewer_anonymous_author">Known Reviewer, Anonymous Author</option>
              <option value="open_review">Open Review</option>
            </select>
          </div>
          <button onclick="submitAssignment()" id="submitAssignBtn"
                  class="w-full bg-purple-600 hover:bg-purple-700 text-white py-2.5 rounded-xl font-bold flex items-center justify-center gap-2 transition">
            <i class="fas fa-user-check"></i> Assign Reviewer
          </button>
        </div>
      </div>

      <div id="ipanel-create" class="hidden space-y-4">
        <div class="bg-green-50 border border-green-200 rounded-xl p-3 text-xs text-green-700 flex items-start gap-2">
          <i class="fas fa-info-circle mt-0.5 flex-shrink-0"></i>
          A new reviewer account will be created and immediately assigned to this submission.
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="field-lbl">First Name <span class="text-red-500">*</span></label>
            <input type="text" id="newFirst" class="inp" placeholder="John">
          </div>
          <div>
            <label class="field-lbl">Last Name <span class="text-red-500">*</span></label>
            <input type="text" id="newLast" class="inp" placeholder="Doe">
          </div>
        </div>
        <div>
          <label class="field-lbl">Email <span class="text-red-500">*</span></label>
          <input type="email" id="newEmail" class="inp" placeholder="reviewer@university.edu">
        </div>
        <div>
          <label class="field-lbl">Password <span class="text-gray-400 font-normal">(default: Reviewer@123)</span></label>
          <input type="password" id="newPass" class="inp" placeholder="Reviewer@123" value="Reviewer@123">
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="field-lbl">Response Due Date</label>
            <input type="date" id="newRespDue" class="inp">
          </div>
          <div>
            <label class="field-lbl">Review Due Date</label>
            <input type="date" id="newRevDue" class="inp">
          </div>
        </div>
        <div>
          <label class="field-lbl">Review Type</label>
          <select id="newRevType" class="inp">
            <option value="anonymous_reviewer_anonymous_author">Anonymous Reviewer, Anonymous Author</option>
            <option value="anonymous_reviewer_known_author">Anonymous Reviewer, Known Author</option>
            <option value="known_reviewer_anonymous_author">Known Reviewer, Anonymous Author</option>
            <option value="open_review">Open Review</option>
          </select>
        </div>
        <button onclick="submitCreateReviewer()" id="createRevBtn"
                class="w-full bg-green-600 hover:bg-green-700 text-white py-2.5 rounded-xl font-bold flex items-center justify-center gap-2 transition">
          <i class="fas fa-user-plus"></i> Create & Assign
        </button>
      </div>
    </div>
  </div>
</div>

<!-- RATING MODAL -->
<div id="ratingModal" class="modal-bg">
  <div class="modal-box" style="max-width:420px">
    <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
      <h2 class="font-bold text-gray-800 flex items-center gap-2">
        <i class="fas fa-star text-yellow-500"></i> Rate Reviewer
      </h2>
      <button onclick="closeRatingModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
    </div>
    <div class="p-6">
      <p class="text-sm text-gray-600 mb-1">Reviewer:</p>
      <p class="font-bold text-gray-800 mb-5" id="ratingRevName">—</p>
      <div class="flex items-center justify-center gap-2 mb-6">
        <span class="star-btn" data-v="1" onclick="setRating(1)">★</span>
        <span class="star-btn" data-v="2" onclick="setRating(2)">★</span>
        <span class="star-btn" data-v="3" onclick="setRating(3)">★</span>
        <span class="star-btn" data-v="4" onclick="setRating(4)">★</span>
        <span class="star-btn" data-v="5" onclick="setRating(5)">★</span>
        <span class="text-lg font-bold text-gray-700 ml-2" id="ratingDisplay">0 / 5</span>
      </div>
      <input type="hidden" id="ratingValue" value="0">
      <input type="hidden" id="ratingRevId" value="">
      <div class="flex gap-3">
        <button onclick="closeRatingModal()" class="flex-1 border border-gray-300 text-gray-600 py-2.5 rounded-xl font-semibold text-sm transition hover:bg-gray-50">Cancel</button>
        <button onclick="submitRating()" id="submitRatingBtn" class="flex-1 bg-yellow-500 hover:bg-yellow-600 text-white py-2.5 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition">
          <i class="fas fa-check"></i> Submit Rating
        </button>
      </div>
    </div>
  </div>
</div>

<div id="toastEl" class="toast-box"><i id="toastIcon" class="fas fa-check-circle"></i><span id="toastMsg"></span></div>

<script>
const SUB_ID = <?= $sid ?>;
// ══════════════════════════════════════════════════════════
// FIX 3: THIS_URL always points to this file, regardless of name
// All fetch() calls use THIS_URL instead of hardcoded filename
// ══════════════════════════════════════════════════════════
const THIS_URL = '<?= $this_url ?>';

let allReviewers = [];
let selectedRevId = null;
let selectedRevName = '';

function toggleMobileSidebar(){ document.getElementById('sidebar')?.classList.toggle('mobile-open'); }
let sc=false;
function toggleSidebar(){
  sc=!sc;
  document.getElementById('sidebar')?.classList.toggle('collapsed',sc);
  document.getElementById('content')?.classList.toggle('collapsed-sidebar',sc);
}
document.getElementById('darkModeToggle').addEventListener('click',function(){
  document.body.classList.toggle('dark');
  this.querySelector('i').classList.toggle('fa-moon');
  this.querySelector('i').classList.toggle('fa-sun');
  localStorage.setItem('darkMode',document.body.classList.contains('dark')?'on':'off');
});
if(localStorage.getItem('darkMode')==='on'){
  document.body.classList.add('dark');
  document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
}

function toast(msg,type='success'){
  const el=document.getElementById('toastEl');
  document.getElementById('toastMsg').textContent=msg;
  document.getElementById('toastIcon').className='fas '+(type==='success'?'fa-check-circle':'fa-exclamation-circle');
  el.className='toast-box show toast-'+type;
  setTimeout(()=>el.classList.remove('show'),3500);
}

function switchTab(name){
  document.querySelectorAll('.wf-tab').forEach(t=>{
    t.classList.toggle('active', t.getAttribute('onclick').includes("'"+name+"'"));
  });
  document.querySelectorAll('.wf-panel').forEach(p=>p.classList.remove('active'));
  document.getElementById('panel-'+name)?.classList.add('active');
  if(name==='reviews') loadReviews();
  if(name==='decision') { loadDecisions(); loadReviewsForPrefill(); }
}

function openAssignModal(){
  document.getElementById('assignModal').classList.add('open');
  switchInnerTab('existing');
  setDefaultDates();
  if(allReviewers.length===0) loadReviewers();
}
function closeAssignModal(){ document.getElementById('assignModal').classList.remove('open'); }
document.getElementById('assignModal').addEventListener('click',function(e){ if(e.target===this) closeAssignModal(); });

function switchInnerTab(t){
  ['existing','create'].forEach(n=>{
    document.getElementById('itab-'+n).classList.toggle('active',n===t);
    document.getElementById('ipanel-'+n).classList.toggle('hidden',n!==t);
  });
  if(t==='existing'&&allReviewers.length===0) loadReviewers();
}

function setDefaultDates(){
  const today=new Date();
  const resp=new Date(today); resp.setDate(resp.getDate()+3);
  const rev=new Date(today); rev.setDate(rev.getDate()+21);
  const fmt=d=>d.toISOString().split('T')[0];
  ['exRespDue','newRespDue'].forEach(id=>{ const el=document.getElementById(id); if(el) el.value=fmt(resp); });
  ['exRevDue','newRevDue'].forEach(id=>{ const el=document.getElementById(id); if(el) el.value=fmt(rev); });
}

async function loadReviewers(){
  document.getElementById('revListWrap').innerHTML='<div class="text-center py-6 text-gray-400 text-sm"><i class="fas fa-spinner fa-spin text-xl mb-2 block"></i>Loading…</div>';
  try{
    // ── FIX 3 applied: THIS_URL instead of hardcoded 'submission_review.php'
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}&ajax=get_reviewers`);
    const d=await r.json();
    if(!d.success) throw new Error(d.error);
    allReviewers=d.reviewers||[];
    renderRevList(allReviewers);
  }catch(e){
    document.getElementById('revListWrap').innerHTML=`<div class="text-center py-4 text-red-400 text-sm">${e.message}</div>`;
  }
}

function renderRevList(list){
  const wrap=document.getElementById('revListWrap');
  if(!list.length){
    wrap.innerHTML='<div class="text-center py-8 text-gray-400 text-sm"><i class="fas fa-users text-3xl opacity-30 block mb-2"></i>No reviewers found. Try creating one.</div>';
    return;
  }
  wrap.innerHTML=list.map(r=>{
    const name=((r.title||'')+' '+(r.first_name||'')+' '+(r.last_name||'')).trim();
    const rating=parseFloat(r.reviewer_rating||0);
    const stars='★'.repeat(Math.floor(rating))+'☆'.repeat(5-Math.floor(rating));
    const avail=r.is_available==1;
    const sel=selectedRevId===r.reviewer_id;
    return `<div class="rev-card ${sel?'selected':''}"
          onclick="selectReviewer(${r.reviewer_id},'${esc(name)}','${esc(r.email||'')}')"
          data-name="${(name).toLowerCase()}" data-email="${(r.email||'').toLowerCase()}"
          data-avail="${r.is_available}" data-rating="${rating}">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-3">
          <div class="w-9 h-9 rounded-full bg-purple-100 text-purple-700 flex items-center justify-center text-xs font-bold flex-shrink-0">
            ${(r.first_name||'?')[0]}${(r.last_name||'?')[0]}
          </div>
          <div>
            <div class="font-semibold text-gray-800 text-sm">${hesc(name)}</div>
            <div class="text-xs text-gray-400">${hesc(r.email||'—')}</div>
            ${r.affiliation_name?`<div class="text-xs text-gray-400 truncate" style="max-width:180px">${hesc(r.affiliation_name)}${r.country?', '+hesc(r.country):''}</div>`:''}
          </div>
        </div>
        <div class="flex flex-col items-end gap-1">
          <span class="text-xs font-bold px-2 py-0.5 rounded-full ${avail?'bg-green-100 text-green-700':'bg-gray-100 text-gray-500'}">${avail?'Available':'Busy'}</span>
          <span class="text-yellow-500 text-xs">${stars} <span class="text-gray-400">${rating.toFixed(1)}</span></span>
          <span class="text-xs text-gray-400">${r.total_reviews_completed||0} reviews</span>
        </div>
      </div>
    </div>`;
  }).join('');
}

function filterRevList(){
  const q=(document.getElementById('revSearchInp').value||'').toLowerCase();
  const avail=document.getElementById('revFilterAvail').value;
  const minR=parseFloat(document.getElementById('revFilterRating').value||0);
  const f=allReviewers.filter(r=>{
    const name=((r.first_name||'')+' '+(r.last_name||'')).toLowerCase();
    if(q && !name.includes(q) && !(r.email||'').toLowerCase().includes(q)) return false;
    if(avail!=='' && String(r.is_available)!==avail) return false;
    if(parseFloat(r.reviewer_rating||0)<minR) return false;
    return true;
  });
  renderRevList(f);
}

function selectReviewer(id, name, email){
  selectedRevId=id;
  selectedRevName=name;
  document.getElementById('selRevName').textContent=name;
  document.getElementById('selRevEmail').textContent=email;
  document.getElementById('existingAssignForm').classList.remove('hidden');
  filterRevList();
}

async function submitAssignment(){
  if(!selectedRevId){ toast('Please select a reviewer first.','error'); return; }
  const btn=document.getElementById('submitAssignBtn');
  btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> Assigning…';
  try{
    const fd=new FormData();
    fd.append('assign_reviewer','1');
    fd.append('reviewer_id',selectedRevId);
    fd.append('response_due_date',document.getElementById('exRespDue').value);
    fd.append('review_due_date',document.getElementById('exRevDue').value);
    fd.append('reviewer_type',document.getElementById('exRevType').value);
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}`,{method:'POST',body:fd});
    const d=await r.json();
    if(!d.success) throw new Error(d.message);
    toast(d.message);
    closeAssignModal();
    loadAssignments();
    refreshStats();
    selectedRevId=null;
    document.getElementById('existingAssignForm').classList.add('hidden');
  }catch(e){ toast(e.message,'error'); }
  finally{ btn.disabled=false; btn.innerHTML='<i class="fas fa-user-check"></i> Assign Reviewer'; }
}

async function submitCreateReviewer(){
  const btn=document.getElementById('createRevBtn');
  const first=document.getElementById('newFirst').value.trim();
  const last=document.getElementById('newLast').value.trim();
  const email=document.getElementById('newEmail').value.trim();
  const pass=document.getElementById('newPass').value||'Reviewer@123';
  if(!first||!last||!email){ toast('Name and email are required.','error'); return; }
  btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> Creating…';
  try{
    const fd=new FormData();
    fd.append('create_reviewer','1');
    fd.append('first_name',first); fd.append('last_name',last);
    fd.append('email',email); fd.append('password',pass);
    fd.append('response_due_date',document.getElementById('newRespDue').value);
    fd.append('review_due_date',document.getElementById('newRevDue').value);
    fd.append('reviewer_type',document.getElementById('newRevType').value);
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}`,{method:'POST',body:fd});
    const d=await r.json();
    if(!d.success) throw new Error(d.message);
    toast(d.message);
    closeAssignModal();
    allReviewers=[];
    loadAssignments();
    refreshStats();
    ['newFirst','newLast','newEmail'].forEach(i=>document.getElementById(i).value='');
    document.getElementById('newPass').value='Reviewer@123';
  }catch(e){ toast(e.message,'error'); }
  finally{ btn.disabled=false; btn.innerHTML='<i class="fas fa-user-plus"></i> Create & Assign'; }
}

async function loadAssignments(){
  document.getElementById('assignmentsList').innerHTML=
    '<div class="text-center py-8 text-gray-400 text-sm"><i class="fas fa-spinner fa-spin text-xl mb-2 block"></i>Loading…</div>';
  try{
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}&ajax=get_assignments&sub_id=${SUB_ID}`);
    const d=await r.json();
    if(!d.success) throw new Error(d.error);
    const asgns=d.assignments||[];
    const badge=document.getElementById('badgeAssignments');
    if(asgns.length){ badge.textContent=asgns.length; badge.classList.remove('hidden'); }
    else badge.classList.add('hidden');
    if(!asgns.length){
      document.getElementById('assignmentsList').innerHTML=
        '<div class="text-center py-10 text-gray-400"><i class="fas fa-inbox text-3xl opacity-30 block mb-2"></i><p class="text-sm">No reviewers assigned yet.</p><button onclick="openAssignModal()" class="mt-3 bg-purple-600 text-white px-4 py-2 rounded-lg text-sm font-semibold">Assign First Reviewer</button></div>';
      return;
    }
    const statusLabels={request_sent:'Request Sent',accepted:'Accepted',declined:'Declined',cancelled:'Cancelled',review_submitted:'Review Submitted'};
    document.getElementById('assignmentsList').innerHTML=asgns.map(a=>{
      const name=((a.title||'')+' '+(a.first_name||'')+' '+(a.last_name||'')).trim();
      const st=a.assignment_status||'request_sent';
      const rating=a.reviewer_rating;
      const avgRating=parseFloat(a.reviewer_avg_rating||0);
      return `<div class="asgn-row">
        <div class="w-9 h-9 rounded-full bg-purple-100 text-purple-700 flex items-center justify-center text-xs font-bold flex-shrink-0">
          ${(a.first_name||'?')[0]}${(a.last_name||'?')[0]}
        </div>
        <div class="flex-1 min-w-0">
          <div class="flex items-center gap-2 flex-wrap">
            <span class="font-semibold text-gray-800 text-sm">${hesc(name)}</span>
            <span class="asgn-badge ab-${st}">${statusLabels[st]||st}</span>
            ${a.reviewer_type!=='anonymous_reviewer_anonymous_author'?`<span class="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">${a.reviewer_type.replace(/_/g,' ')}</span>`:''}
          </div>
          <div class="text-xs text-gray-400 mt-0.5">${hesc(a.email||'—')}</div>
          <div class="flex items-center gap-3 mt-1 text-xs text-gray-400 flex-wrap">
            ${a.response_due_date?`<span><i class="fas fa-reply text-[10px] mr-1"></i>Resp: ${a.response_due_date}</span>`:''}
            ${a.review_due_date?`<span><i class="fas fa-calendar text-[10px] mr-1"></i>Due: ${a.review_due_date}</span>`:''}
            ${avgRating>0?`<span class="text-yellow-500">★ ${avgRating.toFixed(1)} avg</span>`:''}
          </div>
        </div>
        <div class="flex flex-col items-end gap-2">
          <select onchange="updateAssignmentStatus(${a.id}, this.value)" class="text-xs border border-gray-200 rounded-lg px-2 py-1 text-gray-600 focus:outline-none focus:ring-1 focus:ring-blue-400">
            ${['request_sent','accepted','declined','cancelled','review_submitted'].map(s=>
              `<option value="${s}" ${s===st?'selected':''}>${statusLabels[s]}</option>`
            ).join('')}
          </select>
          ${st==='review_submitted'
            ? (rating!==null && rating!==undefined
                ? `<div class="text-yellow-500 text-xs font-bold">★ ${parseFloat(rating).toFixed(1)} / 5 <span class="text-gray-400 font-normal">rated</span></div>`
                : `<button onclick="openRatingModal(${a.reviewer_id},'${esc(name)}')" class="bg-yellow-500 hover:bg-yellow-600 text-white text-xs px-3 py-1.5 rounded-lg font-bold flex items-center gap-1 transition"><i class="fas fa-star text-xs"></i> Rate</button>`)
            : `<span class="text-xs text-gray-300">Not submitted</span>`
          }
        </div>
      </div>`;
    }).join('');
  }catch(e){
    document.getElementById('assignmentsList').innerHTML=`<div class="text-center py-6 text-red-400 text-sm">${e.message}</div>`;
  }
}

async function updateAssignmentStatus(assignId, newStatus){
  try{
    const fd=new FormData();
    fd.append('update_assignment_status','1');
    fd.append('assignment_id',assignId);
    fd.append('new_status',newStatus);
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}`,{method:'POST',body:fd});
    const d=await r.json();
    if(!d.success) throw new Error(d.message);
    toast(d.message);
    loadAssignments();
    refreshStats();
  }catch(e){ toast(e.message,'error'); }
}

async function loadReviews(){
  document.getElementById('reviewsList').innerHTML=
    '<div class="text-center py-8 text-gray-400 text-sm"><i class="fas fa-spinner fa-spin text-xl mb-2 block"></i>Loading reviews…</div>';
  try{
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}&ajax=get_reviews&sub_id=${SUB_ID}`);
    const d=await r.json();
    if(!d.success) throw new Error(d.error);
    const reviews=d.reviews||[];
    const badge=document.getElementById('badgeReviews');
    if(reviews.length){ badge.textContent=reviews.length; badge.classList.remove('hidden'); }
    else badge.classList.add('hidden');
    if(!reviews.length){
      document.getElementById('reviewsList').innerHTML=
        '<div class="text-center py-10 text-gray-400"><i class="fas fa-star text-3xl opacity-30 block mb-2"></i><p class="text-sm">No reviews submitted yet.</p></div>';
      return;
    }
    document.getElementById('reviewsList').innerHTML=reviews.map(rv=>renderReviewCard(rv)).join('');
  }catch(e){
    document.getElementById('reviewsList').innerHTML=`<div class="text-center py-6 text-red-400 text-sm">${e.message}</div>`;
  }
}

function renderReviewCard(rv){
  const name=((rv.title||'')+' '+(rv.first_name||'')+' '+(rv.last_name||'')).trim();
  const rating=rv.admin_rating;
  const scoreMap={Outstanding:'bg-green-100 text-green-700',Excellent:'bg-blue-100 text-blue-700','Very Good':'bg-teal-100 text-teal-700',Good:'bg-yellow-100 text-yellow-700',Fair:'bg-orange-100 text-orange-700',Poor:'bg-red-100 text-red-700'};
  const scoreBadge=v=>v?`<span class="text-xs font-bold px-2 py-0.5 rounded ${scoreMap[v]||'bg-gray-100 text-gray-600'}">${hesc(v)}</span>`:'<span class="text-xs text-gray-300">—</span>';
  const recColors={'Accepted':'text-green-600','Accepted with Changes':'text-blue-600','Resubmit':'text-orange-600','Rejected':'text-red-600'};
  const recColor=Object.entries(recColors).find(([k])=>rv.recommendation&&rv.recommendation.toLowerCase().includes(k.toLowerCase()));
  return `<div class="card mb-4">
    <div class="card-hdr">
      <div class="flex items-center gap-3">
        <div class="w-9 h-9 rounded-full bg-yellow-100 text-yellow-700 flex items-center justify-center text-sm font-bold">
          ${(rv.first_name||'?')[0]}${(rv.last_name||'?')[0]}
        </div>
        <div>
          <div class="font-bold text-gray-800 text-sm">${hesc(name)}</div>
          <div class="text-xs text-gray-400">${hesc(rv.email||'—')}</div>
          ${rv.affiliation_name?`<div class="text-xs text-gray-400">${hesc(rv.affiliation_name)}${rv.country?', '+hesc(rv.country):''}</div>`:''}
        </div>
      </div>
      <div class="flex flex-col items-end gap-1">
        <span class="text-xs text-gray-400">${rv.reviewed_at?new Date(rv.reviewed_at).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'}):''}</span>
        ${rating?`<span class="text-yellow-500 font-bold text-sm">★ ${parseFloat(rating).toFixed(1)}<span class="text-gray-400 font-normal text-xs">/5</span></span>`:
          `<button onclick="openRatingModal(${rv.reviewer_id},'${esc(name)}')" class="bg-yellow-500 hover:bg-yellow-600 text-white text-xs px-2 py-1 rounded-lg font-bold"><i class="fas fa-star text-xs"></i> Rate</button>`}
      </div>
    </div>
    <div class="card-body">
      <div class="grid grid-cols-4 gap-3 mb-5">
        <div class="score-box"><div class="label">Originality</div><div>${scoreBadge(rv.originality)}</div></div>
        <div class="score-box"><div class="label">Presentation</div><div>${scoreBadge(rv.presentation)}</div></div>
        <div class="score-box"><div class="label">Applicability</div><div>${scoreBadge(rv.applicability)}</div></div>
        <div class="score-box"><div class="label">Overall</div><div>${scoreBadge(rv.overall_status)}</div></div>
      </div>
      ${rv.recommendation?`<div class="bg-blue-50 border-l-4 border-blue-400 rounded-r-lg p-3 mb-4">
        <div class="text-xs font-bold text-blue-400 uppercase tracking-wide mb-1">Final Recommendation</div>
        <div class="font-bold text-sm ${recColor?recColor[1]:'text-gray-800'}">${hesc(rv.recommendation)}</div>
      </div>`:''}
      <div class="space-y-3">
        ${rv.strengths?`<div>
          <div class="text-xs font-bold uppercase tracking-wide text-green-600 mb-1"><i class="fas fa-check-circle mr-1"></i>Strengths</div>
          <div class="bg-green-50 border border-green-100 rounded-lg p-3 text-sm text-gray-700 whitespace-pre-wrap leading-relaxed max-h-32 overflow-y-auto">${hesc(rv.strengths)}</div>
        </div>`:''}
        ${rv.weaknesses?`<div>
          <div class="text-xs font-bold uppercase tracking-wide text-red-500 mb-1"><i class="fas fa-exclamation-triangle mr-1"></i>Weaknesses</div>
          <div class="bg-red-50 border border-red-100 rounded-lg p-3 text-sm text-gray-700 whitespace-pre-wrap leading-relaxed max-h-32 overflow-y-auto">${hesc(rv.weaknesses)}</div>
        </div>`:''}
        ${rv.suggestions?`<div>
          <div class="text-xs font-bold uppercase tracking-wide text-yellow-600 mb-1"><i class="fas fa-lightbulb mr-1"></i>Suggestions</div>
          <div class="bg-yellow-50 border border-yellow-100 rounded-lg p-3 text-sm text-gray-700 whitespace-pre-wrap leading-relaxed max-h-32 overflow-y-auto">${hesc(rv.suggestions)}</div>
        </div>`:''}
        ${rv.comments?`<div>
          <div class="text-xs font-bold uppercase tracking-wide text-purple-600 mb-1"><i class="fas fa-user-shield mr-1"></i>Confidential Comments to Editor</div>
          <div class="bg-purple-50 border border-purple-100 rounded-lg p-3 text-sm text-gray-700 whitespace-pre-wrap leading-relaxed">${hesc(rv.comments)}</div>
        </div>`:''}
      </div>
      <div class="mt-4 pt-4 border-t border-gray-100 grid grid-cols-2 md:grid-cols-4 gap-3 text-xs text-gray-500">
        ${rv.request_sent_date?`<div><div class="font-bold text-gray-600 mb-0.5">Request Sent</div>${rv.request_sent_date.split(' ')[0]}</div>`:''}
        ${rv.response_due_date?`<div><div class="font-bold text-gray-600 mb-0.5">Response Due</div>${rv.response_due_date}</div>`:''}
        ${rv.review_due_date?`<div><div class="font-bold text-gray-600 mb-0.5">Review Due</div>${rv.review_due_date}</div>`:''}
        ${rv.reviewed_at?`<div><div class="font-bold text-gray-600 mb-0.5">Submitted</div>${rv.reviewed_at.split(' ')[0]}</div>`:''}
      </div>
      ${rv.review_file||rv.review_file_url?`<div class="mt-4 pt-4 border-t border-gray-100">
        <div class="text-xs font-bold text-gray-500 uppercase tracking-wide mb-2"><i class="fas fa-paperclip mr-1"></i>Attached File</div>
        <div class="flex items-center gap-3 bg-gray-50 border border-gray-200 rounded-lg p-3">
          <i class="fas fa-file-pdf text-red-400 text-lg"></i>
          <span class="text-sm text-gray-600 flex-1">${hesc((rv.review_file||rv.review_file_url||'').split('/').pop())}</span>
          <a href="${hesc(rv.review_file_url||rv.review_file||'')}" target="_blank" class="bg-blue-600 text-white text-xs px-3 py-1.5 rounded-lg font-semibold hover:bg-blue-700 transition">
            <i class="fas fa-eye mr-1"></i>View
          </a>
        </div>
      </div>`:''}
      <div class="mt-3 flex justify-end">
        <button onclick="useReviewInDecision(${rv.id},'${esc(name)}')" class="text-xs text-blue-600 hover:text-blue-800 border border-blue-200 hover:bg-blue-50 px-3 py-1.5 rounded-lg font-semibold transition flex items-center gap-1">
          <i class="fas fa-magic text-xs"></i> Use in Editorial Decision
        </button>
      </div>
    </div>
  </div>`;
}

function refreshReviews(){ loadReviews(); }

let allReviewsData = [];
async function loadReviewsForPrefill(){
  try{
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}&ajax=get_reviews&sub_id=${SUB_ID}`);
    const d=await r.json();
    if(!d.success) return;
    allReviewsData=d.reviews||[];
    const sel=document.getElementById('prefillReviewSel');
    sel.innerHTML='<option value="">— Start from scratch —</option>';
    allReviewsData.forEach(rv=>{
      const name=((rv.first_name||'')+' '+(rv.last_name||'')).trim();
      sel.innerHTML+=`<option value="${rv.id}">Review by ${hesc(name)} — ${hesc(rv.recommendation||'No recommendation')}</option>`;
    });
  }catch(e){}
}

function prefillFromReview(id){
  if(!id){ document.getElementById('basedOnReviewId').value=''; return; }
  const rv=allReviewsData.find(r=>r.id==id);
  if(!rv) return;
  document.getElementById('basedOnReviewId').value=id;
  document.getElementById('dec_originality').value=rv.originality||'';
  document.getElementById('dec_presentation').value=rv.presentation||'';
  document.getElementById('dec_applicability').value=rv.applicability||'';
  document.getElementById('dec_overall_status').value=rv.overall_status||'';
  document.getElementById('dec_strengths').value=rv.strengths||'';
  document.getElementById('dec_weaknesses').value=rv.weaknesses||'';
  document.getElementById('dec_suggestions').value=rv.suggestions||'';
  document.getElementById('dec_recommendation').value=rv.recommendation||'';
  toast('Form prefilled from review. Edit before saving.','success');
}

function useReviewInDecision(id, name){
  switchTab('decision');
  document.getElementById('prefillReviewSel').value=id;
  prefillFromReview(id);
}

function openDecisionForm(){ switchTab('decision'); }

async function loadDecisions(){
  document.getElementById('decisionsList').innerHTML='<div class="text-center py-4 text-gray-400 text-sm"><i class="fas fa-spinner fa-spin"></i></div>';
  try{
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}&ajax=get_decisions&sub_id=${SUB_ID}`);
    const d=await r.json();
    if(!d.success) throw new Error(d.error);
    const decs=d.decisions||[];
    const badge=document.getElementById('badgeDecisions');
    if(decs.length){ badge.textContent=decs.length; badge.classList.remove('hidden'); }
    else badge.classList.add('hidden');
    if(!decs.length){
      document.getElementById('decisionsList').innerHTML='<div class="text-center py-4 text-gray-400 text-sm italic">No decisions saved yet.</div>';
      return;
    }
    const decLabels={accepted:'Accepted',accepted_with_changes:'Accepted with Changes',resubmit:'Resubmit',rejected:'Rejected'};
    document.getElementById('decisionsList').innerHTML=decs.map(dec=>`
      <div class="border rounded-xl p-4 mb-3 dec-${dec.decision}">
        <div class="flex items-center justify-between mb-2">
          <span class="font-bold text-sm capitalize">${decLabels[dec.decision]||dec.decision}</span>
          <div class="text-xs text-gray-400">
            By ${hesc((dec.editor_first||'')+' '+(dec.editor_last||''))} · ${new Date(dec.created_at).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'})}
          </div>
        </div>
        <div class="grid grid-cols-4 gap-2 mb-3 text-xs">
          ${['originality','presentation','applicability','overall_status'].map(f=>
            dec[f]?`<div class="bg-white bg-opacity-60 rounded px-2 py-1 text-center"><div class="text-gray-400 capitalize">${f.replace('_',' ')}</div><div class="font-bold">${hesc(dec[f])}</div></div>`:''
          ).join('')}
        </div>
        ${dec.strengths?`<div class="mb-2"><span class="text-xs font-bold text-green-600">Strengths:</span> <span class="text-xs text-gray-700">${hesc(dec.strengths.substring(0,150))}${dec.strengths.length>150?'…':''}</span></div>`:''}
        ${dec.weaknesses?`<div class="mb-2"><span class="text-xs font-bold text-red-500">Weaknesses:</span> <span class="text-xs text-gray-700">${hesc(dec.weaknesses.substring(0,150))}${dec.weaknesses.length>150?'…':''}</span></div>`:''}
        <div class="text-xs text-gray-400">Due: ${dec.due_date||'—'}</div>
      </div>`
    ).join('');
  }catch(e){
    document.getElementById('decisionsList').innerHTML=`<div class="text-center py-4 text-red-400 text-sm">${e.message}</div>`;
  }
}

function refreshDecisions(){ loadDecisions(); }

document.getElementById('decisionForm').addEventListener('submit', async function(e){
  e.preventDefault();
  const decision=document.getElementById('decisionSel').value;
  if(!decision){ toast('Please select a decision.','error'); return; }
  const btn=this.querySelector('[type=submit]');
  btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> Saving…';
  try{
    const fd=new FormData(this);
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}`,{method:'POST',body:fd});
    const d=await r.json();
    if(!d.success) throw new Error(d.message);
    toast(d.message);
    loadDecisions();
    refreshStats();
  }catch(e){ toast(e.message,'error'); }
  finally{ btn.disabled=false; btn.innerHTML='<i class="fas fa-save"></i> Save Decision'; }
});

function resetDecisionForm(){
  document.getElementById('decisionForm').reset();
  document.getElementById('basedOnReviewId').value='';
  document.getElementById('prefillReviewSel').value='';
}

function openRatingModal(revId, name){
  document.getElementById('ratingRevId').value=revId;
  document.getElementById('ratingRevName').textContent=name;
  document.getElementById('ratingValue').value='0';
  document.getElementById('ratingDisplay').textContent='0 / 5';
  document.querySelectorAll('.star-btn').forEach(s=>s.classList.remove('lit'));
  document.getElementById('ratingModal').classList.add('open');
}
function closeRatingModal(){ document.getElementById('ratingModal').classList.remove('open'); }
document.getElementById('ratingModal').addEventListener('click',function(e){ if(e.target===this) closeRatingModal(); });

function setRating(v){
  document.getElementById('ratingValue').value=v;
  document.getElementById('ratingDisplay').textContent=v+' / 5';
  document.querySelectorAll('.star-btn').forEach(s=>{
    s.classList.toggle('lit',parseInt(s.dataset.v)<=v);
  });
}

async function submitRating(){
  const v=parseFloat(document.getElementById('ratingValue').value);
  if(!v){ toast('Please select a rating.','error'); return; }
  const revId=document.getElementById('ratingRevId').value;
  const btn=document.getElementById('submitRatingBtn');
  btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin"></i>';
  try{
    const fd=new FormData();
    fd.append('rate_reviewer','1');
    fd.append('reviewer_id',revId);
    fd.append('rating',v);
    // ── FIX 3 applied
    const r=await fetch(`${THIS_URL}?id=${SUB_ID}`,{method:'POST',body:fd});
    const d=await r.json();
    if(!d.success) throw new Error(d.message);
    toast(d.message);
    closeRatingModal();
    loadAssignments();
    loadReviews();
    refreshStats();
  }catch(e){ toast(e.message,'error'); }
  finally{ btn.disabled=false; btn.innerHTML='<i class="fas fa-check"></i> Submit Rating'; }
}

async function refreshStats(){
  try{
    const [ar, rr] = await Promise.all([
      // ── FIX 3 applied
      fetch(`${THIS_URL}?id=${SUB_ID}&ajax=get_assignments&sub_id=${SUB_ID}`).then(r=>r.json()),
      fetch(`${THIS_URL}?id=${SUB_ID}&ajax=get_reviews&sub_id=${SUB_ID}`).then(r=>r.json())
    ]);
    const asgns=ar.assignments||[];
    const counts={
      total: asgns.length,
      pending: asgns.filter(a=>a.assignment_status==='request_sent').length,
      accepted: asgns.filter(a=>a.assignment_status==='accepted').length,
      submitted: asgns.filter(a=>a.assignment_status==='review_submitted').length,
      declined: asgns.filter(a=>a.assignment_status==='declined').length,
    };
    document.getElementById('statsBody').innerHTML=`
      <div class="space-y-3">
        ${[
          ['Total Assigned',counts.total,'fas fa-users','text-blue-500'],
          ['Pending',counts.pending,'fas fa-clock','text-yellow-500'],
          ['Accepted',counts.accepted,'fas fa-check','text-green-500'],
          ['Reviews Submitted',counts.submitted,'fas fa-star','text-purple-500'],
          ['Declined',counts.declined,'fas fa-times','text-red-400'],
        ].map(([l,v,ic,cl])=>`
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2 text-sm text-gray-600">
              <i class="${ic} ${cl} text-xs w-4 text-center"></i>${l}
            </div>
            <span class="font-bold text-gray-800 text-sm">${v}</span>
          </div>`
        ).join('')}
      </div>`;
  }catch(e){
    document.getElementById('statsBody').innerHTML='<div class="text-xs text-red-400">Error loading stats.</div>';
  }
}

function hesc(s){ const d=document.createElement('div'); d.appendChild(document.createTextNode(s||'')); return d.innerHTML; }
function esc(s){ return (s||'').replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/"/g,'\\"'); }

document.addEventListener('DOMContentLoaded',()=>{
  loadAssignments();
  refreshStats();
  const d=new Date(); d.setDate(d.getDate()+30);
  document.getElementById('dueDateInp').value=d.toISOString().split('T')[0];
});
</script>
</body>
</html>