<?php
/**
 * admin/reviewer-due-dates.php
 * Reviewer Due Dates Dashboard — Communeglobal Admin
 *
 * FIXES v2:
 *  - Default sub_from = 30 days ago (not today)
 *  - Removed Reviewer Load tab
 *  - Fixed reviewers JOIN
 *  - Removed is_active=1 from journals query
 *  - Added DB debug block at top
 *  - Proper NULL-safe phone concat
 *  - accepted_date / submitted_date display with date shown below badge
 */

ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();

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

$today        = date('Y-m-d');
$default_from = date('Y-m-d', strtotime('-30 days'));

$umi           = trim($_GET['umi']            ?? '');
$journal_id    = trim($_GET['journal_id']     ?? '');
$assigned_from = trim($_GET['assigned_from']  ?? '');
$assigned_to   = trim($_GET['assigned_to']    ?? '');
$response_from = trim($_GET['response_from']  ?? '');
$response_to   = trim($_GET['response_to']    ?? '');
$review_from   = trim($_GET['review_from']    ?? '');
$review_to     = trim($_GET['review_to']      ?? '');
$sub_from      = trim($_GET['sub_from']       ?? $default_from);
$sub_to        = trim($_GET['sub_to']         ?? $today);
$resp_yesno    = trim($_GET['resp_yesno']     ?? '');
$rev_yesno     = trim($_GET['rev_yesno']      ?? '');

$where  = ['1=1'];
$params = [];

if ($sub_from !== '') { $where[] = "DATE(s.submitted_at) >= ?"; $params[] = $sub_from; }
if ($sub_to   !== '') { $where[] = "DATE(s.submitted_at) <= ?"; $params[] = $sub_to; }
if ($resp_yesno === 'yes') $where[] = "ra.accepted_date IS NOT NULL";
if ($resp_yesno === 'no')  $where[] = "ra.accepted_date IS NULL";
if ($rev_yesno  === 'yes') $where[] = "ra.submitted_date IS NOT NULL";
if ($rev_yesno  === 'no')  $where[] = "ra.submitted_date IS NULL";
if ($umi !== '')         { $where[] = "s.tracking_code LIKE ?";            $params[] = "%$umi%"; }
if ($journal_id !== '')  { $where[] = "s.journal_id = ?";                  $params[] = $journal_id; }
if ($assigned_from !='') { $where[] = "DATE(ra.request_sent_date) >= ?";  $params[] = $assigned_from; }
if ($assigned_to   !='') { $where[] = "DATE(ra.request_sent_date) <= ?";  $params[] = $assigned_to; }
if ($response_from !='') { $where[] = "DATE(ra.response_due_date) >= ?";  $params[] = $response_from; }
if ($response_to   !='') { $where[] = "DATE(ra.response_due_date) <= ?";  $params[] = $response_to; }
if ($review_from   !='') { $where[] = "DATE(ra.review_due_date) >= ?";    $params[] = $review_from; }
if ($review_to     !='') { $where[] = "DATE(ra.review_due_date) <= ?";    $params[] = $review_to; }

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

/* DB debug counts */
$dbg = [];
try {
    $dbg['ra']        = $pdo->query("SELECT COUNT(*) FROM review_assignments")->fetchColumn();
    $dbg['reviewers'] = $pdo->query("SELECT COUNT(*) FROM reviewers")->fetchColumn();
    $dbg['subs']      = $pdo->query("SELECT COUNT(*) FROM submissions")->fetchColumn();
    $dbg['mi']        = $pdo->query("SELECT COUNT(*) FROM manuscript_info")->fetchColumn();
    $dbg['join']      = $pdo->query("
        SELECT COUNT(*) FROM review_assignments ra
        JOIN submissions s ON s.submission_id = ra.submission_id
        JOIN reviewers r   ON r.id = ra.reviewer_id
        JOIN users u       ON u.user_id = r.user_id")->fetchColumn();
    $ts = $pdo->prepare("SELECT COUNT(*) FROM review_assignments ra
        JOIN submissions s ON s.submission_id = ra.submission_id
        WHERE DATE(s.submitted_at) BETWEEN ? AND ?");
    $ts->execute([$sub_from, $sub_to]);
    $dbg['date_range'] = $ts->fetchColumn();
} catch (Exception $e) {
    $dbg['error'] = $e->getMessage();
}

/* ── MAIN QUERY ── */
$sql = "
SELECT
    ra.id                       AS assignment_id,
    ra.submission_id,
    ra.access_key,
    ra.request_sent_date,
    ra.response_due_date,
    ra.review_due_date,
    ra.accepted_date,
    ra.submitted_date,
    ra.assignment_status,
    s.tracking_code,
    DATE(s.submitted_at)               AS sub_date,
    s.submission_status,
    COALESCE(mi.article_title,'(No Title)') AS title,
    j.journal_id,
    COALESCE(j.name,'CIJSS')         AS journal_name,
    u.user_id,
    u.first_name,
    u.last_name,
    u.email,
    COALESCE(u.country,'')             AS country,
    TRIM(CONCAT(
        COALESCE(u.phone_country_code,''),
        COALESCE(u.phone_number,'')
    ))                                 AS phone
FROM review_assignments ra
INNER JOIN submissions s         ON s.submission_id  = ra.submission_id
LEFT  JOIN manuscript_info mi    ON mi.submission_id = s.submission_id
LEFT  JOIN journals j            ON j.journal_id     = s.journal_id
INNER JOIN reviewers r           ON r.id             = ra.reviewer_id
INNER JOIN users u               ON u.user_id        = r.user_id
WHERE $whereSQL
ORDER BY
    CASE
        WHEN ra.review_due_date IS NOT NULL AND ra.review_due_date < CURDATE() AND ra.submitted_date IS NULL THEN 1
        WHEN ra.review_due_date = CURDATE() THEN 2
        ELSE 3
    END,
    ra.review_due_date ASC
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

/* stats */
function yesNo($v){ return $v ? 'Yes' : 'No'; }
$totalRows = count($rows);
$responseRows = $reviewRows = 0;
$submissions = [];
foreach ($rows as $r) {
    if (!empty($r['accepted_date']))  $responseRows++;
    if (!empty($r['submitted_date'])) $reviewRows++;
    $k = $r['tracking_code'] ?: $r['submission_id'];
    if (!isset($submissions[$k])) $submissions[$k] = ['has_response'=>false,'has_review'=>false,'reviewers'=>0];
    $submissions[$k]['reviewers']++;
    if (!empty($r['accepted_date']))  $submissions[$k]['has_response'] = true;
    if (!empty($r['submitted_date'])) $submissions[$k]['has_review']   = true;
}
$uniqueSubs   = count($submissions);
$responsePct  = $totalRows ? round(($responseRows/$totalRows)*100,1) : 0;
$reviewPct    = $totalRows ? round(($reviewRows/$totalRows)*100,1) : 0;
$subsWithResp=$subsWithRev=$normalSubs=$multiSubs=0;
foreach ($submissions as $s) {
    if ($s['has_response']) $subsWithResp++;
    if ($s['has_review'])   $subsWithRev++;
    if ($s['reviewers']>=2) $multiSubs++; else $normalSubs++;
}
$subsRespPct = $uniqueSubs ? round(($subsWithResp/$uniqueSubs)*100,1) : 0;
$subsRevPct  = $uniqueSubs ? round(($subsWithRev/$uniqueSubs)*100,1)  : 0;

/* ── LIVE SHEET ── */
$live_from = $_GET['live_sub_from'] ?? date('Y-m-d', strtotime('-30 days'));
$live_to   = $_GET['live_sub_to']   ?? $today;

$liveRows = $pdo->prepare("
SELECT ra.id AS assignment_id, ra.submission_id, ra.access_key,
    ra.response_due_date, ra.review_due_date, ra.accepted_date, ra.submitted_date,
    s.tracking_code,
    COALESCE(mi.article_title,'(No Title)') AS title,
    COALESCE(j.name,'CIJSS') AS journal_name,
    u.first_name, u.last_name, u.email,
    TRIM(CONCAT(COALESCE(u.phone_country_code,''),COALESCE(u.phone_number,''))) AS phone
FROM review_assignments ra
INNER JOIN submissions s      ON s.submission_id  = ra.submission_id
LEFT  JOIN manuscript_info mi ON mi.submission_id = s.submission_id
LEFT  JOIN journals j         ON j.journal_id     = s.journal_id
INNER JOIN reviewers r        ON r.id             = ra.reviewer_id
INNER JOIN users u            ON u.user_id        = r.user_id
WHERE DATE(s.submitted_at) BETWEEN ? AND ?
ORDER BY s.tracking_code ASC
");
$liveRows->execute([$live_from, $live_to]);
$liveRows = $liveRows->fetchAll(PDO::FETCH_ASSOC);

$grouped = [];
foreach ($liveRows as $r) {
    $umi = $r['tracking_code'] ?: $r['submission_id'];
    if (!isset($grouped[$umi])) $grouped[$umi] = ['rows'=>[],'has_response'=>false,'has_review'=>false];
    if (!empty($r['accepted_date']))  $grouped[$umi]['has_response'] = true;
    if (!empty($r['submitted_date'])) $grouped[$umi]['has_review']   = true;
    $grouped[$umi]['rows'][] = $r;
}
$sections = ['response_today'=>[],'review_today'=>[],'response_passed'=>[],'review_passed'=>[],'decline'=>[]];
foreach ($grouped as $umi => $data) {
    if ($data['has_review']) continue;
    foreach ($data['rows'] as $r) {
        if (!$data['has_response']) {
            if (!empty($r['response_due_date']) && $r['response_due_date'] === $today)
                $sections['response_today'][$umi][] = $r;
            if (!empty($r['response_due_date']) && $r['response_due_date'] < $today)
                $sections['response_passed'][$umi][] = $r;
            if (empty($r['accepted_date']) && !empty($r['response_due_date']) && $r['response_due_date'] < $today)
                $sections['decline'][$umi][] = $r;
        }
        if ($data['has_response'] && !empty($r['accepted_date'])) {
            if (!empty($r['review_due_date']) && $r['review_due_date'] === $today)
                $sections['review_today'][$umi][] = $r;
            if (!empty($r['review_due_date']) && $r['review_due_date'] < $today)
                $sections['review_passed'][$umi][] = $r;
        }
    }
}
$liveSummary = [];
foreach ($sections as $sec => $data) {
    foreach ($data as $umi => $sRows) {
        $jn = $sRows[0]['journal_name'] ?? 'CIJSS';
        $liveSummary[$jn][$sec] = ($liveSummary[$jn][$sec] ?? 0) + 1;
    }
}

/* ── MATRIX ── */
$matrix_from = $_GET['matrix_from'] ?? date('Y-m-d', strtotime('-30 days'));
$matrix_to   = $_GET['matrix_to']   ?? $today;
$mq = $pdo->prepare("
SELECT s.submission_id, s.tracking_code,
    COALESCE(mi.article_title,'(No Title)') AS title,
    DATE(s.submitted_at) AS sub_date,
    s.submission_status AS status,
    COALESCE(j.name,'CIJSS') AS journal_name,
    MAX(ra.accepted_date)  AS any_response,
    MAX(ra.submitted_date) AS any_review
FROM submissions s
LEFT JOIN manuscript_info mi    ON mi.submission_id = s.submission_id
LEFT JOIN review_assignments ra ON ra.submission_id = s.submission_id
LEFT JOIN journals j            ON j.journal_id     = s.journal_id
WHERE DATE(s.submitted_at) BETWEEN ? AND ?
  AND s.submission_status NOT IN ('accepted','rejected','published')
GROUP BY s.submission_id
");
$mq->execute([$matrix_from, $matrix_to]);
$matrixRows = $mq->fetchAll(PDO::FETCH_ASSOC);

$matrix = []; $matrixJournals = [];
foreach ($matrixRows as $r) {
    $d=$r['sub_date']; $jn=$r['journal_name'];
    $matrixJournals[$jn] = true;
    if (!isset($matrix[$d][$jn])) $matrix[$d][$jn]=['not_received'=>[],'received_no_decision'=>[]];
    if (!$r['any_response'])   $matrix[$d][$jn]['not_received'][] = $r;
    elseif ($r['any_review'])  $matrix[$d][$jn]['received_no_decision'][] = $r;
}
$matrixJournalList = array_keys($matrixJournals);
sort($matrixJournalList);

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reviewer Due Dates</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></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}
body.dark{background:#0F172A;color:#E2E8F0}
.sidebar{width:250px;background:#1E293B;color:white;transition:all .3s;height:100%;position:fixed;top:0;left:0;z-index:10;overflow-y:auto}
.sidebar.collapsed{width:70px}
.sidebar.collapsed .sidebar-title,.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 12px;cursor:pointer;transition:background .2s;display:flex;align-items:center}
.nav-item:hover{background:#334155}
.nav-item.active{background:#334155;border-left:3px solid #3B82F6}
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}
body.dark .bg-white{background:#1E293B}
body.dark .bg-slate-100,.dark .bg-gray-50,.dark .bg-gray-100{background:#0F172A}
body.dark .border-gray-200{border-color:#334155}
body.dark .text-gray-800{color:#F1F5F9}
body.dark .text-gray-700{color:#CBD5E1}
body.dark .text-gray-600{color:#94A3B8}
body.dark .text-gray-500{color:#64748B}
body.dark select,body.dark input,body.dark textarea{background:#334155;border-color:#475569;color:#E2E8F0}
body.dark .data-table th{background:#0F172A;border-color:#334155;color:#64748B}
body.dark .data-table td{border-color:#1E293B}
body.dark .data-table tr:hover td{background:#1E293B}
body.dark .stat-card{background:#1E293B;border-color:#334155}
body.dark .tab-bar{background:#1E293B;border-color:#334155}
body.dark .tab-btn{color:#94A3B8}
body.dark .tab-btn:hover{background:#334155;color:#E2E8F0}
body.dark .tab-btn.tab-active{color:#6366F1;border-color:#6366F1}
body.dark .filter-card{background:#1E293B;border-color:#334155}
.tab-bar{background:white;border-bottom:1px solid #E5E7EB}
.tab-btn{padding:12px 20px;font-size:13.5px;font-weight:500;color:#6B7280;border-bottom:3px solid transparent;cursor:pointer;transition:all .15s;white-space:nowrap;background:none;border-top:0;border-left:0;border-right:0}
.tab-btn:hover{background:#F9FAFB;color:#374151}
.tab-btn.tab-active{color:#4F46E5;border-bottom-color:#4F46E5;font-weight:700}
.tab-pane{display:none}.tab-pane.active{display:block}
.inp{width:100%;border:1px solid #D1D5DB;border-radius:8px;padding:7px 11px;font-size:13px;color:#374151;outline:none;background:white;transition:border-color .15s}
.inp:focus{border-color:#6366F1;box-shadow:0 0 0 2px rgba(99,102,241,.1)}
body.dark .inp{background:#334155;border-color:#475569;color:#E2E8F0}
.stat-card{background:white;border-radius:12px;border:1px solid #E2E8F0;padding:18px 20px}
.filter-card{background:white;border:1px solid #E5E7EB;border-radius:12px;padding:16px}
.data-table{width:100%;border-collapse:collapse;font-size:13px}
.data-table th{background:#F9FAFB;padding:9px 12px;text-align:left;font-size:11px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:.4px;border-bottom:1px solid #E5E7EB;white-space:nowrap;position:sticky;top:0;z-index:1}
.data-table td{padding:9px 12px;border-bottom:1px solid #F3F4F6;vertical-align:middle}
.data-table tr:hover td{background:#F9FAFB}
.row-overdue td{background:#FEF2F2!important}.row-today td{background:#ECFDF5!important}
body.dark .row-overdue td{background:#2D1515!important}body.dark .row-today td{background:#0D2416!important}
.act-btn{padding:4px 7px;border-radius:6px;font-size:12px;cursor:pointer;transition:all .15s;border:none;background:transparent}
.act-btn:hover{opacity:.8;transform:scale(1.1)}
.dbg{background:#f0f9ff;border:1px solid #bae6fd;border-radius:8px;padding:10px 14px;font-size:12px;font-family:monospace;line-height:1.8}
body.dark .dbg{background:#0c1a2e;border-color:#1e3a5f;color:#7dd3fc}
</style>
</head>
<body class="bg-slate-100">
<button onclick="toggleMobile()" class="fixed top-3 left-3 z-20 bg-slate-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-400 hover:text-gray-600 hidden md:block">
        <i class="fas fa-bars text-lg"></i>
      </button>
      <i class="fas fa-user-clock text-indigo-600 text-xl"></i>
      <span class="font-bold text-gray-800 text-lg">Reviewer Due Dates</span>
    </div>
    <div class="flex items-center gap-3">
      <span class="text-xs text-gray-400 bg-gray-100 px-3 py-1 rounded-full">
        <?= $totalRows ?> rows · <?= $uniqueSubs ?> submissions
      </span>
      <button id="darkToggle" class="text-gray-400 hover:text-gray-600 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
        <i class="fas fa-moon text-sm"></i>
      </button>
    </div>
  </div>

  <!-- Tab Bar (3 tabs — Reviewer Load removed) -->
  <div class="tab-bar flex overflow-x-auto sticky top-[65px] z-10 shadow-sm mt-3">
    <button class="tab-btn tab-active" data-tab="summary">📊 Smart Summary</button>
    <button class="tab-btn" data-tab="live">📑 Live R1 R2 Sheet</button>
    <button class="tab-btn" data-tab="matrix">📊 Submission Matrix</button>
  </div>

  <!-- ══════════════════════════
       TAB 1 — SMART SUMMARY
  ══════════════════════════ -->
  <div id="tab-summary" class="tab-pane active">
  <div class="p-5 space-y-5">

    <div class="filter-card">
      <form method="GET">
        <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-3">
          <div><label class="block text-xs text-gray-500 mb-1">Sub From</label><input type="date" name="sub_from" class="inp" value="<?= esc($sub_from) ?>"></div>
          <div><label class="block text-xs text-gray-500 mb-1">Sub To</label><input type="date" name="sub_to" class="inp" value="<?= esc($sub_to) ?>"></div>
          <div><label class="block text-xs text-gray-500 mb-1">Assigned From</label><input type="date" name="assigned_from" class="inp" value="<?= esc($assigned_from) ?>"></div>
          <div><label class="block text-xs text-gray-500 mb-1">Assigned To</label><input type="date" name="assigned_to" class="inp" value="<?= esc($assigned_to) ?>"></div>
          <div><label class="block text-xs text-gray-500 mb-1">Resp Due From</label><input type="date" name="response_from" class="inp" value="<?= esc($response_from) ?>"></div>
          <div><label class="block text-xs text-gray-500 mb-1">Resp Due To</label><input type="date" name="response_to" class="inp" value="<?= esc($response_to) ?>"></div>
          <div><label class="block text-xs text-gray-500 mb-1">Review Due From</label><input type="date" name="review_from" class="inp" value="<?= esc($review_from) ?>"></div>
          <div><label class="block text-xs text-gray-500 mb-1">Review Due To</label><input type="date" name="review_to" class="inp" value="<?= esc($review_to) ?>"></div>
        </div>
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-3">
          <div><label class="block text-xs text-gray-500 mb-1">Journal</label>
            <select name="journal_id" class="inp">
              <option value="">All Journals</option>
              <?php foreach ($journals as $j): ?>
              <option value="<?= esc($j['journal_id']) ?>" <?= $journal_id==$j['journal_id']?'selected':'' ?>><?= esc($j['name']) ?></option>
              <?php endforeach; ?>
            </select></div>
          <div><label class="block text-xs text-gray-500 mb-1">Response?</label>
            <select name="resp_yesno" class="inp">
              <option value="">Any</option>
              <option value="yes" <?= $resp_yesno==='yes'?'selected':'' ?>>Yes</option>
              <option value="no"  <?= $resp_yesno==='no' ?'selected':'' ?>>No</option>
            </select></div>
          <div><label class="block text-xs text-gray-500 mb-1">Review Done?</label>
            <select name="rev_yesno" class="inp">
              <option value="">Any</option>
              <option value="yes" <?= $rev_yesno==='yes'?'selected':'' ?>>Yes</option>
              <option value="no"  <?= $rev_yesno==='no' ?'selected':'' ?>>No</option>
            </select></div>
          <div><label class="block text-xs text-gray-500 mb-1">UMI / Tracking</label>
            <input type="text" name="umi" class="inp" placeholder="e.g. CG-001" value="<?= esc($umi) ?>"></div>
        </div>
        <div class="flex gap-3 mt-4">
          <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2 rounded-lg text-sm font-bold flex items-center gap-2">
            <i class="fas fa-filter text-xs"></i> Apply Filters
          </button>
          <a href="reviewer-due-dates.php" class="border border-gray-300 text-gray-600 hover:bg-gray-50 px-5 py-2 rounded-lg text-sm font-bold flex items-center gap-2">
            <i class="fas fa-times text-xs"></i> Clear
          </a>
        </div>
      </form>
    </div>

    <!-- Stat cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
      <div class="stat-card">
        <div class="flex justify-between items-center mb-3">
          <h3 class="font-semibold text-gray-700 text-sm">RAW (Row-based) — reviewer rows</h3>
          <span class="text-3xl font-bold text-gray-800"><?= $totalRows ?></span>
        </div>
        <p class="text-xs text-gray-400 mb-4">Each reviewer assignment counted individually.</p>
        <div class="grid grid-cols-2 gap-3">
          <div class="bg-green-50 rounded-xl p-4 border border-green-100">
            <div class="text-xs text-gray-500 mb-2 font-medium">Rows with Response Received</div>
            <div class="text-3xl font-bold text-green-700"><?= $responseRows ?></div>
            <div class="text-sm text-green-500 mt-1"><?= $responsePct ?>% of assignments</div>
            <div class="w-full bg-green-100 rounded-full h-1.5 mt-3">
              <div class="bg-green-500 h-1.5 rounded-full" style="width:<?= $responsePct ?>%"></div>
            </div>
          </div>
          <div class="bg-purple-50 rounded-xl p-4 border border-purple-100">
            <div class="text-xs text-gray-500 mb-2 font-medium">Rows with Review Completed</div>
            <div class="text-3xl font-bold text-purple-700"><?= $reviewRows ?></div>
            <div class="text-sm text-purple-500 mt-1"><?= $reviewPct ?>% of assignments</div>
            <div class="w-full bg-purple-100 rounded-full h-1.5 mt-3">
              <div class="bg-purple-500 h-1.5 rounded-full" style="width:<?= $reviewPct ?>%"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="stat-card">
        <div class="flex justify-between items-center mb-3">
          <h3 class="font-semibold text-gray-700 text-sm">CONSOLIDATED (Submission-based)</h3>
          <span class="text-3xl font-bold text-gray-800"><?= $uniqueSubs ?></span>
        </div>
        <p class="text-xs text-gray-400 mb-4">If any reviewer responded/reviewed → submission = YES.</p>
        <div class="space-y-2 text-sm">
          <div class="flex justify-between py-1.5 border-b border-gray-100">
            <span class="text-gray-500">Normal (1 reviewer)</span><b class="text-gray-800"><?= $normalSubs ?></b>
          </div>
          <div class="flex justify-between py-1.5 border-b border-gray-100">
            <span class="text-gray-500">R1 &amp; R2 (2+ reviewers)</span><b class="text-gray-800"><?= $multiSubs ?></b>
          </div>
          <div class="flex justify-between py-1.5 border-b border-gray-100">
            <span class="text-gray-500">With Response</span>
            <b class="text-green-700"><?= $subsWithResp ?> <span class="font-normal text-green-500">(<?= $subsRespPct ?>%)</span></b>
          </div>
          <div class="flex justify-between py-1.5">
            <span class="text-gray-500">Review Completed</span>
            <b class="text-purple-700"><?= $subsWithRev ?> <span class="font-normal text-purple-500">(<?= $subsRevPct ?>%)</span></b>
          </div>
        </div>
      </div>
    </div>

    <!-- Table -->
    <div class="bg-white border border-gray-200 rounded-xl overflow-hidden">
      <div class="px-5 py-3 border-b border-gray-100 flex items-center justify-between flex-wrap gap-2">
        <div class="flex items-center gap-3">
          <span class="text-sm font-bold text-gray-700">Assignment Records</span>
          <span class="text-xs bg-indigo-50 text-indigo-600 font-bold px-2 py-0.5 rounded-full"><?= $totalRows ?></span>
          <span class="text-xs text-red-500 bg-red-50 px-2 py-0.5 rounded">🔴 Overdue</span>
          <span class="text-xs text-green-600 bg-green-50 px-2 py-0.5 rounded">🟢 Due Today</span>
        </div>
        <button onclick="exportSummaryTable()" class="text-xs bg-emerald-50 text-emerald-700 border border-emerald-200 px-3 py-1.5 rounded-lg font-semibold hover:bg-emerald-100 transition flex items-center gap-1.5">
          <i class="fas fa-file-excel text-xs"></i> Export XLSX
        </button>
      </div>
      <div style="overflow-x:auto;max-height:560px">
        <table class="data-table" id="summaryTable">
          <thead>
            <tr>
              <th>UMI</th>
              <th>Title</th>
              <th>Response<br><span class="font-normal normal-case text-indigo-300 text-[10px]">accepted_date</span></th>
              <th>Review Done<br><span class="font-normal normal-case text-indigo-300 text-[10px]">submitted_date</span></th>
              <th>Journal</th>
              <th>Reviewer</th>
              <th>Email</th>
              <th>Country</th>
              <th>Phone</th>
              <th>Resp Due</th>
              <th>Review Due</th>
              <th>Assigned</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($rows)): ?>
          <tr><td colspan="14" class="text-center py-16 text-gray-400">
            <i class="fas fa-user-clock text-5xl mb-3 block text-gray-200"></i>
            No review assignments found for this date range.<br>
            <span class="text-xs">Try widening the date range. Check the debug bar above.</span>
          </td></tr>
          <?php endif; ?>
          <?php foreach ($rows as $r):
            $reviewer   = trim($r['first_name'].' '.$r['last_name']);
            $phone      = $r['phone'] ?? '';
            $fullTitle  = $r['title'] ?? '';
            $shortTitle = mb_strlen($fullTitle)>55 ? mb_substr($fullTitle,0,55).'…' : $fullTitle;
            $isOverdue  = !empty($r['review_due_date']) && $r['review_due_date'] < $today && empty($r['submitted_date']);
            $isDueToday = !empty($r['review_due_date']) && $r['review_due_date'] === $today;
            $rowCls     = $isOverdue ? 'row-overdue' : ($isDueToday ? 'row-today' : '');
            $directLink = !empty($r['access_key'])
                ? 'https://communeglobal.com/reviewer/access.php?access_key='.urlencode($r['access_key']).'&submission_id='.urlencode($r['submission_id'])
                : '#';
            $hasResp = !empty($r['accepted_date']);
            $hasRev  = !empty($r['submitted_date']);
          ?>
          <tr class="border-b <?= $rowCls ?>">
            <td>
              <a href="submission_view.php?id=<?= (int)$r['submission_id'] ?>"
                 class="text-indigo-700 font-bold text-xs hover:underline whitespace-nowrap">
                <?= esc($r['tracking_code'] ?: '#'.$r['submission_id']) ?>
              </a>
            </td>
            <td class="text-xs text-gray-700 max-w-[200px]" title="<?= esc($fullTitle) ?>"><?= esc($shortTitle) ?></td>
            <td>
              <?php if ($hasResp): ?>
                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-700">
                  <i class="fas fa-check text-[9px]"></i> Yes
                </span>
                <div class="text-[10px] text-gray-400 mt-0.5"><?= esc($r['accepted_date']) ?></div>
              <?php else: ?>
                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-red-100 text-red-600">
                  <i class="fas fa-times text-[9px]"></i> No
                </span>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($hasRev): ?>
                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-700">
                  <i class="fas fa-check text-[9px]"></i> Yes
                </span>
                <div class="text-[10px] text-gray-400 mt-0.5"><?= esc($r['submitted_date']) ?></div>
              <?php else: ?>
                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-red-100 text-red-600">
                  <i class="fas fa-times text-[9px]"></i> No
                </span>
              <?php endif; ?>
            </td>
            <td class="text-xs text-gray-600 max-w-[120px] truncate" title="<?= esc($r['journal_name']) ?>"><?= esc($r['journal_name']?:'—') ?></td>
            <td class="text-xs font-semibold text-gray-800 whitespace-nowrap"><?= esc($reviewer?:'—') ?></td>
            <td class="text-xs text-indigo-600 whitespace-nowrap"><?= esc($r['email']??'—') ?></td>
            <td class="text-xs text-gray-500"><?= esc($r['country']?:'—') ?></td>
            <td class="text-xs text-gray-500 whitespace-nowrap"><?= esc($phone?:'—') ?></td>
            <td class="text-xs whitespace-nowrap <?= (!$hasResp && !empty($r['response_due_date']) && $r['response_due_date']<=$today) ? 'text-red-600 font-bold' : 'text-gray-500' ?>">
              <?= esc($r['response_due_date']?:'—') ?>
            </td>
            <td class="text-xs whitespace-nowrap <?= $isOverdue?'text-red-600 font-bold':($isDueToday?'text-emerald-600 font-bold':'text-gray-500') ?>">
              <?= esc($r['review_due_date']?:'—') ?>
              <?php if ($isOverdue): ?><span class="ml-1 text-[9px] bg-red-100 text-red-600 px-1 rounded-full">OVERDUE</span><?php endif; ?>
              <?php if ($isDueToday): ?><span class="ml-1 text-[9px] bg-green-100 text-green-600 px-1 rounded-full">TODAY</span><?php endif; ?>
            </td>
            <td class="text-xs text-gray-400 whitespace-nowrap"><?= esc($r['request_sent_date']?:'—') ?></td>
            <td>
              <span class="text-xs px-2 py-0.5 rounded-full font-semibold
                <?= $r['assignment_status']==='accepted' ? 'bg-green-100 text-green-700' :
                   ($r['assignment_status']==='declined' ? 'bg-red-100 text-red-600' :
                   ($r['assignment_status']==='completed'? 'bg-blue-100 text-blue-700':'bg-gray-100 text-gray-600')) ?>">
                <?= esc(ucfirst($r['assignment_status']??'pending')) ?>
              </span>
            </td>
            <td>
              <div class="flex items-center gap-1">
                <button onclick='openEditModal(<?= htmlspecialchars(json_encode($r), ENT_QUOTES) ?>)' class="act-btn text-indigo-600" title="Edit"><i class="fas fa-edit"></i></button>
                <button onclick='openWA("send_template","<?= esc($phone) ?>","<?= esc(addslashes($fullTitle)) ?>","<?= esc($reviewer) ?>","<?= esc($directLink) ?>")' class="act-btn text-green-600" title="WA Invite"><i class="fab fa-whatsapp"></i></button>
                <button onclick='openWA("send_reminder","<?= esc($phone) ?>","<?= esc(addslashes($fullTitle)) ?>","<?= esc($reviewer) ?>","<?= esc($directLink) ?>")' class="act-btn text-amber-500" title="WA Reminder"><i class="fas fa-bell"></i></button>
                <button onclick='openWA("today_due","<?= esc($phone) ?>","<?= esc(addslashes($fullTitle)) ?>","<?= esc($reviewer) ?>","<?= esc($directLink) ?>")' class="act-btn text-blue-600" title="WA Today Due"><i class="fas fa-clock"></i></button>
                <button onclick='openEmail("response_due","<?= esc($r['email']) ?>","<?= esc($reviewer) ?>","<?= esc(addslashes($fullTitle)) ?>","<?= esc($r['response_due_date']) ?>","<?= esc($directLink) ?>")' class="act-btn text-red-500" title="Email Resp Due"><i class="fas fa-envelope"></i></button>
                <button onclick='openEmail("review_due","<?= esc($r['email']) ?>","<?= esc($reviewer) ?>","<?= esc(addslashes($fullTitle)) ?>","<?= esc($r['review_due_date']) ?>","<?= esc($directLink) ?>")' class="act-btn text-purple-600" title="Email Rev Due"><i class="fas fa-paper-plane"></i></button>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

  </div>
  </div>

  <!-- ══════════════════════════
       TAB 2 — LIVE R1 R2
  ══════════════════════════ -->
  <div id="tab-live" class="tab-pane">
  <div class="p-5 space-y-5">
    <div class="filter-card">
      <form method="GET" class="flex flex-wrap gap-3 items-end">
        <div><label class="block text-xs text-gray-500 mb-1">Submission From</label>
          <input type="date" name="live_sub_from" class="inp w-auto" value="<?= esc($live_from) ?>"></div>
        <div><label class="block text-xs text-gray-500 mb-1">To</label>
          <input type="date" name="live_sub_to" class="inp w-auto" value="<?= esc($live_to) ?>"></div>
        <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded-lg text-sm font-bold">Show</button>
        <button type="button" onclick="exportLiveSheet()" class="bg-emerald-600 text-white px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2">
          <i class="fas fa-file-excel text-xs"></i> Export Excel
        </button>
      </form>
    </div>
    <div>
      <h2 class="text-sm font-bold text-gray-700 mb-3">📊 Section Summary (Journal-wise)</h2>
      <div class="bg-white border border-gray-200 rounded-xl overflow-x-auto">
        <table class="data-table">
          <thead>
            <tr>
              <th>Journal</th>
              <th class="text-center">Response Today</th>
              <th class="text-center">Review Today</th>
              <th class="text-center">Response Passed</th>
              <th class="text-center">Review Passed</th>
              <th class="text-center">Decline</th>
              <th class="text-center font-bold">Total</th>
            </tr>
          </thead>
          <tbody>
          <?php $grand=['response_today'=>0,'review_today'=>0,'response_passed'=>0,'review_passed'=>0,'decline'=>0]; ?>
          <?php if (empty($liveSummary)): ?>
          <tr><td colspan="7" class="text-center py-8 text-gray-400 text-xs">No data for selected date range.</td></tr>
          <?php else: foreach ($liveSummary as $jn => $cnt):
            $rt = array_sum($cnt);
            foreach ($cnt as $k=>$v) $grand[$k]=($grand[$k]??0)+$v;
          ?>
          <tr class="border-b hover:bg-gray-50">
            <td class="font-semibold text-sm"><?= esc($jn) ?></td>
            <td class="text-center"><?= $cnt['response_today']??0 ?></td>
            <td class="text-center"><?= $cnt['review_today']??0 ?></td>
            <td class="text-center"><?= $cnt['response_passed']??0 ?></td>
            <td class="text-center"><?= $cnt['review_passed']??0 ?></td>
            <td class="text-center"><?= $cnt['decline']??0 ?></td>
            <td class="text-center font-bold"><?= $rt ?></td>
          </tr>
          <?php endforeach; endif; ?>
          <tr class="bg-indigo-50 font-bold text-sm">
            <td class="py-2 px-3 text-indigo-700">TOTAL</td>
            <td class="text-center"><?= $grand['response_today'] ?></td>
            <td class="text-center"><?= $grand['review_today'] ?></td>
            <td class="text-center"><?= $grand['response_passed'] ?></td>
            <td class="text-center"><?= $grand['review_passed'] ?></td>
            <td class="text-center"><?= $grand['decline'] ?></td>
            <td class="text-center"><?= array_sum($grand) ?></td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    function renderSection($ttl, $data) {
        if (empty($data)) return;
        $isResp = stripos($ttl,'Response')!==false;
        $isRev  = stripos($ttl,'Review')!==false;
        echo "<div><h2 class='text-sm font-bold text-gray-700 mb-3'>".htmlspecialchars($ttl)."</h2>";
        echo "<div class='bg-white border border-gray-200 rounded-xl overflow-x-auto mb-2'>";
        echo "<table class='data-table live-table'><thead><tr>
            <th>UMI</th><th>Title</th><th>Reviewer</th><th>Journal</th><th>Email</th><th>Phone</th>
            <th class='text-center'>Actions</th></tr></thead><tbody>";
        foreach ($data as $umi => $rows): foreach ($rows as $r):
            $rev  = trim($r['first_name'].' '.$r['last_name']);
            $ph   = $r['phone']??'';
            $tit  = mb_substr($r['title']??'',0,50);
            $dl   = !empty($r['access_key'])
                ? 'https://communeglobal.com/reviewer/access.php?access_key='.urlencode($r['access_key']).'&submission_id='.urlencode($r['submission_id'])
                : '#';
            echo "<tr class='border-b hover:bg-gray-50'>
                <td class='font-bold text-indigo-700 text-xs'>".htmlspecialchars($umi)."</td>
                <td class='text-xs text-gray-700 max-w-[160px] truncate' title='".htmlspecialchars($r['title']??'')."'>".htmlspecialchars($tit)."</td>
                <td class='text-xs font-semibold'>".htmlspecialchars($rev)."</td>
                <td class='text-xs text-gray-500'>".htmlspecialchars($r['journal_name']??'—')."</td>
                <td class='text-xs text-indigo-600'>".htmlspecialchars($r['email']??'')."</td>
                <td class='text-xs text-gray-500'>".htmlspecialchars($ph?:'—')."</td>
                <td class='text-center'><div class='flex justify-center gap-1'>";
            if ($isResp) {
                echo "<button onclick='openWA(\"send_reminder\",\"".htmlspecialchars($ph)."\",\"".htmlspecialchars(addslashes($r['title']??''))."\",\"".htmlspecialchars($rev)."\",\"".htmlspecialchars($dl)."\")' class='act-btn text-amber-500'><i class='fas fa-bell'></i></button>";
                echo "<button onclick='openEmail(\"response_due\",\"".htmlspecialchars($r['email']??'')."\",\"".htmlspecialchars($rev)."\",\"".htmlspecialchars(addslashes($r['title']??''))."\",\"".htmlspecialchars($r['response_due_date']??'')."\",\"".htmlspecialchars($dl)."\")' class='act-btn text-red-500'><i class='fas fa-envelope'></i></button>";
            }
            if ($isRev) {
                echo "<button onclick='openWA(\"today_due\",\"".htmlspecialchars($ph)."\",\"".htmlspecialchars(addslashes($r['title']??''))."\",\"".htmlspecialchars($rev)."\",\"".htmlspecialchars($dl)."\")' class='act-btn text-blue-600'><i class='fas fa-clock'></i></button>";
                echo "<button onclick='openEmail(\"review_due\",\"".htmlspecialchars($r['email']??'')."\",\"".htmlspecialchars($rev)."\",\"".htmlspecialchars(addslashes($r['title']??''))."\",\"".htmlspecialchars($r['review_due_date']??'')."\",\"".htmlspecialchars($dl)."\")' class='act-btn text-purple-600'><i class='fas fa-paper-plane'></i></button>";
            }
            echo "</div></td></tr>";
        endforeach; endforeach;
        echo "</tbody></table></div></div>";
    }
    renderSection('📅 Response Due Date Today',  $sections['response_today']);
    renderSection('📅 Review Due Date Today',    $sections['review_today']);
    renderSection('⚠️ Response Due Date Passed', $sections['response_passed']);
    renderSection('⚠️ Review Due Date Passed',   $sections['review_passed']);
    renderSection('❌ Decline',                   $sections['decline']);
    ?>
  </div>
  </div>

  <!-- ══════════════════════════
       TAB 3 — MATRIX
  ══════════════════════════ -->
  <div id="tab-matrix" class="tab-pane">
  <div class="p-5 space-y-5">
    <div class="filter-card">
      <form method="GET" class="flex flex-wrap gap-3 items-end">
        <div><label class="block text-xs text-gray-500 mb-1">From</label>
          <input type="date" name="matrix_from" class="inp w-auto" value="<?= esc($matrix_from) ?>"></div>
        <div><label class="block text-xs text-gray-500 mb-1">To</label>
          <input type="date" name="matrix_to" class="inp w-auto" value="<?= esc($matrix_to) ?>"></div>
        <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded-lg text-sm font-bold">Show</button>
      </form>
    </div>
    <div class="flex gap-4 text-xs">
      <span class="bg-red-50 text-red-600 px-3 py-1 rounded-full font-semibold">NR = Not Received</span>
      <span class="bg-amber-50 text-amber-600 px-3 py-1 rounded-full font-semibold">RND = Received, No Decision</span>
    </div>
    <div class="bg-white border border-gray-200 rounded-xl overflow-x-auto">
      <table class="data-table">
        <thead>
          <tr>
            <th>Date</th>
            <?php foreach ($matrixJournalList as $j): ?>
            <th class="text-center"><?= esc(mb_substr($j,0,14)) ?><br><span class="font-normal text-gray-400">NR</span></th>
            <th class="text-center"><?= esc(mb_substr($j,0,14)) ?><br><span class="font-normal text-gray-400">RND</span></th>
            <th class="text-center text-gray-600">Tot</th>
            <?php endforeach; ?>
            <th class="text-center font-bold">Grand</th>
          </tr>
        </thead>
        <tbody>
        <?php if (empty($matrix)): ?>
        <tr><td colspan="50" class="text-center py-12 text-gray-400">No data for selected date range.</td></tr>
        <?php endif; ?>
        <?php foreach ($matrix as $date => $journals): $rowGrand=0; ?>
        <tr class="border-b hover:bg-gray-50">
          <td class="font-semibold text-sm whitespace-nowrap"><?= esc($date) ?></td>
          <?php foreach ($matrixJournalList as $j):
            $nr  = count($journals[$j]['not_received']??[]);
            $rnd = count($journals[$j]['received_no_decision']??[]);
            $tot = $nr+$rnd; $rowGrand+=$tot;
          ?>
          <td class="text-center <?= $nr>0?'text-red-600 font-semibold cursor-pointer hover:bg-red-50':'text-gray-300' ?>"
              <?= $nr>0?"onclick='showMatrixDetails(".htmlspecialchars(json_encode($journals[$j]['not_received']??[]),ENT_QUOTES).")'" :'' ?>>
            <?= $nr ?>
          </td>
          <td class="text-center <?= $rnd>0?'text-amber-600 font-semibold cursor-pointer hover:bg-amber-50':'text-gray-300' ?>"
              <?= $rnd>0?"onclick='showMatrixDetails(".htmlspecialchars(json_encode($journals[$j]['received_no_decision']??[]),ENT_QUOTES).")'" :'' ?>>
            <?= $rnd ?>
          </td>
          <td class="text-center font-semibold <?= $tot>0?'text-gray-800':'text-gray-300' ?>"><?= $tot ?></td>
          <?php endforeach; ?>
          <td class="text-center font-bold"><?= $rowGrand ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
  </div>

</div><!-- /content -->

<script>
let sc=false;
function toggleMobile(){ document.getElementById('sidebar')?.classList.toggle('mobile-open'); }
function toggleSidebar(){
    sc=!sc;
    document.getElementById('sidebar')?.classList.toggle('collapsed',sc);
    document.getElementById('content')?.classList.toggle('collapsed-sidebar',sc);
}
document.getElementById('darkToggle').addEventListener('click',function(){
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('dm',document.body.classList.contains('dark')?'1':'0');
});
if(localStorage.getItem('dm')==='1'){
    document.body.classList.add('dark');
    document.getElementById('darkToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
}
document.querySelectorAll('.tab-btn').forEach(btn=>{
    btn.addEventListener('click',()=>{
        document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('tab-active'));
        btn.classList.add('tab-active');
        document.querySelectorAll('.tab-pane').forEach(p=>p.classList.remove('active'));
        document.getElementById('tab-'+btn.dataset.tab).classList.add('active');
    });
});
function openEditModal(row){
    Swal.fire({
        title:'<span class="text-indigo-700">Edit Review Assignment</span>',
        width:800,
        html:`<div class="grid grid-cols-2 gap-4 text-sm text-left">
            <label class="block">UMI<input id="e_umi" class="swal2-input" value="${row.tracking_code||''}"></label>
            <label class="block">Title<input id="e_title" class="swal2-input" value="${(row.title||'').replace(/"/g,'&quot;')}"></label>
            <label class="block">Reviewer Name<input id="e_name" class="swal2-input" value="${(row.first_name||'')+' '+(row.last_name||'')}"></label>
            <label class="block">Email<input id="e_email" class="swal2-input" value="${row.email||''}"></label>
            <label class="block">Country<input id="e_country" class="swal2-input" value="${row.country||''}"></label>
            <label class="block">Phone<input id="e_phone" class="swal2-input" value="${row.phone||''}"></label>
            <label class="block">Response Due<input type="date" id="e_resp" class="swal2-input" value="${row.response_due_date||''}"></label>
            <label class="block">Review Due<input type="date" id="e_rev" class="swal2-input" value="${row.review_due_date||''}"></label>
        </div>`,
        showCancelButton:true,confirmButtonText:'💾 Save',confirmButtonColor:'#4F46E5',showLoaderOnConfirm:true,
        preConfirm:()=>{
            const fd=new FormData();
            fd.append('assignment_id',row.assignment_id);
            fd.append('tracking_code',document.getElementById('e_umi').value);
            fd.append('title',document.getElementById('e_title').value);
            fd.append('reviewer_name',document.getElementById('e_name').value);
            fd.append('email',document.getElementById('e_email').value);
            fd.append('country',document.getElementById('e_country').value);
            fd.append('phone',document.getElementById('e_phone').value);
            fd.append('response_due_date',document.getElementById('e_resp').value);
            fd.append('review_due_date',document.getElementById('e_rev').value);
            return fetch('update-assignment.php',{method:'POST',body:fd}).then(r=>r.json())
                .catch(()=>Swal.showValidationMessage('Save failed'));
        }
    }).then(res=>{
        if(res.value?.success) Swal.fire('Updated!','','success').then(()=>location.reload());
        else if(res.value) Swal.fire('Error',JSON.stringify(res.value),'error');
    });
}
function openWA(action,phone,title,reviewer,directLink){
    const msgs={
        send_template:`Dear Esteemed Reviewer,\n\nYour reviewer account has been created for Communeglobal. Please log in at ${directLink} to access the manuscript "${title}" assigned for review.\n\nPlease confirm your availability within 2 days and submit your review within 5 days.\n\nThank you.`,
        send_reminder:`Reminder:\n\nPlease confirm your availability today to review the manuscript "${title}" submitted to Communeglobal Journals.\n\nLog in at ${directLink}\n\nThank you`,
        today_due:`Dear ${reviewer},\n\nToday is the due date to submit your review for the manuscript "${title}".\n\nSubmission Link: ${directLink}\n\nKindly submit at your earliest.\n\nThanks\nCommuneglobal Editorial Office`
    };
    Swal.fire({
        title:'<span class="text-green-700">📱 Send WhatsApp</span>',width:600,
        html:`<div class="text-left text-sm space-y-3">
            <label class="block"><span class="font-medium text-gray-600">Mobile Number</span>
                <input id="wa_phone" class="swal2-input" value="${phone}"></label>
            <label class="block"><span class="font-medium text-gray-600">Message</span>
                <textarea id="wa_msg" class="swal2-textarea" rows="7">${msgs[action]}</textarea></label>
        </div>`,
        showCancelButton:true,confirmButtonText:'🚀 Send',confirmButtonColor:'#16a34a',
        preConfirm:()=>{
            const fd=new FormData();
            fd.append('action',action);
            fd.append('phone',document.getElementById('wa_phone').value);
            if(action==='send_template'){fd.append('param2',directLink);fd.append('param3',title);}
            if(action==='send_reminder'){fd.append('p1',title);fd.append('p2',directLink);}
            if(action==='today_due'){fd.append('p1',reviewer);fd.append('p2',title);fd.append('p3',directLink);}
            return fetch('https://rsis.international/articles/tools/send-whatsapp-apibackup.php',{method:'POST',body:fd}).then(r=>r.json());
        }
    }).then(res=>{
        if(res.value?.success) Swal.fire('Sent!','','success');
        else Swal.fire('Failed',JSON.stringify(res.value),'error');
    });
}
function openEmail(type,email,reviewer,title,dueDate,directLink){
    const d={
        response_due:{subject:'Request: Please Confirm Availability to Review',
            body:`Dear ${reviewer},\n\nWe request your review of the manuscript "${title}" for Communeglobal Journals. Please confirm availability by ${dueDate}.\n\nAccess: ${directLink}\n\nRegards,\nCommuneglobal Editorial Office`},
        review_due:{subject:'Reminder: Review Due for Submission',
            body:`Dear ${reviewer},\n\nYour review for "${title}" is due on ${dueDate}.\n\nAccess: ${directLink}\n\nRegards,\nCommuneglobal Editorial Office`}
    }[type]||{};
    Swal.fire({
        title:'📧 Send Email',width:680,
        html:`<input id="em_to" class="swal2-input" value="${email}">
              <input id="em_subject" class="swal2-input" value="${d.subject||''}">
              <textarea id="em_body" class="swal2-textarea" rows="9">${d.body||''}</textarea>`,
        showCancelButton:true,confirmButtonText:'📧 Send Email',confirmButtonColor:'#4F46E5',
        preConfirm:()=>{
            const fd=new FormData();
            fd.append('to',document.getElementById('em_to').value);
            fd.append('subject',document.getElementById('em_subject').value);
            fd.append('body',document.getElementById('em_body').value);
            return fetch('/common/mailer/server_mailer.php',{method:'POST',body:fd}).then(r=>r.json());
        }
    }).then(res=>{ if(res.value?.success) Swal.fire('Email Sent!','','success'); });
}
function showMatrixDetails(rows){
    if(!rows?.length){Swal.fire('No Records');return;}
    let html="<div class='text-left text-sm space-y-2'>";
    rows.forEach(r=>{
        html+=`<div class='border-b pb-2 pt-1'>
            <span class='text-indigo-700 font-bold'>${r.tracking_code||'#'+r.submission_id}</span>
            <span class='text-xs text-gray-400 ml-2'>${r.sub_date||''}</span><br>
            <span class='text-xs text-gray-700'>${r.title||'(No Title)'}</span>
        </div>`;
    });
    html+="</div>";
    Swal.fire({title:'Submission Details',width:700,html,confirmButtonColor:'#4F46E5'});
}
function exportSummaryTable(){
    const ws=XLSX.utils.table_to_sheet(document.getElementById('summaryTable'));
    const wb=XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb,ws,'Summary');
    XLSX.writeFile(wb,`reviewer_summary_${new Date().toISOString().slice(0,10)}.xlsx`);
}
function exportLiveSheet(){
    const tables=document.querySelectorAll('#tab-live .live-table');
    const wb=XLSX.utils.book_new();
    tables.forEach((t,i)=>XLSX.utils.book_append_sheet(wb,XLSX.utils.table_to_sheet(t),'Section_'+(i+1)));
    XLSX.writeFile(wb,`live_r1_r2_${new Date().toISOString().slice(0,10)}.xlsx`);
}
</script>
</body>
</html>