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

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

/* ── Journals for filter ── */
$allJournals = [];
try {
    $allJournals = $pdo->query("SELECT journal_id, name FROM journals WHERE is_active=1 ORDER BY name")
        ->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

/* ── Filter inputs ── */
$tracking      = trim($_GET['tracking']      ?? '');
$country_f     = trim($_GET['country']       ?? '');
$journal_f     = trim($_GET['journal_id']    ?? '');
$feedback_from = trim($_GET['feedback_from'] ?? '');
$feedback_to   = trim($_GET['feedback_to']   ?? '');
$review_sent   = trim($_GET['review_sent']   ?? '');

/* ── Pagination ── */
$perPageOptions = [50, 100, 200, 500];
$perPage = isset($_GET['per_page']) && in_array((int)$_GET['per_page'], $perPageOptions)
    ? (int)$_GET['per_page'] : 100;
$page   = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $perPage;

/* ── Base WHERE conditions ── */
$where  = ["rv.reviewed_at IS NOT NULL"];
$params = [];

if ($tracking !== '') {
    $where[]  = "s.tracking_code LIKE ?";
    $params[] = "%$tracking%";
}
if ($country_f !== '') {
    $where[]  = "u_author.country LIKE ?";
    $params[] = "%$country_f%";
}
if ($journal_f !== '') {
    $where[]  = "s.journal_id = ?";
    $params[] = (int)$journal_f;
}
if ($feedback_from !== '') {
    $where[]  = "DATE(rv.reviewed_at) >= ?";
    $params[] = $feedback_from;
}
if ($feedback_to !== '') {
    $where[]  = "DATE(rv.reviewed_at) <= ?";
    $params[] = $feedback_to;
}
if ($review_sent === 'yes') {
    $where[] = "ed.created_at IS NOT NULL";
}
if ($review_sent === 'no') {
    $where[] = "ed.created_at IS NULL";
}

$whereSql = implode(' AND ', $where);

/* ── Count query ── */
$totalRecords = 0;
try {
    $cStmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM reviews rv
        LEFT JOIN submissions s         ON s.submission_id  = rv.submission_id
        LEFT JOIN users u_author        ON u_author.user_id = s.user_id
        LEFT JOIN reviewers rev         ON rev.id           = rv.reviewer_id
        LEFT JOIN users u_rev           ON u_rev.user_id    = rev.user_id
        LEFT JOIN (
            SELECT submission_id, MAX(created_at) AS created_at
            FROM editorial_decisions
            GROUP BY submission_id
        ) ed ON ed.submission_id = s.submission_id
        WHERE $whereSql
    ");
    $cStmt->execute($params);
    $totalRecords = (int)$cStmt->fetchColumn();
} catch (PDOException $e) {}

$totalPages = max(1, ceil($totalRecords / $perPage));

/* ── Main query ── */
$feedbackData = [];
try {
    $stmt = $pdo->prepare("
        SELECT
            rv.id            AS review_id,
            rv.submission_id,
            rv.reviewed_at,
            rv.recommendation,
            rv.status        AS review_status,

            s.tracking_code,
            s.submitted_at,
            s.submission_status,
            s.journal_id,

            j.name           AS journal_name,

            u_author.country AS author_country,
            CONCAT(u_author.first_name,' ',u_author.last_name) AS author_name,
            u_author.email   AS author_email,

            CONCAT(u_rev.first_name,' ',u_rev.last_name) AS reviewer_name,
            u_rev.email      AS reviewer_email,

            ra.assignment_status,
            ra.review_due_date,
            ra.request_sent_date,

            ed.created_at    AS decision_date,
            ed_full.decision AS latest_decision,

            mi.article_title,

            (
                SELECT COUNT(*)
                FROM reviews rv2
                WHERE rv2.submission_id = rv.submission_id
                  AND rv2.reviewed_at IS NOT NULL
            ) AS review_count

        FROM reviews rv
        LEFT JOIN submissions s         ON s.submission_id  = rv.submission_id
        LEFT JOIN journals j            ON j.journal_id     = s.journal_id
        LEFT JOIN users u_author        ON u_author.user_id = s.user_id
        LEFT JOIN reviewers rev         ON rev.id           = rv.reviewer_id
        LEFT JOIN users u_rev           ON u_rev.user_id    = rev.user_id
        LEFT JOIN review_assignments ra ON ra.submission_id = rv.submission_id
                                       AND ra.reviewer_id   = rev.id
        LEFT JOIN (
            SELECT submission_id, MAX(created_at) AS created_at
            FROM editorial_decisions GROUP BY submission_id
        ) ed ON ed.submission_id = s.submission_id
        LEFT JOIN editorial_decisions ed_full
            ON ed_full.submission_id = s.submission_id
           AND ed_full.created_at    = ed.created_at
        LEFT JOIN manuscript_info mi    ON mi.submission_id = s.submission_id
        WHERE $whereSql
        ORDER BY rv.reviewed_at DESC
        LIMIT $perPage OFFSET $offset
    ");
    $stmt->execute($params);
    $feedbackData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $dbError = $e->getMessage();
}

/* ── Quick stats ── */
$stats = ['total_reviews' => 0, 'today' => 0, 'this_week' => 0, 'pending_decision' => 0];
try {
    $sr = $pdo->query("
        SELECT
            COUNT(*) AS total_reviews,
            SUM(DATE(reviewed_at) = CURDATE()) AS today,
            SUM(reviewed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)) AS this_week,
            SUM(reviewed_at IS NOT NULL) AS completed
        FROM reviews WHERE reviewed_at IS NOT NULL
    ")->fetch(PDO::FETCH_ASSOC);
    if ($sr) {
        $stats['total_reviews'] = (int)$sr['total_reviews'];
        $stats['today']         = (int)$sr['today'];
        $stats['this_week']     = (int)$sr['this_week'];
    }
    $pd = $pdo->query("
        SELECT COUNT(DISTINCT rv.submission_id) FROM reviews rv
        LEFT JOIN (SELECT submission_id FROM editorial_decisions GROUP BY submission_id) ed
            ON ed.submission_id = rv.submission_id
        WHERE rv.reviewed_at IS NOT NULL AND ed.submission_id IS NULL
    ")->fetchColumn();
    $stats['pending_decision'] = (int)$pd;
} catch (PDOException $e) {}

$user_name = $_SESSION['username'] ?? 'Admin';
$active_section = 'live_feedback';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Live Feedback Dashboard — Communeglobal 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">
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<style>
body { font-family:'Roboto',sans-serif; margin:0; height:100vh; overflow:hidden; transition:background-color .3s; }
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, .sidebar.collapsed nav ul li a span { 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 15px; cursor:pointer; transition:background .2s; }
.nav-item:hover { background:#4a5568; }
.nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
@media(max-width:768px){ .sidebar{transform:translateX(-250px)} .sidebar.mobile-open{transform:translateX(0)} .content{margin-left:0} }

body.dark .bg-white { background-color:#2d3748; }
body.dark .text-gray-700 { color:#d1d5db; }
body.dark .bg-gray-50 { background-color:#3f3f3f; }
body.dark input, body.dark select { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }

/* Tabs */
.tab-btn { padding:10px 20px; font-size:13px; font-weight:500; color:#64748b; border-bottom:3px solid transparent; transition:all .2s; cursor:pointer; white-space:nowrap; }
.tab-btn:hover { color:#4f46e5; background:#f8fafc; }
.tab-btn.tab-active { color:#4f46e5; border-bottom-color:#4f46e5; font-weight:700; }
.tab-pane { display:none; }
.tab-pane.active { display:block; }

/* Table */
.data-table { border-collapse:collapse; width:100%; }
.data-table th { background:#f8fafc; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.4px; color:#64748b; padding:10px 12px; text-align:left; border-bottom:2px solid #e2e8f0; white-space:nowrap; }
.data-table td { padding:9px 12px; font-size:12.5px; border-bottom:1px solid #f1f5f9; vertical-align:middle; }
.data-table tbody tr:hover { background:#f8fafc; }
body.dark .data-table th { background:#374151; color:#9ca3af; border-color:#4b5563; }
body.dark .data-table td { border-color:#374151; }
body.dark .data-table tbody tr:hover { background:#374151; }

/* Status badges */
.sbadge { display:inline-flex; align-items:center; gap:3px; padding:2px 8px; border-radius:9999px; font-size:10px; font-weight:700; }
.sb-submitted { background:rgba(59,130,246,.1); color:#2563eb; }
.sb-under_review { background:rgba(245,158,11,.1); color:#d97706; }
.sb-accepted { background:rgba(16,185,129,.1); color:#059669; }
.sb-rejected { background:rgba(239,68,68,.1); color:#dc2626; }
.sb-draft { background:rgba(156,163,175,.12); color:#6b7280; }

.rec-accepted { background:#dcfce7; color:#166534; }
.rec-rejected { background:#fee2e2; color:#991b1b; }
.rec-resubmit { background:#fef9c3; color:#854d0e; }
.rec-other    { background:#f1f5f9; color:#475569; }

/* Modal */
.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.55); z-index:9000; display:none; align-items:center; justify-content:center; }
.modal-overlay.open { display:flex; }
.modal-box { background:#fff; border-radius:12px; width:90%; max-width:900px; max-height:85vh; overflow:hidden; display:flex; flex-direction:column; box-shadow:0 25px 60px rgba(0,0,0,.2); }
body.dark .modal-box { background:#2d3748; }
.modal-header { padding:16px 20px; border-bottom:1px solid #e2e8f0; display:flex; align-items:center; justify-content:space-between; }
.modal-body { overflow-y:auto; padding:0; flex:1; }
.modal-footer { padding:12px 20px; border-top:1px solid #e2e8f0; display:flex; justify-content:flex-end; }

/* Toast */
.toast { position:fixed; bottom:20px; right:20px; z-index:9999; padding:12px 18px; border-radius:8px; font-size:13px; font-weight:600; display:flex; align-items:center; gap:8px; box-shadow:0 4px 20px rgba(0,0,0,.15); transform:translateY(60px); opacity:0; transition:all .25s; }
.toast.show { transform:translateY(0); opacity:1; }
.toast-s { background:#ECFDF5; color:#065F46; border:1px solid #A7F3D0; }
.toast-e { background:#FEF2F2; color:#991B1B; border:1px solid #FECACA; }

/* Skeleton loader */
.skeleton { background:linear-gradient(90deg,#f0f0f0 25%,#e0e0e0 50%,#f0f0f0 75%); background-size:200% 100%; animation:shimmer 1.5s infinite; border-radius:4px; height:14px; }
@keyframes shimmer { 0%{background-position:200% 0} 100%{background-position:-200% 0} }
</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-3 flex items-center justify-between sticky top-0 z-10 shadow-sm">
    <div class="flex items-center gap-3">
      <button onclick="toggleSidebar()" id="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-indigo-600"><i class="fas fa-home"></i></a>
        <i class="fas fa-chevron-right text-xs text-gray-300"></i>
        <span class="text-gray-800 font-bold flex items-center gap-2">
          <i class="fas fa-comments text-indigo-500"></i> Live Feedback Dashboard
        </span>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <span class="hidden md:block text-sm text-gray-500">Welcome, <strong><?= htmlspecialchars($user_name) ?></strong></span>
      <button id="darkModeToggle" class="text-gray-500 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
        <i class="fas fa-moon"></i>
      </button>
      <a href="logout.php" class="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600 text-sm flex items-center gap-1">
        <i class="fas fa-sign-out-alt"></i> Logout
      </a>
    </div>
  </div>

  <main class="p-5">

    <?php if (!empty($dbError)): ?>
    <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-3 rounded mb-4 text-sm">
      <strong>DB Error:</strong> <?= htmlspecialchars($dbError) ?>
    </div>
    <?php endif; ?>

    <!-- Stats Cards -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
      <?php $sc = [
        ['Total Reviews',    $stats['total_reviews'],    'text-indigo-600', 'bg-indigo-50',  'fa-star'],
        ['Received Today',   $stats['today'],            'text-green-600',  'bg-green-50',   'fa-calendar-day'],
        ['Last 7 Days',      $stats['this_week'],        'text-blue-600',   'bg-blue-50',    'fa-calendar-week'],
        ['Pending Decision', $stats['pending_decision'], 'text-amber-600',  'bg-amber-50',   'fa-hourglass-half'],
      ]; foreach ($sc as $c): ?>
      <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100">
        <div class="w-8 h-8 <?= $c[3] ?> rounded-lg flex items-center justify-center mb-1.5">
          <i class="fas <?= $c[4] ?> <?= $c[2] ?> text-xs"></i>
        </div>
        <div class="text-xl font-bold <?= $c[2] ?>"><?= number_format($c[1]) ?></div>
        <div class="text-xs text-gray-500 font-medium"><?= $c[0] ?></div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Tabs -->
    <div class="bg-white rounded-xl shadow mb-4">
      <div class="flex border-b overflow-x-auto">
        <button class="tab-btn tab-active" data-tab="live">
          <i class="fas fa-comments mr-1 text-indigo-400"></i> Live Feedback
        </button>
        <button class="tab-btn" data-tab="load">
          <i class="fas fa-users-cog mr-1 text-blue-400"></i> Reviewer Load
        </button>
        <button class="tab-btn" data-tab="received">
          <i class="fas fa-chart-bar mr-1 text-green-400"></i> Feedback Received
        </button>
      </div>
    </div>

    <!-- ════════════════ TAB 1: LIVE FEEDBACK ════════════════ -->
    <div id="tab-live" class="tab-pane active">

      <!-- Filter -->
      <div class="bg-white p-4 rounded-xl shadow mb-4">
        <form method="GET" class="flex flex-wrap items-end gap-3 text-sm">
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Feedback From</label>
            <input type="date" name="feedback_from" value="<?= htmlspecialchars($feedback_from) ?>"
                   class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Feedback To</label>
            <input type="date" name="feedback_to" value="<?= htmlspecialchars($feedback_to) ?>"
                   class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Tracking Code</label>
            <input type="text" name="tracking" value="<?= htmlspecialchars($tracking) ?>"
                   placeholder="e.g. RSIS-AB1234"
                   class="border border-gray-300 rounded-lg px-3 py-2 text-sm w-36">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Country</label>
            <input type="text" name="country" value="<?= htmlspecialchars($country_f) ?>"
                   placeholder="e.g. India"
                   class="border border-gray-300 rounded-lg px-3 py-2 text-sm w-28">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Journal</label>
            <select name="journal_id" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
              <option value="">All Journals</option>
              <?php foreach ($allJournals as $j): ?>
              <option value="<?= (int)$j['journal_id'] ?>" <?= $journal_f == $j['journal_id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($j['name']) ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Decision Sent</label>
            <select name="review_sent" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
              <option value="">All</option>
              <option value="yes" <?= $review_sent === 'yes' ? 'selected' : '' ?>>Yes</option>
              <option value="no"  <?= $review_sent === 'no'  ? 'selected' : '' ?>>No</option>
            </select>
          </div>
          <div class="flex gap-2 items-end">
            <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 text-sm font-semibold flex items-center gap-1">
              <i class="fas fa-search"></i> Filter
            </button>
            <a href="live_feedback.php" class="bg-gray-500 text-white px-3 py-2 rounded-lg hover:bg-gray-600 text-sm">
              <i class="fas fa-times"></i>
            </a>
          </div>
          <div class="ml-auto">
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Per Page</label>
            <select name="per_page" onchange="this.form.submit()" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
              <?php foreach ($perPageOptions as $opt): ?>
              <option value="<?= $opt ?>" <?= $perPage == $opt ? 'selected' : '' ?>><?= $opt ?> / page</option>
              <?php endforeach; ?>
            </select>
          </div>
        </form>
      </div>

      <!-- Table -->
      <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="flex items-center justify-between px-4 py-3 border-b border-gray-100 flex-wrap gap-2">
          <div class="flex items-center gap-2">
            <span class="text-sm font-bold text-gray-700">
              <i class="fas fa-list text-indigo-400 mr-1"></i> Reviews Received
            </span>
            <span class="bg-indigo-100 text-indigo-700 text-xs font-bold px-2 py-0.5 rounded-full">
              <?= number_format($totalRecords) ?> total
            </span>
          </div>
          <button onclick="exportExcel()" class="bg-green-600 text-white px-3 py-1.5 rounded-lg hover:bg-green-700 text-xs font-semibold flex items-center gap-1">
            <i class="fas fa-file-excel"></i> Export
          </button>
        </div>

        <?php if (empty($feedbackData)): ?>
        <div class="text-center py-16 text-gray-400">
          <i class="fas fa-inbox text-4xl mb-3 block opacity-30"></i>
          <p class="text-sm">No feedback records found for the selected filters.</p>
        </div>
        <?php else: ?>
        <div style="overflow-x:auto; max-height:calc(100vh - 460px)">
          <table class="data-table" id="feedbackTable">
            <thead>
              <tr>
                <th class="px-3">Sub. Date</th>
                <th class="px-3">Sub. ID</th>
                <th class="px-3">Tracking</th>
                <th class="px-3">Title</th>
                <th class="px-3">Author</th>
                <th class="px-3">Country</th>
                <th class="px-3">Journal</th>
                <th class="px-3 text-center">Rev. Count</th>
                <th class="px-3">Feedback Date</th>
                <th class="px-3">Decision Date</th>
                <th class="px-3">Reviewer</th>
                <th class="px-3">Recommendation</th>
                <th class="px-3">Status</th>
                <th class="px-3 text-center">Action</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($feedbackData as $row):
                $subStatus = $row['submission_status'] ?? 'draft';
                $rec = strtolower($row['recommendation'] ?? '');
                $recClass = match(true) {
                    str_contains($rec, 'accept') => 'rec-accepted',
                    str_contains($rec, 'reject') => 'rec-rejected',
                    str_contains($rec, 'resubmit') || str_contains($rec, 'revisi') => 'rec-resubmit',
                    default => 'rec-other',
                };
                $daysSince = $row['reviewed_at']
                    ? (int)((time() - strtotime($row['reviewed_at'])) / 86400)
                    : null;
              ?>
              <tr>
                <td class="px-3 text-xs text-gray-400 whitespace-nowrap">
                  <?= $row['submitted_at'] ? date('d M Y', strtotime($row['submitted_at'])) : '—' ?>
                </td>
                <td class="px-3">
                  <span class="font-mono text-xs bg-gray-100 px-1.5 py-0.5 rounded">#<?= $row['submission_id'] ?></span>
                </td>
                <td class="px-3">
                  <?php if ($row['tracking_code']): ?>
                  <span class="font-mono text-xs font-bold text-indigo-800 bg-indigo-50 border border-indigo-200 rounded px-1.5 py-0.5">
                    <?= htmlspecialchars($row['tracking_code']) ?>
                  </span>
                  <?php else: ?>
                  <span class="text-gray-300 text-xs">—</span>
                  <?php endif; ?>
                </td>
                <td class="px-3 max-w-xs">
                  <div class="text-xs text-gray-700 truncate" style="max-width:180px"
                       title="<?= htmlspecialchars($row['article_title'] ?? '') ?>">
                    <?= htmlspecialchars(mb_strimwidth($row['article_title'] ?? '—', 0, 55, '…')) ?>
                  </div>
                </td>
                <td class="px-3">
                  <div class="text-xs font-medium text-gray-700"><?= htmlspecialchars(trim($row['author_name'])) ?></div>
                  <div class="text-xs text-gray-400"><?= htmlspecialchars($row['author_email']) ?></div>
                </td>
                <td class="px-3 text-xs text-gray-500"><?= htmlspecialchars($row['author_country'] ?? '—') ?></td>
                <td class="px-3 text-xs text-gray-600"><?= htmlspecialchars($row['journal_name'] ?? '—') ?></td>
                <td class="px-3 text-center">
                  <span class="inline-flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold
                    <?= $row['review_count'] >= 2 ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700' ?>">
                    <?= $row['review_count'] ?>
                  </span>
                </td>
                <td class="px-3 text-xs whitespace-nowrap">
                  <?php if ($row['reviewed_at']): ?>
                  <div class="font-medium text-gray-700"><?= date('d M Y', strtotime($row['reviewed_at'])) ?></div>
                  <?php if ($daysSince !== null): ?>
                  <div class="text-gray-400"><?= $daysSince === 0 ? 'Today' : "$daysSince days ago" ?></div>
                  <?php endif; ?>
                  <?php else: ?>—<?php endif; ?>
                </td>
                <td class="px-3 text-xs whitespace-nowrap">
                  <?= $row['decision_date']
                    ? '<span class="text-green-600 font-medium">' . date('d M Y', strtotime($row['decision_date'])) . '</span>'
                    : '<span class="text-amber-500 italic">Pending</span>' ?>
                </td>
                <td class="px-3">
                  <div class="text-xs font-medium text-gray-700"><?= htmlspecialchars(trim($row['reviewer_name'])) ?></div>
                  <div class="text-xs text-gray-400"><?= htmlspecialchars($row['reviewer_email'] ?? '') ?></div>
                </td>
                <td class="px-3">
                  <?php if ($row['recommendation']): ?>
                  <span class="sbadge <?= $recClass ?>">
                    <?= htmlspecialchars(ucfirst($row['recommendation'])) ?>
                  </span>
                  <?php else: ?><span class="text-gray-300 text-xs">—</span><?php endif; ?>
                </td>
                <td class="px-3">
                  <span class="sbadge sb-<?= htmlspecialchars($subStatus) ?>">
                    <?= ucfirst(str_replace('_', ' ', $subStatus)) ?>
                  </span>
                </td>
                <td class="px-3 text-center whitespace-nowrap">
                  <a href="submission_review.php?id=<?= $row['submission_id'] ?>"
                     title="View Review Assignment"
                     class="text-indigo-500 hover:text-indigo-700 text-base mx-0.5">
                    <i class="fas fa-eye"></i>
                  </a>
                  <button onclick="viewReviewDetails(<?= $row['review_id'] ?>, <?= $row['submission_id'] ?>)"
                          title="View Full Review"
                          class="text-blue-500 hover:text-blue-700 text-base mx-0.5 bg-transparent border-none cursor-pointer">
                    <i class="fas fa-file-alt"></i>
                  </button>
                  <a href="submission_view.php?id=<?= $row['submission_id'] ?>"
                     title="View Submission"
                     class="text-green-500 hover:text-green-700 text-base mx-0.5">
                    <i class="fas fa-external-link-alt"></i>
                  </a>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
        <div class="px-4 py-3 border-t flex items-center justify-between flex-wrap gap-2">
          <div class="text-xs text-gray-400">
            Showing <?= number_format(($page-1)*$perPage+1) ?>–<?= number_format(min($page*$perPage,$totalRecords)) ?>
            of <?= number_format($totalRecords) ?>
          </div>
          <div class="flex gap-1">
            <?php
            $qs = $_GET; unset($qs['page']);
            $baseUrl = '?' . http_build_query($qs) . '&page=';
            $start = max(1, $page - 2);
            $end   = min($totalPages, $page + 2);
            if ($page > 1): ?>
            <a href="<?= $baseUrl.($page-1) ?>" class="px-3 py-1 text-xs rounded bg-gray-100 hover:bg-gray-200 text-gray-600">‹</a>
            <?php endif;
            for ($i = $start; $i <= $end; $i++): ?>
            <a href="<?= $baseUrl.$i ?>"
               class="px-3 py-1 text-xs rounded <?= $i == $page ? 'bg-indigo-600 text-white' : 'bg-gray-100 hover:bg-gray-200 text-gray-600' ?>">
              <?= $i ?>
            </a>
            <?php endfor;
            if ($page < $totalPages): ?>
            <a href="<?= $baseUrl.($page+1) ?>" class="px-3 py-1 text-xs rounded bg-gray-100 hover:bg-gray-200 text-gray-600">›</a>
            <?php endif; ?>
          </div>
        </div>
        <?php endif; ?>
        <?php endif; ?>
      </div>
    </div><!-- /tab-live -->

    <!-- ════════════════ TAB 2: REVIEWER LOAD ════════════════ -->
    <div id="tab-load" class="tab-pane">
      <div class="bg-white p-4 rounded-xl shadow mb-4">
        <div class="flex flex-wrap items-end gap-3 text-sm">
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Date Range</label>
            <select id="load_range" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
              <option value="today">Today</option>
              <option value="yesterday">Yesterday</option>
              <option value="3">Last 3 Days</option>
              <option value="7" selected>Last 7 Days</option>
              <option value="30">Last 30 Days</option>
              <option value="custom">Custom Range</option>
            </select>
          </div>
          <div id="load_custom_wrap" class="hidden flex gap-2">
            <div>
              <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">From</label>
              <input type="date" id="load_from" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
            </div>
            <div>
              <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">To</label>
              <input type="date" id="load_to" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
            </div>
          </div>
          <button onclick="loadReviewerStats()"
                  class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 text-sm font-semibold flex items-center gap-1">
            <i class="fas fa-search"></i> Load Stats
          </button>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="px-4 py-3 border-b flex items-center gap-2">
          <span class="text-sm font-bold text-gray-700"><i class="fas fa-users-cog text-blue-400 mr-1"></i> Reviewer Workload</span>
          <span id="loadCount" class="bg-blue-100 text-blue-700 text-xs font-bold px-2 py-0.5 rounded-full hidden"></span>
        </div>
        <div style="overflow-x:auto">
          <table class="data-table" id="loadTable">
            <thead>
              <tr>
                <th class="px-3">Reviewer</th>
                <th class="px-3">Research Interests</th>
                <th class="px-3 text-center">Total Assigned</th>
                <th class="px-3 text-center">Active</th>
                <th class="px-3 text-center">Completed</th>
                <th class="px-3 text-center">Declined</th>
                <th class="px-3 text-center">Overdue</th>
                <th class="px-3 text-center">% Complete</th>
              </tr>
            </thead>
            <tbody id="reviewerLoadBody">
              <tr><td colspan="8" class="text-center py-12 text-gray-400 text-sm">
                <i class="fas fa-arrow-up mr-1"></i> Select a range and click "Load Stats"
              </td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div><!-- /tab-load -->

    <!-- ════════════════ TAB 3: FEEDBACK RECEIVED ════════════════ -->
    <div id="tab-received" class="tab-pane">
      <div class="bg-white p-4 rounded-xl shadow mb-4">
        <div class="flex flex-wrap items-end gap-3 text-sm">
          <div>
            <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Date Range</label>
            <select id="fb_range" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
              <option value="today">Today</option>
              <option value="yesterday">Yesterday</option>
              <option value="3">Last 3 Days</option>
              <option value="7" selected>Last 7 Days</option>
              <option value="30">Last 30 Days</option>
              <option value="custom">Custom Range</option>
            </select>
          </div>
          <div id="fb_custom_wrap" class="hidden flex gap-2">
            <div>
              <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">From</label>
              <input type="date" id="fb_from" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
            </div>
            <div>
              <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">To</label>
              <input type="date" id="fb_to" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
            </div>
          </div>
          <button onclick="loadFeedbackStats()"
                  class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 text-sm font-semibold flex items-center gap-1">
            <i class="fas fa-chart-bar"></i> Load Stats
          </button>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="px-4 py-3 border-b flex items-center gap-2">
          <span class="text-sm font-bold text-gray-700"><i class="fas fa-chart-bar text-green-400 mr-1"></i> Feedback by Reviewer</span>
          <span id="fbCount" class="bg-green-100 text-green-700 text-xs font-bold px-2 py-0.5 rounded-full hidden"></span>
        </div>
        <div style="overflow-x:auto">
          <table class="data-table" id="fbTable">
            <thead>
              <tr>
                <th class="px-3">Reviewer</th>
                <th class="px-3">Email</th>
                <th class="px-3">Research Interests</th>
                <th class="px-3 text-center">Feedback Count</th>
                <th class="px-3 text-center">Avg Days Taken</th>
              </tr>
            </thead>
            <tbody id="feedbackStatsBody">
              <tr><td colspan="5" class="text-center py-12 text-gray-400 text-sm">
                <i class="fas fa-arrow-up mr-1"></i> Select a range and click "Load Stats"
              </td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div><!-- /tab-received -->

  </main>
</div>

<!-- ════ Detail Modal ════ -->
<div id="detailModal" class="modal-overlay">
  <div class="modal-box">
    <div class="modal-header">
      <div>
        <h3 class="font-bold text-gray-800" id="modalTitle">Review Details</h3>
        <p class="text-xs text-gray-400 mt-0.5" id="modalSubtitle"></p>
      </div>
      <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 text-xl w-8 h-8 flex items-center justify-center">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <div class="modal-body" id="modalContent">
      <div class="p-8 text-center text-gray-400"><i class="fas fa-spinner fa-spin text-2xl"></i></div>
    </div>
    <div class="modal-footer">
      <button onclick="closeModal()" class="bg-gray-500 text-white px-5 py-2 rounded-lg text-sm hover:bg-gray-600">Close</button>
    </div>
  </div>
</div>

<!-- ════ Assignment List Modal ════ -->
<div id="assignModal" class="modal-overlay">
  <div class="modal-box">
    <div class="modal-header">
      <div>
        <h3 class="font-bold text-gray-800" id="assignModalTitle">Assignments</h3>
        <p class="text-xs text-gray-400 mt-0.5" id="assignModalSubtitle"></p>
      </div>
      <button onclick="closeAssignModal()" class="text-gray-400 hover:text-gray-600 text-xl w-8 h-8 flex items-center justify-center">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <div class="modal-body" id="assignModalContent">
      <div class="p-8 text-center text-gray-400"><i class="fas fa-spinner fa-spin text-2xl"></i></div>
    </div>
    <div class="modal-footer">
      <button onclick="closeAssignModal()" class="bg-gray-500 text-white px-5 py-2 rounded-lg text-sm hover:bg-gray-600">Close</button>
    </div>
  </div>
</div>

<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'); }
var _sc = false;
function toggleSidebar(){
  _sc = !_sc;
  document.getElementById('sidebar').classList.toggle('collapsed', _sc);
  document.getElementById('content').classList.toggle('collapsed-sidebar', _sc);
}
document.getElementById('toggleSidebar')?.addEventListener('click', toggleSidebar);
document.getElementById('darkModeToggle').addEventListener('click', function(){
  document.body.classList.toggle('dark');
  var ic = this.querySelector('i'); ic.classList.toggle('fa-moon'); ic.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');
}

/* ── Tabs ── */
document.querySelectorAll('.tab-btn').forEach(function(btn){
  btn.addEventListener('click', function(){
    document.querySelectorAll('.tab-btn').forEach(function(b){ b.classList.remove('tab-active'); });
    this.classList.add('tab-active');
    document.querySelectorAll('.tab-pane').forEach(function(p){ p.classList.remove('active'); });
    document.getElementById('tab-' + this.dataset.tab).classList.add('active');
  });
});

/* ── Custom range toggles ── */
document.getElementById('load_range').addEventListener('change', function(){
  document.getElementById('load_custom_wrap').classList.toggle('hidden', this.value !== 'custom');
});
document.getElementById('fb_range').addEventListener('change', function(){
  document.getElementById('fb_custom_wrap').classList.toggle('hidden', this.value !== 'custom');
});

/* ── Export ── */
function exportExcel(){
  var wb = XLSX.utils.table_to_book(document.getElementById('feedbackTable'), {sheet:'Live Feedback'});
  XLSX.writeFile(wb, 'LiveFeedback_' + new Date().toISOString().slice(0,10) + '.xlsx');
}

/* ── Toast ── */
function showToast(msg, type){
  var t = document.getElementById('toast'), ic = document.getElementById('toastIcon');
  document.getElementById('toastMsg').textContent = msg;
  t.className = 'toast toast-' + (type||'s') + ' show';
  ic.className = 'fas ' + (type === 'e' ? 'fa-exclamation-circle' : 'fa-check-circle');
  setTimeout(function(){ t.classList.remove('show'); }, 3500);
}

/* ── Review detail modal ── */
function viewReviewDetails(reviewId, submissionId){
  document.getElementById('modalTitle').textContent = 'Review Details';
  document.getElementById('modalSubtitle').textContent = 'Submission #' + submissionId;
  document.getElementById('modalContent').innerHTML = '<div class="p-8 text-center text-gray-400"><i class="fas fa-spinner fa-spin text-2xl"></i></div>';
  document.getElementById('detailModal').classList.add('open');
  fetch('ajax/review_detail_modal.php?review_id=' + reviewId)
    .then(function(r){ return r.text(); })
    .then(function(html){ document.getElementById('modalContent').innerHTML = html; })
    .catch(function(){ document.getElementById('modalContent').innerHTML = '<div class="p-8 text-center text-red-400">Failed to load details.</div>'; });
}
function closeModal(){ document.getElementById('detailModal').classList.remove('open'); }
document.getElementById('detailModal').addEventListener('click', function(e){
  if (e.target === this) closeModal();
});

/* ── Assignment list modal ── */
function openAssignModal(reviewerId, name, range, from, to){
  document.getElementById('assignModalTitle').textContent = 'Assignments — ' + name;
  document.getElementById('assignModalSubtitle').textContent = 'Range: ' + range + (from ? ' | ' + from + ' → ' + to : '');
  document.getElementById('assignModalContent').innerHTML = '<div class="p-8 text-center text-gray-400"><i class="fas fa-spinner fa-spin text-2xl"></i></div>';
  document.getElementById('assignModal').classList.add('open');
  fetch('ajax/reviewer_assignments_modal.php?id=' + reviewerId + '&range=' + range + '&from=' + from + '&to=' + to)
    .then(function(r){ return r.text(); })
    .then(function(html){ document.getElementById('assignModalContent').innerHTML = html; })
    .catch(function(){ document.getElementById('assignModalContent').innerHTML = '<div class="p-8 text-center text-red-400">Failed to load.</div>'; });
}
function closeAssignModal(){ document.getElementById('assignModal').classList.remove('open'); }
document.getElementById('assignModal').addEventListener('click', function(e){
  if (e.target === this) closeAssignModal();
});

/* ── Feedback list modal ── */
function openFeedbackModal(reviewerId, name, range, from, to){
  document.getElementById('assignModalTitle').textContent = 'Feedback Submitted — ' + name;
  document.getElementById('assignModalSubtitle').textContent = 'Range: ' + range + (from ? ' | ' + from + ' → ' + to : '');
  document.getElementById('assignModalContent').innerHTML = '<div class="p-8 text-center text-gray-400"><i class="fas fa-spinner fa-spin text-2xl"></i></div>';
  document.getElementById('assignModal').classList.add('open');
  fetch('ajax/reviewer_feedback_modal.php?id=' + reviewerId + '&range=' + range + '&from=' + from + '&to=' + to)
    .then(function(r){ return r.text(); })
    .then(function(html){ document.getElementById('assignModalContent').innerHTML = html; })
    .catch(function(){ document.getElementById('assignModalContent').innerHTML = '<div class="p-8 text-center text-red-400">Failed to load.</div>'; });
}

/* ── Load Reviewer Stats ── */
function loadReviewerStats(){
  var range = document.getElementById('load_range').value;
  var from  = document.getElementById('load_from').value || '';
  var to    = document.getElementById('load_to').value   || '';
  var body  = document.getElementById('reviewerLoadBody');
  // skeleton
  body.innerHTML = Array(5).fill(`
    <tr>${Array(8).fill('<td class="px-3 py-3"><div class="skeleton"></div></td>').join('')}</tr>
  `).join('');
  fetch('ajax/reviewer_load_stats.php?range=' + range + '&from=' + from + '&to=' + to)
    .then(function(r){ return r.json(); })
    .then(function(data){
      if (!data.length){
        body.innerHTML = '<tr><td colspan="8" class="text-center py-10 text-gray-400 text-sm">No data for this range.</td></tr>';
        document.getElementById('loadCount').textContent = '0'; document.getElementById('loadCount').classList.remove('hidden');
        return;
      }
      document.getElementById('loadCount').textContent = data.length + ' reviewers';
      document.getElementById('loadCount').classList.remove('hidden');
      body.innerHTML = data.map(function(r){
        var pct = parseFloat(r.completion_percent || 0);
        var barColor = pct >= 80 ? '#10b981' : pct >= 50 ? '#f59e0b' : '#ef4444';
        return `<tr>
          <td class="px-3">
            <div class="font-medium text-xs text-gray-800">${escHtml(r.reviewer)}</div>
            <div class="text-xs text-gray-400">${escHtml(r.reviewer_email || '')}</div>
          </td>
          <td class="px-3 text-xs text-gray-500" style="max-width:160px">
            <div class="truncate" title="${escHtml(r.reviewing_interests || '')}">${escHtml((r.reviewing_interests || '').substring(0,50))}${(r.reviewing_interests||'').length>50?'…':''}</div>
          </td>
          <td class="px-3 text-center">
            <a href="#" class="assignedBtn text-indigo-600 font-bold text-sm hover:underline"
               data-id="${r.reviewer_id}" data-name="${escHtml(r.reviewer)}"
               data-range="${range}" data-from="${from}" data-to="${to}">
              ${r.total_assigned}
            </a>
          </td>
          <td class="px-3 text-center"><span class="font-medium text-blue-600">${r.active}</span></td>
          <td class="px-3 text-center"><span class="font-medium text-green-600">${r.completed}</span></td>
          <td class="px-3 text-center"><span class="font-medium text-amber-600">${r.declined || 0}</span></td>
          <td class="px-3 text-center"><span class="font-medium text-red-600">${r.total_overdue}</span></td>
          <td class="px-3">
            <div class="flex items-center gap-2">
              <div style="flex:1;background:#f1f5f9;border-radius:99px;height:6px;overflow:hidden">
                <div style="width:${pct}%;background:${barColor};height:100%;border-radius:99px;transition:width .5s"></div>
              </div>
              <span class="text-xs font-bold" style="color:${barColor}">${pct}%</span>
            </div>
          </td>
        </tr>`;
      }).join('');
    })
    .catch(function(){
      body.innerHTML = '<tr><td colspan="8" class="text-center py-10 text-red-400 text-sm">Failed to load reviewer stats.</td></tr>';
    });
}

/* ── Load Feedback Stats ── */
function loadFeedbackStats(){
  var range = document.getElementById('fb_range').value;
  var from  = document.getElementById('fb_from').value  || '';
  var to    = document.getElementById('fb_to').value    || '';
  var body  = document.getElementById('feedbackStatsBody');
  body.innerHTML = Array(5).fill(`
    <tr>${Array(5).fill('<td class="px-3 py-3"><div class="skeleton"></div></td>').join('')}</tr>
  `).join('');
  fetch('ajax/reviewer_feedback_stats.php?range=' + range + '&from=' + from + '&to=' + to)
    .then(function(r){ return r.json(); })
    .then(function(data){
      if (!data.length){
        body.innerHTML = '<tr><td colspan="5" class="text-center py-10 text-gray-400 text-sm">No feedback for this range.</td></tr>';
        document.getElementById('fbCount').textContent = '0'; document.getElementById('fbCount').classList.remove('hidden');
        return;
      }
      document.getElementById('fbCount').textContent = data.length + ' reviewers';
      document.getElementById('fbCount').classList.remove('hidden');
      body.innerHTML = data.map(function(r){
        return `<tr>
          <td class="px-3">
            <div class="font-medium text-xs text-gray-800">${escHtml(r.reviewer)}</div>
          </td>
          <td class="px-3 text-xs text-gray-400">${escHtml(r.reviewer_email || '')}</td>
          <td class="px-3 text-xs text-gray-500">${escHtml((r.reviewing_interests||'').substring(0,60))}${(r.reviewing_interests||'').length>60?'…':''}</td>
          <td class="px-3 text-center">
            <a href="#" class="feedbackBtn text-green-600 font-bold text-sm hover:underline"
               data-id="${r.reviewer_id}" data-name="${escHtml(r.reviewer)}"
               data-range="${range}" data-from="${from}" data-to="${to}">
              ${r.feedback_count}
            </a>
          </td>
          <td class="px-3 text-center text-xs text-gray-600">${r.avg_days ? r.avg_days + ' days' : '—'}</td>
        </tr>`;
      }).join('');
    })
    .catch(function(){
      body.innerHTML = '<tr><td colspan="5" class="text-center py-10 text-red-400 text-sm">Failed to load feedback stats.</td></tr>';
    });
}

/* ── Delegated click for dynamic modal links ── */
document.addEventListener('click', function(e){
  if (e.target.classList.contains('assignedBtn') || e.target.closest('.assignedBtn')){
    e.preventDefault();
    var el = e.target.classList.contains('assignedBtn') ? e.target : e.target.closest('.assignedBtn');
    openAssignModal(el.dataset.id, el.dataset.name, el.dataset.range, el.dataset.from, el.dataset.to);
  }
  if (e.target.classList.contains('feedbackBtn') || e.target.closest('.feedbackBtn')){
    e.preventDefault();
    var el = e.target.classList.contains('feedbackBtn') ? e.target : e.target.closest('.feedbackBtn');
    openFeedbackModal(el.dataset.id, el.dataset.name, el.dataset.range, el.dataset.from, el.dataset.to);
  }
});

/* ── Escape HTML helper ── */
function escHtml(str){
  return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>
</body>
</html>