<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

// ── Ensure review tables exist in current schema ──────────────
try {
    $pdo->exec("ALTER TABLE submissions ADD COLUMN IF NOT EXISTS submission_status
        ENUM('draft','submitted','under_review','accepted','rejected') NOT NULL DEFAULT 'draft'");
} catch(PDOException $e) {}

// ── Auto-patch review_assignments to match current schema ─────
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `review_assignments` (
        `id` int(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `submission_id` int(10) UNSIGNED NOT NULL,
        `reviewer_id` int(10) UNSIGNED NOT NULL,
        `review_round` tinyint UNSIGNED DEFAULT 1,
        `assignment_status` enum('request_sent','accepted','declined','cancelled','review_submitted') DEFAULT 'request_sent',
        `reviewer_type` varchar(60) DEFAULT 'anonymous_reviewer_anonymous_author',
        `access_key` varchar(64) DEFAULT NULL,
        `request_sent_date` datetime DEFAULT NOW(),
        `response_due_date` date DEFAULT NULL,
        `review_due_date` date DEFAULT NULL,
        `submitted_date` datetime DEFAULT NULL,
        `reviewer_rating` decimal(3,2) DEFAULT NULL,
        `recommendation` varchar(100) DEFAULT NULL,
        `created_at` datetime DEFAULT NOW(),
        UNIQUE KEY `access_key` (`access_key`),
        KEY `idx_submission` (`submission_id`),
        KEY `idx_reviewer` (`reviewer_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch(PDOException $e) {}

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `reviewers` (
        `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `user_id` int(11) NOT NULL,
        `reviewing_interests` text DEFAULT NULL,
        `max_reviews_per_period` int DEFAULT 0,
        `preferred_review_duration_days` int DEFAULT 0,
        `reviewer_rating` decimal(2,1) DEFAULT 0.0,
        `total_reviews_completed` int DEFAULT 0,
        `total_reviews_declined` int DEFAULT 0,
        `total_reviews_cancelled` int DEFAULT 0,
        `avg_days_to_complete` decimal(5,2) DEFAULT 0.00,
        `last_review_assigned` date DEFAULT NULL,
        `is_available` tinyint(1) DEFAULT 1,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch(PDOException $e) {}

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

    // Get reviewers list for modal
    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,
                       u.user_id, u.first_name, u.last_name, u.email,
                       a.name AS affiliation_name, u.phone_country_code
                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')
                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;
    }

    // Get existing assignments for a submission
    if ($_GET['ajax'] === 'get_assignments' && isset($_GET['sub_id'])) {
        $sid = (int)$_GET['sub_id'];
        try {
            $stmt = $pdo->prepare("
                SELECT ra.*, u.first_name, u.last_name, u.email
                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([$sid]);
            echo json_encode(['success' => true, 'assignments' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    // Get submission details for review modal header
    if ($_GET['ajax'] === 'get_submission' && isset($_GET['sub_id'])) {
        $sid = (int)$_GET['sub_id'];
        try {
            $stmt = $pdo->prepare("
                SELECT s.submission_id, s.tracking_code, s.submission_status,
                       mi.article_title, mi.abstract,
                       u.first_name, u.last_name, u.email,
                       j.name AS journal_name
                FROM submissions s
                LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
                LEFT JOIN users u ON u.user_id = s.user_id
                LEFT JOIN journals j ON j.journal_id = s.journal_id
                WHERE s.submission_id = ?
            ");
            $stmt->execute([$sid]);
            echo json_encode(['success' => true, 'submission' => $stmt->fetch(PDO::FETCH_ASSOC)]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    // Toggle reviewer availability
    if ($_GET['ajax'] === 'toggle_reviewer' && isset($_GET['reviewer_id'])) {
        try {
            $pdo->prepare("UPDATE reviewers SET is_available = 1 - is_available WHERE id = ?")
                ->execute([(int)$_GET['reviewer_id']]);
            echo json_encode(['success' => true]);
        } catch(PDOException $e) {
            echo json_encode(['success' => false]);
        }
        exit;
    }

    exit;
}

// ── POST: Assign existing reviewer ───────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_reviewer'])) {
    $result = ['success' => false, 'message' => ''];
    try {
        $sid          = (int)$_POST['submission_id'];
        $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.");

        // Check not already assigned
        $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.");

        // Unique access key
        do {
            $access_key = bin2hex(random_bytes(32));
            $kchk = $pdo->prepare("SELECT id FROM review_assignments WHERE access_key=?");
            $kchk->execute([$access_key]);
        } while ($kchk->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]);

        // Only update status if not already decided
        $subStatus = $pdo->prepare("SELECT submission_status FROM submissions WHERE submission_id=?");
        $subStatus->execute([$sid]);
        $currentStatus = $subStatus->fetchColumn();
        if (!in_array($currentStatus, ['accepted','rejected'])) {
            $pdo->prepare("UPDATE submissions SET submission_status='under_review', updated_at=NOW() WHERE submission_id=?")
                ->execute([$sid]);
        }

        // Log the assignment
        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", $_SESSION['user_id'] ?? 1]);
        } catch(PDOException $e) {}

        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'message' => 'Reviewer assigned successfully.']);
    } catch(Exception $e) {
        header('Content-Type: application/json');
        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';
        $sid        = (int)$_POST['submission_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 (!$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.");

        // Check email not taken
        $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.");

        // Insert user
        $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();

        // Insert reviewer record
        $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();

        // Assign to submission
        do {
            $access_key = bin2hex(random_bytes(32));
            $kchk = $pdo->prepare("SELECT id FROM review_assignments WHERE access_key=?");
            $kchk->execute([$access_key]);
        } while ($kchk->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]);

        // Update status
        $subStatus = $pdo->prepare("SELECT submission_status FROM submissions WHERE submission_id=?");
        $subStatus->execute([$sid]);
        $currentStatus = $subStatus->fetchColumn();
        if (!in_array($currentStatus, ['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();
        echo json_encode(['success' => true, 'message' => "Reviewer $first_name $last_name created and assigned."]);
    } catch(Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ── POST: Status update ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'], $_POST['sub_id'], $_POST['new_status'])) {
    $valid = ['draft','submitted','under_review','accepted','rejected'];
    if (in_array($_POST['new_status'], $valid)) {
        $pdo->prepare("UPDATE submissions SET submission_status=?, updated_at=NOW() WHERE submission_id=?")
           ->execute([$_POST['new_status'], (int)$_POST['sub_id']]);
    }
    $qs = http_build_query(array_filter([
        'q' => $_GET['q'] ?? '', 'status' => $_GET['status'] ?? '',
        'journal' => $_GET['journal'] ?? '', 'from' => $_GET['from'] ?? '',
        'to' => $_GET['to'] ?? '', 'sort' => $_GET['sort'] ?? ''
    ], 'strlen'));
    header('Location: submissions.php'.($qs ? "?$qs" : '')); exit;
}

// ── Filters & main query ──────────────────────────────────────
$search   = trim($_GET['q']       ?? '');
$status   = trim($_GET['status']  ?? '');
$journal  = trim($_GET['journal'] ?? '');
$dateFrom = trim($_GET['from']    ?? '');
$dateTo   = trim($_GET['to']      ?? '');
$sort     = in_array($_GET['sort'] ?? '', ['newest','oldest','title','author'])
            ? $_GET['sort'] : 'newest';

$where = []; $params = [];
if ($search) {
    $where[] = "(COALESCE(mi.article_title,'') LIKE ? OR COALESCE(u.first_name,'') LIKE ?
                 OR COALESCE(u.last_name,'') LIKE ? OR COALESCE(u.email,'') LIKE ?
                 OR COALESCE(j.name,'') LIKE ?)";
    for ($i = 0; $i < 5; $i++) $params[] = "%$search%";
}
if ($status && in_array($status, ['draft','submitted','under_review','accepted','rejected'])) {
    $where[] = "COALESCE(s.submission_status,'draft')=?"; $params[] = $status;
}
if ($journal) { $where[] = "s.journal_id=?"; $params[] = (int)$journal; }
if ($dateFrom) { $where[] = "DATE(s.created_at)>=?"; $params[] = $dateFrom; }
if ($dateTo)   { $where[] = "DATE(s.created_at)<=?"; $params[] = $dateTo; }

$orderBy = match($sort) {
    'oldest' => 's.created_at ASC',
    'title'  => 'COALESCE(mi.article_title,"zzz") ASC',
    'author' => 'COALESCE(u.last_name,"zzz") ASC',
    default  => 's.created_at DESC',
};

$sql = "
    SELECT s.submission_id, s.created_at, s.updated_at,
           COALESCE(s.submission_status,'draft') AS submission_status,
           s.tracking_code, s.submitted_at,
           u.first_name, u.last_name, u.email,
           j.name AS journal_name,
           at.name AS article_type_name,
           mi.article_title,
           (SELECT COUNT(*) FROM submission_authors sa WHERE sa.submission_id=s.submission_id) AS author_count,
           (SELECT COUNT(*) FROM submission_authors sa WHERE sa.submission_id=s.submission_id AND sa.is_corresponding=1) AS has_corr,
           (SELECT 1 FROM submission_editorial se WHERE se.submission_id=s.submission_id AND se.cover_letter IS NOT NULL AND se.cover_letter!='' LIMIT 1) AS has_editorial,
           (SELECT 1 FROM submission_statements ss WHERE ss.submission_id=s.submission_id LIMIT 1) AS has_statements,
           (SELECT address FROM submission_payment sp WHERE sp.submission_id=s.submission_id LIMIT 1) AS pay_address,
           (SELECT COUNT(*) FROM review_assignments ra WHERE ra.submission_id=s.submission_id) AS reviewer_count
    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 article_types   at ON at.article_type_id = s.article_type_id
    LEFT JOIN manuscript_info mi ON mi.submission_id   = s.submission_id
".($where ? " WHERE ".implode(' AND ', $where) : "")."
    ORDER BY $orderBy
";

try {
    $stmt = $pdo->prepare($sql); $stmt->execute($params);
    $submissions = $stmt->fetchAll();

    $stats = $pdo->query("
        SELECT COUNT(*) AS total,
            SUM(COALESCE(submission_status,'draft')='draft')        AS draft,
            SUM(COALESCE(submission_status,'draft')='submitted')    AS submitted,
            SUM(COALESCE(submission_status,'draft')='under_review') AS under_review,
            SUM(COALESCE(submission_status,'draft')='accepted')     AS accepted,
            SUM(COALESCE(submission_status,'draft')='rejected')     AS rejected
        FROM submissions
    ")->fetch();

    $journals = $pdo->query("SELECT journal_id, name FROM journals ORDER BY name")->fetchAll();

} catch(PDOException $e) {
    $submissions = [];
    $stats = array_fill_keys(['total','draft','submitted','under_review','accepted','rejected'], 0);
    $journals = [];
    $dbError = $e->getMessage();
}

$active_section = 'submissions';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Submissions — Admin</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; }
body.dark { background-color:#1a202c; color:#e2e8f0; }
.sidebar { width:250px; background:#2d3748; 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:#4a5568; }
.nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
body.dark .bg-white { background-color:#2d3748; }
body.dark .text-gray-700 { color:#d1d5db; }
body.dark table { color:#e2e8f0; }
body.dark .border-gray-200 { border-color:#4a5568; }
body.dark .bg-gray-50 { background-color:#374151; }
body.dark .border-gray-100 { border-color:#4a5568; }
body.dark input, body.dark select { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }
body.dark .text-gray-800 { color:#F3F4F6; }
body.dark .text-gray-600 { color:#9CA3AF; }
body.dark .text-gray-500 { color:#6B7280; }
@media(max-width:768px){ .sidebar{transform:translateX(-250px)} .sidebar.mobile-open{transform:translateX(0)} .content{margin-left:0} }

/* Status badges */
.sbadge { display:inline-flex; align-items:center; gap:5px; padding:3px 10px; border-radius:9999px; font-size:11px; font-weight:600; }
.sbadge::before { content:''; width:6px; height:6px; border-radius:50%; flex-shrink:0; }
.sb-draft { background:rgba(156,163,175,.15); color:#6b7280; } .sb-draft::before { background:#6b7280; }
.sb-submitted { background:rgba(59,130,246,.12); color:#2563eb; } .sb-submitted::before { background:#2563eb; }
.sb-under_review { background:rgba(245,158,11,.12); color:#d97706; } .sb-under_review::before { background:#d97706; }
.sb-accepted { background:rgba(16,185,129,.12); color:#059669; } .sb-accepted::before { background:#059669; }
.sb-rejected { background:rgba(239,68,68,.12); color:#dc2626; } .sb-rejected::before { background:#dc2626; }

/* Section dots */
.comp-dot { width:8px; height:8px; border-radius:50%; display:inline-block; flex-shrink:0; }
.comp-yes { background:#10b981; } .comp-no { background:#e2e8f0; }

/* Filter tag */
.filter-tag { display:inline-flex; align-items:center; gap:5px; background:#EFF6FF; color:#2563EB; border:1px solid #BFDBFE; padding:2px 10px; border-radius:20px; font-size:12px; font-weight:500; }

/* Status dropdown */
.action-dd { display:none; position:absolute; right:0; top:36px; background:white; border-radius:8px; box-shadow:0 8px 30px rgba(0,0,0,.15); border:1px solid #E5E7EB; z-index:50; width:165px; padding:4px 0; }
.action-dd.open { display:block; }
body.dark .action-dd { background:#374151; border-color:#4B5563; }

/* ── Review Modal ─────────────────────────────────────────── */
.modal-backdrop { background:rgba(0,0,0,.55); backdrop-filter:blur(3px); }
.reviewer-card { border:1px solid #E5E7EB; border-radius:10px; padding:14px; background:#FAFAFA; transition:border-color .15s,box-shadow .15s; cursor:pointer; }
.reviewer-card:hover { border-color:#3B82F6; box-shadow:0 0 0 3px rgba(59,130,246,.1); }
.reviewer-card.selected { border-color:#2563EB; background:#EFF6FF; box-shadow:0 0 0 3px rgba(37,99,235,.15); }
body.dark .reviewer-card { background:#374151; border-color:#4B5563; }
body.dark .reviewer-card.selected { background:#1E3A5F; border-color:#3B82F6; }
.rev-tab { padding:8px 16px; border-radius:8px; font-size:13px; font-weight:500; cursor:pointer; border:none; background:transparent; color:#64748b; transition:all .15s; white-space:nowrap; }
.rev-tab.active { background:#EFF6FF; color:#1d4ed8; font-weight:600; }
.rev-panel { display:none; }
.rev-panel.active { display:block; }
.assign-input { width:100%; border:1px solid #D1D5DB; border-radius:8px; padding:8px 12px; font-size:13px; color:#374151; transition:border-color .15s; outline:none; }
.assign-input:focus { border-color:#3B82F6; box-shadow:0 0 0 2px rgba(59,130,246,.1); }
.star-display i { font-size:11px; }
.assignment-row { display:flex; align-items:center; gap:10px; padding:10px 12px; border:1px solid #E5E7EB; border-radius:8px; background:#F9FAFB; margin-bottom:8px; }
.as-badge { padding:2px 8px; border-radius:9999px; font-size:10px; font-weight:700; }
.as-request_sent { background:#DBEAFE; color:#1E40AF; }
.as-accepted { background:#D1FAE5; color:#065F46; }
.as-declined { background:#FEE2E2; color:#991B1B; }
.as-review_submitted { background:#F0FDF4; color:#14532D; }
.as-cancelled { background:#F3F4F6; color:#374151; }
.toast { 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 ease; }
.toast.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; }
</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">

    <!-- Topbar -->
    <div class="bg-white border-b border-gray-200 px-6 py-4 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-500 hover:text-gray-700 hidden md:block">
                <i class="fas fa-bars text-lg"></i>
            </button>
            <div class="flex items-center gap-2 text-sm text-gray-500">
                <a href="index.php" class="hover:text-blue-600"><i class="fas fa-home"></i></a>
                <i class="fas fa-chevron-right text-xs text-gray-300"></i>
                <h1 class="text-gray-800 font-bold flex items-center gap-2">
                    <i class="fas fa-file-signature text-blue-600"></i> Submissions
                </h1>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <button id="darkModeToggle" class="text-gray-500 hover:text-gray-700 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
                <i class="fas fa-moon"></i>
            </button>
        </div>
    </div>

    <main class="p-6">

        <?php if (!empty($dbError)): ?>
        <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-5 rounded-lg flex items-center gap-2">
            <i class="fas fa-exclamation-circle"></i>
            <div><strong>DB Error:</strong> <?= htmlspecialchars($dbError) ?></div>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
        <?php
        $cards = [
            ['Total',        'total',        'text-gray-800',   'bg-gray-100',   'fa-layer-group'],
            ['Draft',        'draft',        'text-gray-500',   'bg-gray-100',   'fa-pencil-alt'],
            ['Submitted',    'submitted',    'text-blue-600',   'bg-blue-100',   'fa-paper-plane'],
            ['Under Review', 'under_review', 'text-yellow-500', 'bg-yellow-100', 'fa-search'],
            ['Accepted',     'accepted',     'text-green-600',  'bg-green-100',  'fa-check-circle'],
            ['Rejected',     'rejected',     'text-red-500',    'bg-red-100',    'fa-times-circle'],
        ];
        foreach ($cards as [$label,$key,$color,$ibg,$icon]): ?>
        <div class="bg-white rounded-xl p-4 shadow-sm border border-gray-100 cursor-pointer hover:shadow-md hover:-translate-y-0.5 transition-all"
             onclick="filterByStatus('<?= $key==='total'?'':$key ?>')">
            <div class="w-8 h-8 <?= $ibg ?> rounded-lg flex items-center justify-center mb-2">
                <i class="fas <?= $icon ?> <?= $color ?> text-sm"></i>
            </div>
            <div class="text-2xl font-bold <?= $color ?>"><?= (int)($stats[$key] ?? 0) ?></div>
            <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide"><?= $label ?></div>
        </div>
        <?php endforeach; ?>
        </div>

        <!-- Table Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100">

            <!-- Filters toolbar -->
            <div class="p-4 border-b border-gray-100">
                <form method="GET" id="filterForm">
                    <div class="flex flex-wrap gap-3 items-center">
                        <div class="relative flex-1 min-w-[180px] max-w-xs">
                            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                            <input type="text" name="q" value="<?= htmlspecialchars($search) ?>"
                                   placeholder="Title, author, email…"
                                   class="w-full border border-gray-300 rounded-lg pl-9 pr-4 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        <select name="status" onchange="this.form.submit()"
                                class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">All Status</option>
                            <option value="draft"        <?= $status==='draft'        ?'selected':'' ?>>Draft</option>
                            <option value="submitted"    <?= $status==='submitted'    ?'selected':'' ?>>Submitted</option>
                            <option value="under_review" <?= $status==='under_review' ?'selected':'' ?>>Under Review</option>
                            <option value="accepted"     <?= $status==='accepted'     ?'selected':'' ?>>Accepted</option>
                            <option value="rejected"     <?= $status==='rejected'     ?'selected':'' ?>>Rejected</option>
                        </select>
                        <?php if (!empty($journals)): ?>
                        <select name="journal" onchange="this.form.submit()"
                                class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">All Journals</option>
                            <?php foreach ($journals as $j): ?>
                            <option value="<?= $j['journal_id'] ?>" <?= $journal==$j['journal_id']?'selected':'' ?>>
                                <?= htmlspecialchars(mb_strimwidth($j['name'],0,30,'…')) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <?php endif; ?>
                        <div class="flex items-center gap-2">
                            <input type="date" name="from" value="<?= htmlspecialchars($dateFrom) ?>"
                                   class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <span class="text-gray-400 text-xs">→</span>
                            <input type="date" name="to" value="<?= htmlspecialchars($dateTo) ?>"
                                   class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        <select name="sort" onchange="this.form.submit()"
                                class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="newest" <?= $sort==='newest'?'selected':'' ?>>Newest first</option>
                            <option value="oldest" <?= $sort==='oldest'?'selected':'' ?>>Oldest first</option>
                            <option value="title"  <?= $sort==='title' ?'selected':'' ?>>By title</option>
                            <option value="author" <?= $sort==='author'?'selected':'' ?>>By author</option>
                        </select>
                        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition">
                            <i class="fas fa-search"></i> Search
                        </button>
                        <?php if ($search||$status||$journal||$dateFrom||$dateTo): ?>
                        <a href="submissions.php" class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-500 hover:bg-gray-50 flex items-center gap-1">
                            <i class="fas fa-times"></i> Clear
                        </a>
                        <?php endif; ?>
                    </div>
                    <?php if ($search||$status||$journal||$dateFrom||$dateTo): ?>
                    <div class="flex flex-wrap gap-2 mt-3">
                        <?php if ($search): ?><span class="filter-tag"><i class="fas fa-search text-xs"></i> "<?= htmlspecialchars($search) ?>"</span><?php endif; ?>
                        <?php if ($status): ?><span class="filter-tag"><?= ucfirst(str_replace('_',' ',$status)) ?></span><?php endif; ?>
                        <?php if ($journal): ?><span class="filter-tag"><i class="fas fa-book text-xs"></i> Journal filtered</span><?php endif; ?>
                        <?php if ($dateFrom||$dateTo): ?><span class="filter-tag"><i class="fas fa-calendar text-xs"></i> <?= $dateFrom?:'…' ?> → <?= $dateTo?:'…' ?></span><?php endif; ?>
                    </div>
                    <?php endif; ?>
                </form>
                <div class="mt-3 text-sm text-gray-500">
                    <strong class="text-gray-700"><?= count($submissions) ?></strong>
                    submission<?= count($submissions)!==1?'s':'' ?> found
                </div>
            </div>

            <!-- Table -->
            <div class="overflow-x-auto">
                <?php if (empty($submissions)): ?>
                <div class="text-center py-16">
                    <i class="fas fa-file-signature text-5xl text-gray-200 mb-4 block"></i>
                    <p class="text-gray-500 font-medium">No submissions found</p>
                    <p class="text-gray-400 text-sm mt-1"><?= ($search||$status||$journal) ? 'Try adjusting your filters' : 'No submissions yet' ?></p>
                </div>
                <?php else: ?>
                <table class="w-full text-sm text-left text-gray-600">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide w-10">#</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide">Title / Author</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide">Journal</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide">Status</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide text-center">Sections</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide text-center">Reviewers</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide">Date</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                    <?php foreach ($submissions as $i => $sub):
                        $sk     = $sub['submission_status'];
                        $title  = $sub['article_title'] ?: '<<untitled>>';
                        $author = trim(($sub['first_name']??'').' '.($sub['last_name']??''));
                        $d1 = !empty($sub['journal_name']);
                        $d2 = !empty($sub['article_title']);
                        $d3 = ($sub['author_count']??0) > 0 && ($sub['has_corr']??0) > 0;
                        $d4 = !empty($sub['has_editorial']);
                        $d5 = !empty($sub['has_statements']);
                        $d6 = !empty($sub['pay_address']);
                        $done = array_sum([$d1,$d2,$d3,$d4,$d5,$d6]);
                        $revCount = (int)($sub['reviewer_count'] ?? 0);
                    ?>
                    <tr class="hover:bg-gray-50 transition">
                        <td class="px-4 py-3 text-gray-400 font-mono text-xs"><?= $i+1 ?></td>

                        <!-- Title / Author -->
                        <td class="px-4 py-3" style="max-width:220px">
                            <a href="submission_view.php?id=<?= $sub['submission_id'] ?>"
                               class="font-semibold text-gray-800 hover:text-blue-600 transition block truncate"
                               title="<?= htmlspecialchars($title) ?>" style="max-width:210px">
                                <?= htmlspecialchars(mb_strimwidth($title,0,48,'…')) ?>
                            </a>
                            <div class="text-xs text-gray-400 mt-0.5 flex items-center gap-1">
                                <i class="fas fa-user text-[9px]"></i>
                                <?= htmlspecialchars($author ?: '—') ?>
                                <?php if (($sub['author_count']??0) > 1): ?>
                                <span class="text-gray-300 ml-0.5">+<?= $sub['author_count']-1 ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="text-xs text-gray-400 mt-0.5 truncate" style="max-width:210px">
                                <i class="fas fa-envelope text-[9px]"></i>
                                <?= htmlspecialchars($sub['email'] ?? '—') ?>
                            </div>
                            <?php if ($sub['tracking_code']): ?>
                            <div class="text-xs font-mono text-blue-400 mt-0.5"><?= htmlspecialchars($sub['tracking_code']) ?></div>
                            <?php endif; ?>
                        </td>

                        <!-- Journal -->
                        <td class="px-4 py-3" style="max-width:180px">
                            <?php if ($sub['journal_name']): ?>
                            <div class="text-xs font-medium text-gray-700 truncate" style="max-width:170px" title="<?= htmlspecialchars($sub['journal_name']) ?>">
                                <?= htmlspecialchars($sub['journal_name']) ?>
                            </div>
                            <?php if ($sub['article_type_name']): ?>
                            <div class="text-xs text-gray-400 mt-0.5"><?= htmlspecialchars($sub['article_type_name']) ?></div>
                            <?php endif; ?>
                            <?php else: ?>
                            <span class="text-xs text-gray-300 italic">Not selected</span>
                            <?php endif; ?>
                        </td>

                        <!-- Status -->
                        <td class="px-4 py-3">
                            <span class="sbadge sb-<?= $sk ?>"><?= ucfirst(str_replace('_',' ',$sk)) ?></span>
                        </td>

                        <!-- Section dots -->
                        <td class="px-4 py-3 text-center">
                            <div class="flex items-center justify-center gap-1" title="Details · Manuscript · Authors · Editorial · Statements · Payment">
                                <?php foreach ([$d1,$d2,$d3,$d4,$d5,$d6] as $d): ?>
                                <span class="comp-dot <?= $d?'comp-yes':'comp-no' ?>"></span>
                                <?php endforeach; ?>
                            </div>
                            <div class="text-xs text-gray-400 mt-1 font-mono"><?= $done ?>/6</div>
                        </td>

                        <!-- Reviewer count -->
                        <td class="px-4 py-3 text-center">
                            <?php if ($revCount > 0): ?>
                            <span class="inline-flex items-center gap-1 text-xs font-semibold text-yellow-600 bg-yellow-50 border border-yellow-200 px-2 py-0.5 rounded-full">
                                <i class="fas fa-user-check text-[9px]"></i> <?= $revCount ?>
                            </span>
                            <?php else: ?>
                            <span class="text-xs text-gray-300">—</span>
                            <?php endif; ?>
                        </td>

                        <!-- Date -->
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-xs text-gray-600 font-medium"><?= date('d M Y',strtotime($sub['created_at'])) ?></div>
                            <div class="text-xs text-gray-400 font-mono"><?= date('H:i',strtotime($sub['created_at'])) ?></div>
                        </td>

                        <!-- Actions -->
                        <td class="px-4 py-3">
                            <div class="flex items-center justify-center gap-1.5">
                                <!-- View -->
                                <a href="submission_view.php?id=<?= $sub['submission_id'] ?>"
                                   class="bg-blue-50 hover:bg-blue-100 text-blue-600 px-2.5 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1 transition">
                                    <i class="fas fa-eye"></i> View
                                </a>
                                <a href="submission_review.php?id=<?= $sub['submission_id'] ?>"
                                   class="bg-blue-50 hover:bg-blue-100 text-blue-600 px-2.5 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1 transition">
                                    <i class="fas fa-eye"></i> Review Details
                                </a>

                                <!-- ── REVIEW button ── -->
                                <button onclick="openReviewModal(<?= $sub['submission_id'] ?>, '<?= htmlspecialchars(addslashes($title), ENT_QUOTES) ?>')"
                                        class="bg-purple-50 hover:bg-purple-100 text-purple-700 border border-purple-200 px-2.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1 transition">
                                    <i class="fas fa-user-check text-[10px]"></i>
                                    Review
                                    <?php if ($revCount > 0): ?>
                                    <span class="bg-purple-200 text-purple-800 rounded-full w-4 h-4 text-[9px] font-bold flex items-center justify-center"><?= $revCount ?></span>
                                    <?php endif; ?>
                                </button>

                                <!-- Status dropdown -->
                                <div class="relative">
                                    <button onclick="toggleDD(<?= $sub['submission_id'] ?>)"
                                            class="bg-gray-50 hover:bg-gray-100 text-gray-500 px-2 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1 transition">
                                        <i class="fas fa-chevron-down text-xs"></i>
                                    </button>
                                    <div class="action-dd" id="dd_<?= $sub['submission_id'] ?>">
                                        <?php
                                        $allSt = [
                                            'submitted'    => ['fa-paper-plane','text-blue-500',  'Mark Submitted'],
                                            'under_review' => ['fa-search',     'text-yellow-500','Under Review'],
                                            'accepted'     => ['fa-check',      'text-green-500', 'Accept'],
                                            'rejected'     => ['fa-times',      'text-red-500',   'Reject'],
                                            'draft'        => ['fa-undo',       'text-gray-400',  'Reset to Draft'],
                                        ];
                                        foreach ($allSt as $sv => [$ic,$cl,$lb]):
                                            if ($sv === $sk) continue;
                                        ?>
                                        <form method="POST">
                                            <input type="hidden" name="sub_id"     value="<?= $sub['submission_id'] ?>">
                                            <input type="hidden" name="new_status" value="<?= $sv ?>">
                                            <button type="submit" name="update_status"
                                                    class="w-full text-left px-4 py-2 text-xs text-gray-700 hover:bg-gray-50 flex items-center gap-2">
                                                <i class="fas <?= $ic ?> <?= $cl ?>"></i> <?= $lb ?>
                                            </button>
                                        </form>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </td>

                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>

    </main>
</div>

<!-- ═══════════════════════════════════════════════════════════
     REVIEW ASSIGNMENT MODAL
═══════════════════════════════════════════════════════════ -->
<div id="reviewModal" class="fixed inset-0 modal-backdrop hidden z-50 flex items-center justify-center p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[92vh] overflow-hidden flex flex-col">

    <!-- Modal Header -->
    <div class="px-6 py-4 border-b border-gray-100 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 text-base" id="reviewModalTitle">Review Assignment</h2>
          <p class="text-xs text-gray-400 mt-0.5" id="reviewModalSubtitle">Loading…</p>
        </div>
      </div>
      <button onclick="closeReviewModal()" class="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center">
        <i class="fas fa-times"></i>
      </button>
    </div>

    <!-- Sub-tabs -->
    <div class="px-5 pt-3 pb-0 border-b border-gray-100 flex gap-1 flex-shrink-0">
      <button class="rev-tab active" onclick="switchRevTab('existing')" id="revtab-existing">
        <i class="fas fa-users mr-1 text-xs text-blue-500"></i>Existing Reviewers
      </button>
      <button class="rev-tab" onclick="switchRevTab('create')" id="revtab-create">
        <i class="fas fa-user-plus mr-1 text-xs text-green-500"></i>Create New Reviewer
      </button>
      <button class="rev-tab" onclick="switchRevTab('assignments')" id="revtab-assignments">
        <i class="fas fa-list-check mr-1 text-xs text-yellow-500"></i>Current Assignments
        <span id="assignCountBadge" class="ml-1 bg-yellow-100 text-yellow-700 rounded-full text-[10px] font-bold px-1.5 hidden"></span>
      </button>
    </div>

    <div class="flex-1 overflow-y-auto p-5">

      <!-- ── TAB: Existing Reviewers ── -->
      <div id="revpanel-existing" class="rev-panel active">

        <!-- Filters for reviewer search -->
        <div class="flex flex-wrap gap-2 mb-4">
          <div class="relative flex-1 min-w-[150px]">
            <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="revSearch" placeholder="Name, email…"
                   oninput="filterReviewers()"
                   class="assign-input pl-8">
          </div>
          <select id="revFilterAvail" onchange="filterReviewers()" class="assign-input" style="width:140px">
            <option value="">All availability</option>
            <option value="1">Available</option>
            <option value="0">Busy</option>
          </select>
          <input type="range" id="revFilterRating" min="0" max="5" step="0.5" value="0"
                 oninput="document.getElementById('revRatingVal').textContent=this.value;filterReviewers()"
                 class="align-middle" style="width:100px">
          <span class="text-xs text-gray-500 self-center">Rating ≥ <strong id="revRatingVal">0</strong></span>
        </div>

        <!-- Reviewer list -->
        <div id="reviewerListContainer" class="space-y-2 max-h-64 overflow-y-auto mb-5">
          <div class="text-center py-8 text-gray-400 text-sm" id="reviewerListLoading">
            <i class="fas fa-spinner fa-spin text-2xl mb-2 block"></i>Loading reviewers…
          </div>
        </div>

        <!-- Selected reviewer + assignment form -->
        <div id="assignForm" 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 text-blue-500 font-semibold mb-1 uppercase tracking-wide">Selected Reviewer</div>
            <div class="font-semibold text-gray-800" id="selectedRevName">—</div>
            <div class="text-xs text-gray-500" id="selectedRevEmail">—</div>
          </div>
          <div class="grid grid-cols-2 gap-4 mb-4">
            <div>
              <label class="block text-xs font-semibold text-gray-600 mb-1.5">Response Due Date</label>
              <input type="date" id="responseDueDate" class="assign-input">
            </div>
            <div>
              <label class="block text-xs font-semibold text-gray-600 mb-1.5">Review Due Date</label>
              <input type="date" id="reviewDueDate" class="assign-input">
            </div>
          </div>
          <div class="mb-4">
            <label class="block text-xs font-semibold text-gray-600 mb-1.5">Review Type</label>
            <select id="reviewerType" class="assign-input">
              <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="assignBtn"
                  class="w-full bg-purple-600 hover:bg-purple-700 text-white py-2.5 rounded-xl font-semibold flex items-center justify-center gap-2 transition">
            <i class="fas fa-user-check"></i> Assign Reviewer
          </button>
        </div>
      </div>

      <!-- ── TAB: Create New Reviewer ── -->
      <div id="revpanel-create" class="rev-panel 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"></i>
          <span>A new user account with <strong>reviewer</strong> role will be created and immediately assigned to this submission.</span>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-xs font-semibold text-gray-600 mb-1.5">First Name <span class="text-red-500">*</span></label>
            <input type="text" id="newRevFirstName" class="assign-input" placeholder="John">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-600 mb-1.5">Last Name <span class="text-red-500">*</span></label>
            <input type="text" id="newRevLastName" class="assign-input" placeholder="Doe">
          </div>
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1.5">Email <span class="text-red-500">*</span></label>
          <input type="email" id="newRevEmail" class="assign-input" placeholder="reviewer@university.edu">
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1.5">Password <span class="text-gray-400 font-normal">(default: Reviewer@123)</span></label>
          <input type="password" id="newRevPassword" class="assign-input" placeholder="Reviewer@123">
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-xs font-semibold text-gray-600 mb-1.5">Response Due Date</label>
            <input type="date" id="newRevRespDue" class="assign-input">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-600 mb-1.5">Review Due Date</label>
            <input type="date" id="newRevReviewDue" class="assign-input">
          </div>
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1.5">Review Type</label>
          <select id="newRevType" class="assign-input">
            <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-semibold flex items-center justify-center gap-2 transition">
          <i class="fas fa-user-plus"></i> Create & Assign Reviewer
        </button>
      </div>

      <!-- ── TAB: Current Assignments ── -->
      <div id="revpanel-assignments" class="rev-panel">
        <div id="assignmentsContainer">
          <div class="text-center py-8 text-gray-400 text-sm">
            <i class="fas fa-spinner fa-spin text-2xl mb-2 block"></i>Loading assignments…
          </div>
        </div>
      </div>

    </div>
  </div>
</div>

<!-- Toast notification -->
<div id="toast" class="toast">
  <i id="toastIcon" class="fas fa-check-circle"></i>
  <span id="toastMsg"></span>
</div>

<script>
// ─── Sidebar / dark mode ─────────────────────────────────────
function toggleMobileSidebar() { document.getElementById('sidebar').classList.toggle('mobile-open'); }
let sidebarCollapsed = false;
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const content = document.getElementById('content');
    sidebarCollapsed = !sidebarCollapsed;
    sidebar.classList.toggle('collapsed', sidebarCollapsed);
    content.classList.toggle('collapsed-sidebar', sidebarCollapsed);
}
document.getElementById('darkModeToggle').addEventListener('click', function () {
    document.body.classList.toggle('dark');
    const icon = this.querySelector('i');
    icon.classList.toggle('fa-moon'); icon.classList.toggle('fa-sun');
    localStorage.setItem('darkMode', document.body.classList.contains('dark') ? 'enabled' : 'disabled');
});
if (localStorage.getItem('darkMode') === 'enabled') {
    document.body.classList.add('dark');
    document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon', 'fa-sun');
}
function filterByStatus(s) {
    document.querySelector('[name=status]').value = s;
    document.getElementById('filterForm').submit();
}
function toggleDD(id) {
    document.querySelectorAll('.action-dd').forEach(d => { if (d.id !== 'dd_' + id) d.classList.remove('open'); });
    document.getElementById('dd_' + id)?.classList.toggle('open');
}
document.addEventListener('click', e => {
    if (!e.target.closest('.relative')) document.querySelectorAll('.action-dd').forEach(d => d.classList.remove('open'));
});
document.querySelector('input[name="q"]')?.addEventListener('keypress', e => {
    if (e.key === 'Enter') document.getElementById('filterForm').submit();
});

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

// ─── Review Modal state ───────────────────────────────────────
let currentSubId = null;
let allReviewers = [];
let selectedReviewerId = null;

async function openReviewModal(subId, title) {
    currentSubId = subId;
    selectedReviewerId = null;
    document.getElementById('reviewModal').classList.remove('hidden');
    document.getElementById('reviewModalTitle').textContent = 'Review Assignment';
    document.getElementById('reviewModalSubtitle').textContent = 'Loading…';
    document.getElementById('assignForm').classList.add('hidden');
    switchRevTab('existing');
    setDefaultDates();

    // Load submission info for subtitle
    try {
        const r = await fetch(`submissions.php?ajax=get_submission&sub_id=${subId}`);
        const d = await r.json();
        if (d.success && d.submission) {
            const s = d.submission;
            const t = s.article_title || title || '<<untitled>>';
            document.getElementById('reviewModalSubtitle').textContent =
                (s.tracking_code ? s.tracking_code + ' · ' : '') + t.substring(0, 60) + (t.length > 60 ? '…' : '');
        }
    } catch(e) {}

    loadReviewers();
    loadAssignments();
}

function closeReviewModal() {
    document.getElementById('reviewModal').classList.add('hidden');
    currentSubId = null;
    selectedReviewerId = null;
}

// Close on backdrop
document.getElementById('reviewModal').addEventListener('click', function(e) {
    if (e.target === this) closeReviewModal();
});

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];
    ['responseDueDate','reviewDueDate','newRevRespDue','newRevReviewDue'].forEach(id => {
        const el = document.getElementById(id);
        if (!el) return;
        el.value = id.includes('Resp') || id === 'responseDueDate' ? fmt(resp) : fmt(rev);
    });
}

// ─── Tab switching ────────────────────────────────────────────
function switchRevTab(name) {
    ['existing','create','assignments'].forEach(t => {
        document.getElementById('revpanel-'+t).classList.toggle('active', t===name);
        document.getElementById('revtab-'+t).classList.toggle('active', t===name);
    });
}

// ─── Load & render reviewers ──────────────────────────────────
async function loadReviewers() {
    document.getElementById('reviewerListContainer').innerHTML =
        '<div class="text-center py-8 text-gray-400 text-sm"><i class="fas fa-spinner fa-spin text-2xl mb-2 block"></i>Loading reviewers…</div>';
    try {
        const r = await fetch('submissions.php?ajax=get_reviewers');
        const d = await r.json();
        if (!d.success) throw new Error(d.error);
        allReviewers = d.reviewers || [];
        renderReviewers(allReviewers);
    } catch(e) {
        document.getElementById('reviewerListContainer').innerHTML =
            `<div class="text-center py-6 text-red-400 text-sm"><i class="fas fa-exclamation-circle text-xl mb-2 block"></i>${e.message}</div>`;
    }
}

function renderReviewers(list) {
    const container = document.getElementById('reviewerListContainer');
    if (!list.length) {
        container.innerHTML = '<div class="text-center py-8 text-gray-400 text-sm"><i class="fas fa-users text-3xl mb-2 block opacity-30"></i>No reviewers found. Create one in the next tab.</div>';
        return;
    }
    container.innerHTML = list.map(r => {
        const name = (r.first_name || '') + ' ' + (r.last_name || '');
        const rating = parseFloat(r.reviewer_rating || 0);
        const stars = Array.from({length:5}, (_,i) =>
            `<i class="fas fa-star text-[10px] ${i < Math.floor(rating) ? 'text-yellow-400' : (i < rating ? 'text-yellow-300' : 'text-gray-200')}"></i>`
        ).join('');
        const avail = r.is_available == 1;
        const isSelected = selectedReviewerId === r.reviewer_id;
        return `<div class="reviewer-card ${isSelected?'selected':''}" onclick="selectReviewer(${r.reviewer_id},'${escJS(name.trim())}','${escJS(r.email||'')}')" data-name="${escAttr(name.toLowerCase())}" data-email="${escAttr((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-8 h-8 rounded-full bg-blue-100 text-blue-600 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">${escHTML(name.trim())}</div>
                        <div class="text-xs text-gray-400">${escHTML(r.email||'—')}</div>
                        ${r.affiliation_name ? `<div class="text-xs text-gray-400 truncate" style="max-width:200px">${escHTML(r.affiliation_name)}</div>` : ''}
                    </div>
                </div>
                <div class="flex flex-col items-end gap-1">
                    <span class="inline-flex items-center text-[10px] font-semibold px-2 py-0.5 rounded-full ${avail ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}">
                        ${avail ? 'Available' : 'Busy'}
                    </span>
                    <div class="star-display">${stars} <span class="text-[10px] text-gray-400 ml-0.5">${rating.toFixed(1)}</span></div>
                    <div class="text-[10px] text-gray-400">${r.total_reviews_completed||0} reviews done</div>
                </div>
            </div>
        </div>`;
    }).join('');
}

function filterReviewers() {
    const q = (document.getElementById('revSearch').value || '').toLowerCase().trim();
    const avail = document.getElementById('revFilterAvail').value;
    const minRating = parseFloat(document.getElementById('revFilterRating').value || 0);
    const filtered = allReviewers.filter(r => {
        const name = ((r.first_name||'')+' '+(r.last_name||'')).toLowerCase();
        const email = (r.email||'').toLowerCase();
        if (q && !name.includes(q) && !email.includes(q)) return false;
        if (avail !== '' && String(r.is_available) !== avail) return false;
        if (parseFloat(r.reviewer_rating||0) < minRating) return false;
        return true;
    });
    renderReviewers(filtered);
}

function selectReviewer(id, name, email) {
    selectedReviewerId = id;
    document.getElementById('selectedRevName').textContent = name;
    document.getElementById('selectedRevEmail').textContent = email;
    document.getElementById('assignForm').classList.remove('hidden');
    // Re-render to show selection highlight
    filterReviewers();
}

// ─── Submit assignment ────────────────────────────────────────
async function submitAssignment() {
    if (!selectedReviewerId || !currentSubId) return showToast('Select a reviewer first.', 'error');
    const btn = document.getElementById('assignBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Assigning…';
    try {
        const body = new FormData();
        body.append('assign_reviewer', '1');
        body.append('submission_id', currentSubId);
        body.append('reviewer_id',   selectedReviewerId);
        body.append('response_due_date', document.getElementById('responseDueDate').value);
        body.append('review_due_date',   document.getElementById('reviewDueDate').value);
        body.append('reviewer_type',     document.getElementById('reviewerType').value);
        const r = await fetch('submissions.php', {method:'POST', body});
        const d = await r.json();
        if (!d.success) throw new Error(d.message);
        showToast(d.message);
        loadAssignments();
        switchRevTab('assignments');
        selectedReviewerId = null;
        document.getElementById('assignForm').classList.add('hidden');
        // Update reviewer count badge in table row
        updateTableReviewerCount(currentSubId);
    } catch(e) {
        showToast(e.message, 'error');
    } finally {
        btn.disabled = false; btn.innerHTML = '<i class="fas fa-user-check"></i> Assign Reviewer';
    }
}

// ─── Create + assign reviewer ────────────────────────────────
async function submitCreateReviewer() {
    if (!currentSubId) return;
    const btn = document.getElementById('createRevBtn');
    const firstName = document.getElementById('newRevFirstName').value.trim();
    const lastName  = document.getElementById('newRevLastName').value.trim();
    const email     = document.getElementById('newRevEmail').value.trim();
    const password  = document.getElementById('newRevPassword').value || 'Reviewer@123';
    if (!firstName || !lastName || !email) return showToast('Name and email are required.', 'error');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating…';
    try {
        const body = new FormData();
        body.append('create_reviewer',    '1');
        body.append('submission_id',      currentSubId);
        body.append('first_name',         firstName);
        body.append('last_name',          lastName);
        body.append('email',              email);
        body.append('password',           password);
        body.append('response_due_date',  document.getElementById('newRevRespDue').value);
        body.append('review_due_date',    document.getElementById('newRevReviewDue').value);
        body.append('reviewer_type',      document.getElementById('newRevType').value);
        const r = await fetch('submissions.php', {method:'POST', body});
        const d = await r.json();
        if (!d.success) throw new Error(d.message);
        showToast(d.message);
        // Reset form
        ['newRevFirstName','newRevLastName','newRevEmail','newRevPassword'].forEach(id => {
            document.getElementById(id).value = '';
        });
        loadReviewers();
        loadAssignments();
        switchRevTab('assignments');
        updateTableReviewerCount(currentSubId);
    } catch(e) {
        showToast(e.message, 'error');
    } finally {
        btn.disabled = false; btn.innerHTML = '<i class="fas fa-user-plus"></i> Create & Assign Reviewer';
    }
}

// ─── Load current assignments ────────────────────────────────
async function loadAssignments() {
    if (!currentSubId) return;
    document.getElementById('assignmentsContainer').innerHTML =
        '<div class="text-center py-8 text-gray-400 text-sm"><i class="fas fa-spinner fa-spin text-2xl mb-2 block"></i>Loading…</div>';
    try {
        const r = await fetch(`submissions.php?ajax=get_assignments&sub_id=${currentSubId}`);
        const d = await r.json();
        if (!d.success) throw new Error(d.error);
        const assignments = d.assignments || [];
        // Update badge
        const badge = document.getElementById('assignCountBadge');
        if (assignments.length) { badge.textContent = assignments.length; badge.classList.remove('hidden'); }
        else badge.classList.add('hidden');
        if (!assignments.length) {
            document.getElementById('assignmentsContainer').innerHTML =
                '<div class="text-center py-8 text-gray-400 text-sm"><i class="fas fa-inbox text-3xl mb-2 block opacity-30"></i>No reviewers assigned yet.</div>';
            return;
        }
        document.getElementById('assignmentsContainer').innerHTML = assignments.map(a => {
            const name = (a.first_name||'') + ' ' + (a.last_name||'');
            const statusMap = {
                request_sent: 'Request Sent',
                accepted: 'Accepted',
                declined: 'Declined',
                cancelled: 'Cancelled',
                review_submitted: 'Review Submitted'
            };
            return `<div class="assignment-row">
                <div class="w-8 h-8 rounded-full bg-purple-100 text-purple-600 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="font-semibold text-gray-800 text-sm">${escHTML(name.trim())}</div>
                    <div class="text-xs text-gray-400">${escHTML(a.email||'—')}</div>
                    <div class="text-xs text-gray-400 mt-0.5">
                        Response due: <strong>${a.response_due_date||'—'}</strong> &nbsp;·&nbsp;
                        Review due: <strong>${a.review_due_date||'—'}</strong>
                    </div>
                </div>
                <div>
                    <span class="as-badge as-${a.assignment_status||'request_sent'}">${statusMap[a.assignment_status]||a.assignment_status}</span>
                </div>
            </div>`;
        }).join('');
    } catch(e) {
        document.getElementById('assignmentsContainer').innerHTML =
            `<div class="text-center py-6 text-red-400 text-sm">${e.message}</div>`;
    }
}

// ─── Update reviewer count in table (without page reload) ────
function updateTableReviewerCount(subId) {
    // Find the reviewer count cell for this submission and increment it
    // (a simple reload of that row's data isn't available without full page reload)
    // We just show a toast — the count will refresh on next page load
}

// ─── Escape helpers ───────────────────────────────────────────
function escHTML(s) { const d=document.createElement('div'); d.appendChild(document.createTextNode(s||'')); return d.innerHTML; }
function escJS(s)   { return (s||'').replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/"/g,'\\"'); }
function escAttr(s) { return (s||'').replace(/"/g,'&quot;'); }
</script>

</body>
</html>