<?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) {}

/* ── Filters ── */
$umi             = trim($_GET['umi']             ?? '');
$decision_f      = trim($_GET['decision']        ?? '');
$journal_f       = trim($_GET['journal_id']      ?? '');
$country_f       = trim($_GET['country']         ?? '');
$submission_date = trim($_GET['submission_date'] ?? '');
$due_date_f      = trim($_GET['due_date']        ?? '');
$fee_paid_f      = trim($_GET['fee_paid']        ?? '');
$status_f        = trim($_GET['status']          ?? '');

/* ── Build WHERE ── */
$where  = ["ed_latest.submission_id IS NOT NULL"];
$params = [];

if ($umi !== '') {
    $where[]  = "s.tracking_code LIKE ?";
    $params[] = "%$umi%";
}
if ($decision_f !== '') {
    $where[]  = "ed.decision = ?";
    $params[] = $decision_f;
}
if ($journal_f !== '') {
    $where[]  = "s.journal_id = ?";
    $params[] = (int)$journal_f;
}
if ($country_f !== '') {
    $where[]  = "u.country LIKE ?";
    $params[] = "%$country_f%";
}
if ($submission_date !== '') {
    $where[]  = "DATE(s.submitted_at) = ?";
    $params[] = $submission_date;
}
if ($due_date_f !== '') {
    $where[]  = "ed.due_date = ?";
    $params[] = $due_date_f;
}
if ($status_f !== '') {
    $where[]  = "s.submission_status = ?";
    $params[] = $status_f;
}

$whereSql = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';

/* ── Main query ── */
$rows = [];
$dbError = '';
try {
    $sql = "
        SELECT
            s.submission_id,
            s.tracking_code,
            s.submitted_at,
            s.submission_status,
            s.journal_id,

            j.name           AS journal_name,

            u.user_id,
            u.first_name,
            u.last_name,
            u.email          AS author_email,
            u.country,
            u.phone_number   AS phone,
            u.phone_country_code,

            mi.article_title,

            ed.decision,
            ed.due_date,
            ed.created_at    AS decision_date,
            ed.editor_comments,

            /* Latest editorial decision for pub date */
            sf_pub.publication_date,

            /* Resubmission file exists? */
            IF(sf_resub.file_id IS NOT NULL, 1, 0) AS has_resubmission,

            /* Final manuscript exists? */
            IF(sf_fm.file_id IS NOT NULL, 1, 0) AS has_final_ms,

            /* Payment: online (non-bank) completed */
            COALESCE(pay.online_count, 0) AS online_pay_count,
            COALESCE(pay.bank_completed, 0) AS bank_pay_count,
            pay.total_paid,
            pay.currency,

            /* Bank slip uploaded */
            IF(sf_pay.file_id IS NOT NULL, 1, 0) AS has_payment_receipt,
            sf_pay.payment_proof_status,

            /* Days since decision */
            DATEDIFF(CURDATE(), DATE(ed.created_at)) AS days_since_decision,

            /* Days until due */
            DATEDIFF(ed.due_date, CURDATE()) AS days_until_due

        FROM submissions s

        /* Get only latest editorial decision per submission */
        JOIN (
            SELECT submission_id, MAX(created_at) AS latest_at
            FROM editorial_decisions
            WHERE decision IN ('accepted','accepted_with_changes','resubmit','rejected')
            GROUP BY submission_id
        ) ed_latest ON ed_latest.submission_id = s.submission_id

        JOIN editorial_decisions ed
            ON ed.submission_id = s.submission_id
           AND ed.created_at    = ed_latest.latest_at

        LEFT JOIN journals j         ON j.journal_id     = s.journal_id
        LEFT JOIN users u            ON u.user_id        = s.user_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id

        /* Latest payment receipt file */
        LEFT JOIN (
            SELECT f1.submission_id, f1.file_id, f1.payment_proof_status, f1.publication_date
            FROM submission_files f1
            INNER JOIN (
                SELECT submission_id, MAX(uploaded_at) AS mx
                FROM submission_files WHERE file_type='payment_receipt' GROUP BY submission_id
            ) f2 ON f1.submission_id=f2.submission_id AND f1.uploaded_at=f2.mx
            AND f1.file_type='payment_receipt'
        ) sf_pay ON sf_pay.submission_id = s.submission_id

        /* Latest resubmission file */
        LEFT JOIN (
            SELECT submission_id, MAX(file_id) AS file_id
            FROM submission_files WHERE file_type='resubmission' GROUP BY submission_id
        ) sf_resub ON sf_resub.submission_id = s.submission_id

        /* Latest final manuscript */
        LEFT JOIN (
            SELECT submission_id, MAX(file_id) AS file_id
            FROM submission_files WHERE file_type='final_manuscript_revised' GROUP BY submission_id
        ) sf_fm ON sf_fm.submission_id = s.submission_id

        /* Publication date from any file record */
        LEFT JOIN (
            SELECT submission_id, MAX(publication_date) AS publication_date
            FROM submission_files WHERE publication_date IS NOT NULL GROUP BY submission_id
        ) sf_pub ON sf_pub.submission_id = s.submission_id

        /* Payments */
        LEFT JOIN (
            SELECT submission_id,
                COUNT(CASE WHEN status='COMPLETED' AND gateway != 'bank' THEN 1 END) AS online_count,
                COUNT(CASE WHEN status='COMPLETED' AND gateway = 'bank'  THEN 1 END) AS bank_completed,
                SUM(CASE WHEN status='COMPLETED' THEN amount ELSE 0 END) AS total_paid,
                MAX(CASE WHEN status='COMPLETED' THEN currency END) AS currency
            FROM payments GROUP BY submission_id
        ) pay ON pay.submission_id = s.submission_id

        $whereSql
        ORDER BY ed.due_date ASC, ed.created_at DESC
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $dbError = $e->getMessage();
}

/* ── PHP-side fee_paid filter ── */
if ($fee_paid_f === 'Yes') {
    $rows = array_values(array_filter($rows, fn($r) =>
        (int)$r['online_pay_count'] > 0 || (int)$r['bank_pay_count'] > 0 || (int)$r['has_payment_receipt']
    ));
}
if ($fee_paid_f === 'No') {
    $rows = array_values(array_filter($rows, fn($r) =>
        (int)$r['online_pay_count'] === 0 && (int)$r['bank_pay_count'] === 0 && !(int)$r['has_payment_receipt']
    ));
}

/* ── Stats ── */
$totalRows     = count($rows);
$overdueRows   = count(array_filter($rows, fn($r) => $r['due_date'] && $r['days_until_due'] < 0 && $r['due_date']));
$dueTodayRows  = count(array_filter($rows, fn($r) => $r['due_date'] && (int)$r['days_until_due'] === 0));
$paidRows      = count(array_filter($rows, fn($r) => (int)$r['online_pay_count'] > 0 || (int)$r['bank_pay_count'] > 0 || (int)$r['has_payment_receipt']));
$unpaidRows    = $totalRows - $paidRows;

$user_name     = $_SESSION['username'] ?? 'Admin';
$active_section = 'reminders';

/* ── Helpers ── */
function feePaidLabel($r) {
    $paid = (int)$r['online_pay_count'] > 0 || (int)$r['bank_pay_count'] > 0 || (int)$r['has_payment_receipt'];
    if (!$paid) return ['No', 'bg-red-100 text-red-700'];
    if ((int)$r['online_pay_count'] > 0) return ['Online ✓', 'bg-green-100 text-green-700'];
    if ((int)$r['bank_pay_count'] > 0)   return ['Bank ✓',   'bg-blue-100 text-blue-700'];
    return ['Slip ⏳', 'bg-amber-100 text-amber-700'];
}

function decisionColor($d) {
    return match(strtolower($d ?? '')) {
        'accepted'              => 'bg-green-100 text-green-700',
        'accepted_with_changes' => 'bg-blue-100 text-blue-700',
        'resubmit'              => 'bg-amber-100 text-amber-700',
        'rejected'              => 'bg-red-100 text-red-700',
        default                 => 'bg-gray-100 text-gray-500',
    };
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Reminder 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>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></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,
.sidebar.collapsed .nav-item span,
.sidebar.collapsed .submenu,
.sidebar.collapsed button span.label { display:none !important; }
.sidebar.collapsed .nav-item i.main-icon { display:inline-block !important; font-size:22px; margin-right:0; }
.sidebar.collapsed .nav-item i.arrow-icon,
.sidebar.collapsed .submenu { display:none !important; }
.content { margin-left:250px; transition:margin-left .3s; height:100vh; overflow-y:auto; }
.content.collapsed-sidebar { margin-left:70px; }
.nav-item { padding:10px 12px; cursor:pointer; transition:background .2s; display:flex; align-items:center; }
.nav-item:hover { background:#4a5568; }
.nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
@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,body.dark textarea { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }
body.dark table { color:#e2e8f0; }
body.dark .data-table th { background:#374151 !important; color:#9ca3af; border-color:#4b5563; }
body.dark .data-table td { border-color:#374151; }

/* 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:9px 10px; text-align:left;
    border-bottom:2px solid #e2e8f0; white-space:nowrap; position:sticky; top:0; z-index:2;
}
.data-table td { padding:7px 10px; font-size:12px; border-bottom:1px solid #f1f5f9; vertical-align:middle; }
.data-table tbody tr:hover { background:#f8fafc; }
.data-table tbody tr.overdue-row td { background:#fef2f2 !important; }
.data-table tbody tr.due-today-row td { background:#fefce8 !important; }
body.dark .data-table tbody tr:hover { background:#374151; }

.badge { display:inline-flex; align-items:center; padding:2px 8px; border-radius:9999px; font-size:10.5px; font-weight:700; white-space:nowrap; }

/* 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; }
</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-bell text-indigo-500"></i> Reminder 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 ($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-5 gap-3 mb-5">
      <?php $sc = [
        ['Total',        $totalRows,    'text-indigo-600', 'bg-indigo-50',  'fa-bell'],
        ['Overdue',      $overdueRows,  'text-red-600',    'bg-red-50',     'fa-exclamation-circle'],
        ['Due Today',    $dueTodayRows, 'text-amber-600',  'bg-amber-50',   'fa-calendar-day'],
        ['Fee Paid',     $paidRows,     'text-green-600',  'bg-green-50',   'fa-check-circle'],
        ['Fee Pending',  $unpaidRows,   'text-orange-600', 'bg-orange-50',  'fa-clock'],
      ]; 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>

    <!-- Filter -->
    <div class="bg-white p-4 rounded-xl shadow mb-4">
      <h2 class="text-sm font-semibold mb-3 flex items-center gap-2 text-gray-700">
        <i class="fas fa-filter text-indigo-500"></i> Filter Reminders
      </h2>
      <form method="GET" class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3">
        <div>
          <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Search UMI</label>
          <input type="text" name="umi" value="<?= htmlspecialchars($umi) ?>"
                 placeholder="RSIS-AB1234"
                 class="w-full 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">Decision</label>
          <select name="decision" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm">
            <option value="">All</option>
            <option value="accepted"              <?= $decision_f === 'accepted'              ? 'selected' : '' ?>>Accepted</option>
            <option value="accepted_with_changes" <?= $decision_f === 'accepted_with_changes' ? 'selected' : '' ?>>Accepted w/ Changes</option>
            <option value="resubmit"              <?= $decision_f === 'resubmit'              ? 'selected' : '' ?>>Resubmit</option>
            <option value="rejected"              <?= $decision_f === 'rejected'              ? 'selected' : '' ?>>Rejected</option>
          </select>
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Journal</label>
          <select name="journal_id" class="w-full 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">Country</label>
          <input type="text" name="country" value="<?= htmlspecialchars($country_f) ?>"
                 placeholder="India"
                 class="w-full 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">Sub. Date</label>
          <input type="date" name="submission_date" value="<?= htmlspecialchars($submission_date) ?>"
                 class="w-full 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">Due Date</label>
          <input type="date" name="due_date" value="<?= htmlspecialchars($due_date_f) ?>"
                 class="w-full 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">Fee Paid</label>
          <select name="fee_paid" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm">
            <option value="">All</option>
            <option value="Yes" <?= $fee_paid_f === 'Yes' ? 'selected' : '' ?>>Yes</option>
            <option value="No"  <?= $fee_paid_f === 'No'  ? 'selected' : '' ?>>No</option>
          </select>
        </div>
        <div class="flex items-end gap-2">
          <button type="submit" class="flex-1 bg-indigo-600 text-white py-2 rounded-lg hover:bg-indigo-700 text-sm font-semibold flex items-center justify-center gap-1">
            <i class="fas fa-search"></i> Filter
          </button>
          <a href="reminders.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>
      </form>
    </div>

    <!-- Legend + Export -->
    <div class="flex items-center justify-between mb-3 flex-wrap gap-2">
      <div class="flex items-center gap-4 text-xs text-gray-500">
        <span class="flex items-center gap-1.5">
          <span class="w-3 h-3 rounded bg-red-100 border border-red-300 inline-block"></span> Overdue
        </span>
        <span class="flex items-center gap-1.5">
          <span class="w-3 h-3 rounded bg-yellow-100 border border-yellow-300 inline-block"></span> Due Today
        </span>
        <span class="flex items-center gap-1.5">
          <span class="w-3 h-3 rounded bg-white border border-gray-200 inline-block"></span> Upcoming
        </span>
      </div>
      <div class="flex items-center gap-2">
        <label class="flex items-center gap-1.5 text-xs text-gray-500 cursor-pointer">
          <input type="checkbox" id="selAllTop" onchange="selectAllRows(this)"> Select All
        </label>
        <button onclick="bulkSendWA()" class="bg-green-600 text-white px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1 hover:bg-green-700">
          <i class="fab fa-whatsapp"></i> Bulk WA
        </button>
        <button onclick="exportExcel()" class="bg-emerald-600 text-white px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1 hover:bg-emerald-700">
          <i class="fas fa-file-excel"></i> Export
        </button>
        <span class="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded-full font-bold">
          <?= number_format($totalRows) ?> records
        </span>
      </div>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
      <?php if (empty($rows)): ?>
      <div class="text-center py-16 text-gray-400">
        <i class="fas fa-bell-slash text-4xl mb-3 block opacity-30"></i>
        <p class="text-sm">No reminder entries found for the selected filters.</p>
      </div>
      <?php else: ?>
      <div style="overflow-x:auto; max-height:calc(100vh - 380px)">
        <table class="data-table" id="reminderTable">
          <thead>
            <tr>
              <th class="px-2 w-8 text-center"><input type="checkbox" id="selAllTh" onchange="selectAllRows(this)"></th>
              <th class="px-2">UMI</th>
              <th class="px-2">Title</th>
              <th class="px-2">Author</th>
              <th class="px-2">Email</th>
              <th class="px-2">Country</th>
              <th class="px-2">Phone</th>
              <th class="px-2">Journal</th>
              <th class="px-2">Sub. Date</th>
              <th class="px-2">Review Sent</th>
              <th class="px-2">Decision</th>
              <th class="px-2">Fee Paid</th>
              <th class="px-2">Payment Link</th>
              <th class="px-2">Publication</th>
              <th class="px-2">Due Date</th>
              <th class="px-2">Days Left</th>
              <th class="px-2 text-center">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $r):
              [$feeLabel, $feeClass] = feePaidLabel($r);
              $decClass  = decisionColor($r['decision']);
              $isOverdue  = $r['due_date'] && (int)$r['days_until_due'] < 0;
              $isDueToday = $r['due_date'] && (int)$r['days_until_due'] === 0;
              $rowClass   = $isOverdue ? 'overdue-row' : ($isDueToday ? 'due-today-row' : '');

              $fullPhone  = trim(($r['phone_country_code'] ?? '') . ($r['phone'] ?? ''));
              $fullPhone  = ltrim($fullPhone, '+');
              $payUrl     = 'https://communeglobal.com/payment/pay.php?tracking_code=' . urlencode($r['tracking_code'] ?? '');

              // JS-safe escaping
              $js = fn($v) => htmlspecialchars(addslashes((string)($v ?? '')), ENT_QUOTES);
            ?>
            <tr class="<?= $rowClass ?>" data-phone="<?= htmlspecialchars($fullPhone) ?>"
                data-umi="<?= htmlspecialchars($r['tracking_code'] ?? '') ?>"
                data-decision="<?= htmlspecialchars($r['decision'] ?? '') ?>">

              <td class="px-2 text-center">
                <input type="checkbox" class="row-cb" value="<?= $r['submission_id'] ?>">
              </td>

              <!-- UMI -->
              <td class="px-2">
                <?php if ($r['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($r['tracking_code']) ?>
                </span>
                <?php else: ?><span class="text-gray-300 text-xs">#<?= $r['submission_id'] ?></span><?php endif; ?>
              </td>

              <!-- Title -->
              <td class="px-2" style="max-width:200px">
                <div class="text-xs text-gray-700 truncate" style="max-width:190px"
                     title="<?= htmlspecialchars($r['article_title'] ?? '') ?>">
                  <?= htmlspecialchars(mb_strimwidth($r['article_title'] ?? '—', 0, 55, '…')) ?>
                </div>
              </td>

              <!-- Author -->
              <td class="px-2">
                <div class="text-xs font-medium text-gray-800 whitespace-nowrap">
                  <?= htmlspecialchars(trim($r['first_name'] . ' ' . $r['last_name'])) ?>
                </div>
              </td>

              <!-- Email -->
              <td class="px-2">
                <div class="text-xs text-gray-500"><?= htmlspecialchars($r['author_email'] ?? '') ?></div>
              </td>

              <!-- Country -->
              <td class="px-2 text-xs text-gray-500 whitespace-nowrap">
                <?= htmlspecialchars($r['country'] ?? '—') ?>
              </td>

              <!-- Phone -->
              <td class="px-2 text-xs text-gray-500 whitespace-nowrap font-mono">
                <?= htmlspecialchars($fullPhone ?: '—') ?>
              </td>

              <!-- Journal -->
              <td class="px-2">
                <span class="text-xs text-teal-700 bg-teal-50 border border-teal-200 rounded px-1.5 py-0.5">
                  <?= htmlspecialchars(mb_strimwidth($r['journal_name'] ?? '—', 0, 30, '…')) ?>
                </span>
              </td>

              <!-- Sub Date -->
              <td class="px-2 text-xs text-gray-400 whitespace-nowrap">
                <?= $r['submitted_at'] ? date('d M Y', strtotime($r['submitted_at'])) : '—' ?>
              </td>

              <!-- Review Sent / Decision Date -->
              <td class="px-2 text-xs whitespace-nowrap">
                <?= $r['decision_date']
                  ? '<span class="text-green-600 font-medium">' . date('d M Y', strtotime($r['decision_date'])) . '</span>'
                  : '<span class="text-gray-300">—</span>' ?>
              </td>

              <!-- Decision -->
              <td class="px-2">
                <span class="badge <?= $decClass ?>">
                  <?= htmlspecialchars(ucwords(str_replace('_', ' ', $r['decision'] ?? '—'))) ?>
                </span>
              </td>

              <!-- Fee Paid -->
              <td class="px-2">
                <span class="badge <?= $feeClass ?>"><?= $feeLabel ?></span>
                <?php if ($r['total_paid']): ?>
                <div class="text-xs text-gray-400 mt-0.5">
                  <?= $r['currency'] === 'USD' ? '$' : '₹' ?><?= number_format((float)$r['total_paid'], 0) ?>
                </div>
                <?php endif; ?>
              </td>

              <!-- Payment Link -->
              <td class="px-2">
                <a href="<?= htmlspecialchars($payUrl) ?>" target="_blank"
                   class="text-xs text-indigo-600 hover:underline font-semibold flex items-center gap-1">
                  <i class="fas fa-external-link-alt text-xs"></i> Pay Now
                </a>
              </td>

              <!-- Publication Date -->
              <td class="px-2 text-xs text-gray-500 whitespace-nowrap">
                <?= $r['publication_date'] ? date('d M Y', strtotime($r['publication_date'])) : '—' ?>
              </td>

              <!-- Due Date -->
              <td class="px-2 text-xs whitespace-nowrap">
                <?php if ($r['due_date']): ?>
                <span class="font-medium <?= $isOverdue ? 'text-red-600' : ($isDueToday ? 'text-amber-600' : 'text-gray-600') ?>">
                  <?= date('d M Y', strtotime($r['due_date'])) ?>
                </span>
                <?php else: ?><span class="text-gray-300">—</span><?php endif; ?>
              </td>

              <!-- Days Left -->
              <td class="px-2 text-center">
                <?php if ($r['due_date']): ?>
                  <?php $dl = (int)$r['days_until_due']; ?>
                  <span class="badge <?= $dl < 0 ? 'bg-red-100 text-red-700' : ($dl === 0 ? 'bg-amber-100 text-amber-700' : 'bg-green-100 text-green-700') ?>">
                    <?= $dl < 0 ? abs($dl) . 'd over' : ($dl === 0 ? 'Today' : $dl . 'd left') ?>
                  </span>
                <?php else: ?>—<?php endif; ?>
              </td>

              <!-- Actions -->
              <td class="px-2 text-center whitespace-nowrap">
                <div class="flex items-center justify-center gap-2">

                  <!-- Edit -->
                  <button onclick='openEditModal(<?= json_encode([
                    "sid"          => $r['submission_id'],
                    "umi"          => $r['tracking_code']  ?? '',
                    "email"        => $r['author_email']   ?? '',
                    "title"        => $r['article_title']  ?? '',
                    "author"       => trim($r['first_name'] . ' ' . $r['last_name']),
                    "decision"     => $r['decision']       ?? '',
                    "fee_paid"     => $feeLabel,
                    "country"      => $r['country']        ?? '',
                    "journal"      => $r['journal_name']   ?? '',
                    "phone"        => $fullPhone,
                    "sub_date"     => $r['submitted_at']   ? date('Y-m-d', strtotime($r['submitted_at'])) : '',
                    "dec_date"     => $r['decision_date']  ? date('Y-m-d', strtotime($r['decision_date'])) : '',
                    "due_date"     => $r['due_date']       ?? '',
                    "pub_date"     => $r['publication_date'] ?? '',
                    "pay_url"      => $payUrl,
                  ]) ?>)'
                    title="Edit" class="text-amber-500 hover:text-amber-600 text-base bg-transparent border-none cursor-pointer">
                    <i class="fas fa-edit"></i>
                  </button>

                  <!-- WhatsApp Decision -->
                  <button onclick='sendDecisionWA(<?= json_encode([
                    "decision" => $r['decision']       ?? '',
                    "phone"    => $fullPhone,
                    "author"   => trim($r['first_name'] . ' ' . $r['last_name']),
                    "journal"  => $r['journal_name']   ?? '',
                    "due_date" => $r['due_date']        ?? '',
                    "umi"      => $r['tracking_code']   ?? '',
                    "title"    => $r['article_title']  ?? '',
                    "pay_url"  => $payUrl,
                  ]) ?>)'
                    title="Send Decision WA" class="text-green-600 hover:text-green-700 text-base bg-transparent border-none cursor-pointer">
                    <i class="fab fa-whatsapp"></i>
                  </button>

                  <!-- WhatsApp Reminder bell -->
                  <button onclick='sendReminderWA(<?= json_encode([
                    "decision" => $r['decision']      ?? '',
                    "phone"    => $fullPhone,
                    "author"   => trim($r['first_name'] . ' ' . $r['last_name']),
                    "journal"  => $r['journal_name']  ?? '',
                    "umi"      => $r['tracking_code'] ?? '',
                    "title"    => $r['article_title'] ?? '',
                    "pay_url"  => $payUrl,
                  ]) ?>)'
                    title="Send Reminder WA" class="text-indigo-500 hover:text-indigo-700 text-base bg-transparent border-none cursor-pointer">
                    <i class="fas fa-bell"></i>
                  </button>

                  <!-- View Submission -->
                  <a href="submission_view.php?id=<?= $r['submission_id'] ?>"
                     title="View Submission"
                     class="text-blue-500 hover:text-blue-700 text-base">
                    <i class="fas fa-eye"></i>
                  </a>

                </div>
              </td>

            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <div class="px-4 py-2 border-t text-xs text-gray-400 flex items-center gap-4">
        <span><?= number_format($totalRows) ?> record(s)</span>
        <span class="text-red-400"><?= $overdueRows ?> overdue</span>
        <span class="text-amber-400"><?= $dueTodayRows ?> due today</span>
      </div>
      <?php endif; ?>
    </div>

  </main>
</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');
}

/* ── 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);
}

/* ── Select All ── */
function selectAllRows(cb){
  document.querySelectorAll('.row-cb').forEach(function(x){ x.checked = cb.checked; });
  document.querySelectorAll('#selAllTop,#selAllTh').forEach(function(x){ x.checked = cb.checked; });
}

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

/* ════════════════════════════════════════
   EDIT MODAL
════════════════════════════════════════ */
function openEditModal(d){
  Swal.fire({
    title: '<div style="font-size:17px;font-weight:700;color:#1e293b;text-align:left">'
         + '<i class="fas fa-edit" style="color:#6366f1;margin-right:8px"></i>Edit Reminder Entry</div>'
         + '<div style="font-size:12px;font-family:monospace;color:#64748b;margin-top:5px;text-align:left;background:#f1f5f9;padding:4px 10px;border-radius:6px;display:inline-block">'
         + escHtml(d.umi || '#'+d.sid) + '</div>',
    width: '900px',
    padding: '28px',
    html: `
      <div style="text-align:left;font-family:'Roboto',sans-serif;max-height:70vh;overflow-y:auto">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">UMI / Tracking Code</label>
            <input id="em_umi" value="${escHtml(d.umi)}" readonly
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;background:#f1f5f9;font-family:monospace;box-sizing:border-box">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Email</label>
            <input id="em_email" value="${escHtml(d.email)}"
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;box-sizing:border-box"
              onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#d1d5db'">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Title</label>
            <input id="em_title" value="${escHtml(d.title)}"
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;box-sizing:border-box"
              onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#d1d5db'">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Author</label>
            <input id="em_author" value="${escHtml(d.author)}" readonly
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;background:#f1f5f9;box-sizing:border-box">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Decision</label>
            <input id="em_decision" value="${escHtml(d.decision)}" readonly
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;background:#f1f5f9;box-sizing:border-box">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Fee Paid</label>
            <input id="em_fee" value="${escHtml(d.fee_paid)}" readonly
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;background:#f1f5f9;box-sizing:border-box">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Country</label>
            <input id="em_country" value="${escHtml(d.country)}"
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;box-sizing:border-box"
              onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#d1d5db'">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Phone / WhatsApp</label>
            <input id="em_phone" value="${escHtml(d.phone)}"
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;box-sizing:border-box"
              onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#d1d5db'">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Initial Submission Date</label>
            <input value="${escHtml(d.sub_date)}" readonly
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;background:#f1f5f9;box-sizing:border-box">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Review Sent Date</label>
            <input value="${escHtml(d.dec_date) || '—'}" readonly
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;background:#f1f5f9;box-sizing:border-box">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Payment Due Date</label>
            <input type="date" id="em_due" value="${escHtml(d.due_date)}"
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;box-sizing:border-box"
              onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#d1d5db'">
          </div>

          <div>
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Publication Date</label>
            <input type="date" id="em_pub" value="${escHtml(d.pub_date)}"
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;box-sizing:border-box"
              onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#d1d5db'">
          </div>

          <div style="grid-column:1/-1">
            <label style="display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:5px">Payment Link</label>
            <input id="em_payurl" value="${escHtml(d.pay_url)}"
              style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:12px;font-family:monospace;box-sizing:border-box"
              onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#d1d5db'">
          </div>

        </div>
      </div>`,
    showCancelButton: true,
    confirmButtonText: '<i class="fas fa-save" style="margin-right:5px"></i> Save Changes',
    cancelButtonText: '<i class="fas fa-times" style="margin-right:4px"></i> Cancel',
    confirmButtonColor: '#6366f1',
    cancelButtonColor: '#6b7280',
    focusConfirm: false,
    preConfirm: function(){
      return fetch('ajax/update_reminder.php', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
          submission_id:    d.sid,
          phone:            document.getElementById('em_phone').value,
          due_date:         document.getElementById('em_due').value,
          publication_date: document.getElementById('em_pub').value,
        })
      })
      .then(function(r){ return r.json(); })
      .then(function(res){
        if (!res.success){ Swal.showValidationMessage('❌ ' + (res.message || 'Update failed')); return false; }
        return res;
      })
      .catch(function(){ Swal.showValidationMessage('❌ Network error'); return false; });
    }
  }).then(function(res){
    if (res.isConfirmed && res.value){ showToast('Entry updated successfully!'); setTimeout(function(){ location.reload(); }, 900); }
  });
}

/* ════════════════════════════════════════
   SEND DECISION WHATSAPP
════════════════════════════════════════ */
function sendDecisionWA(d){
  var decision  = (d.decision || '').toLowerCase();
  var isAccepted = ['accepted','accepted_with_changes'].includes(decision);
  var template   = isAccepted ? 'newfees' : 'resubmissionneww';
  var preview    = isAccepted
    ? '📩 Acceptance + payment instructions will be sent'
    : '📩 Revision / Resubmission instructions will be sent';

  Swal.fire({
    title: '<div style="font-size:16px;font-weight:700;color:#15803d;text-align:left"><i class="fab fa-whatsapp" style="margin-right:6px"></i>Send Decision via WhatsApp</div>',
    html: `
      <div style="text-align:left;font-size:13px">
        <label style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase">Mobile / WhatsApp Number</label>
        <input id="wa_phone" class="swal2-input" value="${escHtml(d.phone)}" placeholder="+919876543210" style="margin-top:6px">
        <div style="margin-top:10px;padding:10px;background:#f0fdf4;border:1px solid #a7f3d0;border-radius:8px;font-size:12px;color:#166534">
          <strong>Template:</strong> ${template}<br>
          ${preview}<br>
          <strong>Author:</strong> ${escHtml(d.author)} | <strong>Journal:</strong> ${escHtml(d.journal)}<br>
          <strong>UMI:</strong> ${escHtml(d.umi)} | <strong>Due:</strong> ${escHtml(d.due_date || '—')}
        </div>
      </div>`,
    confirmButtonText: '<i class="fab fa-whatsapp" style="margin-right:5px"></i> Send Now',
    cancelButtonText: 'Cancel',
    showCancelButton: true,
    confirmButtonColor: '#15803d',
    focusConfirm: false,
    preConfirm: function(){
      var phone = document.getElementById('wa_phone').value.trim();
      if (!phone){ Swal.showValidationMessage('Phone number is required'); return false; }
      return fetch('https://rsis.international/articles/tools/send-whatsapp-apibackup.php', {
        method: 'POST',
        body: new URLSearchParams({
          action:       'review_decision_whatsapp',
          phone:        phone,
          decision:     decision,
          author_name:  d.author,
          journal_name: d.journal,
          due_date:     d.due_date || '',
          umi:          d.umi,
          title:        d.title,
          payment_link: d.pay_url
        })
      })
      .then(function(r){ return r.json(); })
      .then(function(res){ if (!res.success) throw new Error(res.error || 'Send failed'); return res; })
      .catch(function(err){ Swal.showValidationMessage('❌ ' + err.message); return false; });
    }
  }).then(function(res){
    if (res.isConfirmed && res.value) showToast('WhatsApp decision sent!');
  });
}

/* ════════════════════════════════════════
   SEND REMINDER WHATSAPP
════════════════════════════════════════ */
function sendReminderWA(d){
  var decision   = (d.decision || '').toLowerCase();
  var isAccepted = ['accepted','accepted_with_changes'].includes(decision);
  var template   = isAccepted ? 'reminderfirstfees' : 'revisisonreeminder';

  Swal.fire({
    title: '<div style="font-size:16px;font-weight:700;color:#4f46e5;text-align:left"><i class="fas fa-bell" style="margin-right:6px"></i>Send Reminder via WhatsApp</div>',
    html: `
      <div style="text-align:left;font-size:13px">
        <label style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase">Mobile / WhatsApp Number</label>
        <input id="wa_phone2" class="swal2-input" value="${escHtml(d.phone)}" placeholder="+919876543210" style="margin-top:6px">
        <div style="margin-top:10px;padding:10px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;font-size:12px;color:#1d4ed8">
          <strong>Template:</strong> ${template}<br>
          <strong>Author:</strong> ${escHtml(d.author)} | <strong>Journal:</strong> ${escHtml(d.journal)}<br>
          <strong>UMI:</strong> ${escHtml(d.umi)}
        </div>
      </div>`,
    confirmButtonText: '<i class="fas fa-bell" style="margin-right:5px"></i> Send Reminder',
    cancelButtonText: 'Cancel',
    showCancelButton: true,
    confirmButtonColor: '#4f46e5',
    focusConfirm: false,
    preConfirm: function(){
      var phone = document.getElementById('wa_phone2').value.trim();
      if (!phone){ Swal.showValidationMessage('Phone number is required'); return false; }
      return fetch('https://rsis.international/articles/tools/send-whatsapp-apibackup.php', {
        method: 'POST',
        body: new URLSearchParams({
          action:       'registration_reminder_whatsapp',
          phone:        phone,
          decision:     decision,
          author_name:  d.author,
          journal_name: d.journal,
          umi:          d.umi,
          title:        d.title,
          payment_link: d.pay_url
        })
      })
      .then(function(r){ return r.json(); })
      .then(function(res){ if (!res.success) throw new Error(res.error || 'Reminder failed'); return res; })
      .catch(function(err){ Swal.showValidationMessage('❌ ' + err.message); return false; });
    }
  }).then(function(res){
    if (res.isConfirmed && res.value) showToast('Reminder sent!');
  });
}

/* ════════════════════════════════════════
   BULK WHATSAPP (selected rows)
════════════════════════════════════════ */
function bulkSendWA(){
  var selected = Array.from(document.querySelectorAll('.row-cb:checked'))
    .map(function(cb){ return cb.closest('tr'); })
    .filter(Boolean);

  if (!selected.length){
    Swal.fire({icon:'warning',title:'No rows selected',text:'Please check at least one row first.',timer:2000,showConfirmButton:false});
    return;
  }

  Swal.fire({
    title: 'Bulk WhatsApp Reminder',
    html: '<p style="font-size:13px">Send reminder WA to <strong>' + selected.length + '</strong> selected author(s)?</p>',
    icon: 'question',
    confirmButtonText: 'Send All',
    confirmButtonColor: '#15803d',
    showCancelButton: true,
    cancelButtonText: 'Cancel',
  }).then(function(res){
    if (!res.isConfirmed) return;
    var promises = selected.map(function(row){
      var phone    = row.dataset.phone;
      var umi      = row.dataset.umi;
      var decision = (row.dataset.decision || '').toLowerCase();
      if (!phone) return Promise.resolve({ umi, success: false, error: 'No phone' });
      var isAccepted = ['accepted','accepted_with_changes'].includes(decision);
      return fetch('https://rsis.international/articles/tools/send-whatsapp-apibackup.php', {
        method: 'POST',
        body: new URLSearchParams({
          action:       'registration_reminder_whatsapp',
          phone:        phone,
          decision:     decision,
          umi:          umi,
          payment_link: 'https://communeglobal.com/payment/pay.php?tracking_code=' + encodeURIComponent(umi)
        })
      }).then(function(r){ return r.json(); }).then(function(r){ return { umi, success: r.success }; })
        .catch(function(){ return { umi, success: false, error: 'fetch error' }; });
    });

    Promise.all(promises).then(function(results){
      var ok   = results.filter(function(r){ return r.success; }).length;
      var fail = results.length - ok;
      Swal.fire({
        icon: ok > 0 ? 'success' : 'error',
        title: 'Bulk WA Done',
        html: '<b>' + ok + '</b> sent, <b>' + fail + '</b> failed',
        timer: 3000, showConfirmButton: false
      });
    });
  });
}

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