<?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();

define('SITE_ROOT', 'https://communeglobal.com');

function fsFileUrl($path) {
    $path = trim((string)$path);
    if ($path === '' || $path === '0') return '';
    if (strpos($path, 'http://') === 0 || strpos($path, 'https://') === 0) return $path;
    $clean = ltrim($path, '/');
    if (strpos($clean, 'uploads/final_submissions') === 0) return SITE_ROOT . '/author/' . $clean;
    return SITE_ROOT . '/' . $clean;
}

// ── AJAX handlers ──────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';

    // ── Save full edit ──────────────────────────────────────────────────────
    if ($action === 'save_edit') {
        $sid      = (int)($_POST['submission_id'] ?? 0);
        $pub_date = trim($_POST['publication_date'] ?? '');
        $decl_st  = $_POST['author_declaration_status'] ?? 'pending';
        $pay_st   = $_POST['payment_proof_status']      ?? 'pending';
        $comment  = trim($_POST['admin_comment']        ?? '');
        $resubPath = trim($_POST['resub_path'] ?? '');
        $stage     = trim($_POST['stage'] ?? '');

        $validDecl = ['pending','approved','not_approved','resubmit'];
        $validPay  = ['pending','approved','not_approved','resubmit'];
        if (!$sid || !in_array($decl_st, $validDecl) || !in_array($pay_st, $validPay)) {
            echo json_encode(['success'=>false,'message'=>'Invalid params']); exit;
        }

        try {
            // Update resubmission file record if path given
            if ($resubPath !== '' || !empty($_POST['resub_was_set'])) {
                if ($resubPath === '') {
                    $pdo->prepare("DELETE FROM submission_files WHERE submission_id=? AND file_type='resubmission'")
                        ->execute([$sid]);
                } else {
                    $chk = $pdo->prepare("SELECT file_id FROM submission_files WHERE submission_id=? AND file_type='resubmission'");
                    $chk->execute([$sid]);
                    if ($chk->fetch()) {
                        $pdo->prepare(
                            "UPDATE submission_files SET stored_path=?, original_name=?,
                             publication_date=?, author_declaration_status=?, payment_proof_status=?, admin_comment=?
                             WHERE submission_id=? AND file_type='resubmission'"
                        )->execute([$resubPath, basename($resubPath), $pub_date ?: null, $decl_st, $pay_st, $comment, $sid]);
                    } else {
                        $pdo->prepare(
                            "INSERT INTO submission_files (submission_id, file_type, original_name, stored_path,
                             publication_date, author_declaration_status, payment_proof_status, admin_comment, uploaded_at)
                             VALUES (?,?,?,?,?,?,?,?,NOW())"
                        )->execute([$sid, 'resubmission', basename($resubPath), $resubPath,
                            $pub_date ?: null, $decl_st, $pay_st, $comment]);
                    }
                }
            }

            // Update status on all resubmission file records for this submission
            $pdo->prepare(
                "UPDATE submission_files SET publication_date=?, author_declaration_status=?,
                 payment_proof_status=?, admin_comment=?
                 WHERE submission_id=? AND file_type='resubmission'"
            )->execute([$pub_date ?: null, $decl_st, $pay_st, $comment, $sid]);

            // Update submission stage if provided
            if ($stage !== '') {
                $allowedStages = ['draft','submitted','under_review','accepted','rejected'];
                if (in_array($stage, $allowedStages)) {
                    $pdo->prepare("UPDATE submissions SET submission_status=?, updated_at=NOW() WHERE submission_id=?")
                        ->execute([$stage, $sid]);
                }
            }

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

    // ── Quick stage change ──────────────────────────────────────────────────
    if ($action === 'change_stage') {
        $sid   = (int)($_POST['submission_id'] ?? 0);
        $stage = $_POST['stage'] ?? '';
        $allowedStages = ['draft','submitted','under_review','accepted','rejected'];
        if (!$sid || !in_array($stage, $allowedStages)) {
            echo json_encode(['success'=>false,'message'=>'Invalid']); exit;
        }
        try {
            $pdo->prepare("UPDATE submissions SET submission_status=?, updated_at=NOW() WHERE submission_id=?")
                ->execute([$stage, $sid]);
            echo json_encode(['success' => true]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }

    echo json_encode(['success'=>false,'message'=>'Unknown action']); exit;
}

// ── Filters ────────────────────────────────────────────────────────────────
$search    = trim($_GET['q']          ?? '');
$journal_f = trim($_GET['journal_id'] ?? '');
$status_f  = trim($_GET['status']     ?? '');

$where  = ["sf.file_type = 'resubmission'"];
$params = [];

if ($search !== '') {
    $where[]  = "(s.tracking_code LIKE ? OR u.email LIKE ? OR CONCAT(u.first_name,' ',u.last_name) LIKE ? OR mi.article_title LIKE ?)";
    $params[] = '%'.$search.'%'; $params[] = '%'.$search.'%';
    $params[] = '%'.$search.'%'; $params[] = '%'.$search.'%';
}
if ($journal_f !== '') { $where[] = "s.journal_id = ?"; $params[] = (int)$journal_f; }
if ($status_f  !== '') { $where[] = "s.submission_status = ?"; $params[] = $status_f; }
$where_sql = 'WHERE ' . implode(' AND ', $where);

$rows = []; $dbError = '';
try {
    $sql = "
        SELECT
            s.submission_id,
            s.tracking_code,
            s.submission_status,
            CONCAT(u.first_name,' ',u.last_name) AS author_name,
            u.email  AS author_email,
            u.country,
            j.name   AS journal_name,
            mi.article_title,
            ed.decision   AS latest_decision,
            ed.created_at AS decision_date,

            /* resubmission file */
            rs.file_id           AS resub_file_id,
            rs.stored_path       AS resub_path,
            rs.original_name     AS resub_name,
            rs.uploaded_at       AS resub_date,
            rs.publication_date  AS pub_date,
            rs.author_declaration_status AS decl_status,
            rs.payment_proof_status      AS pay_status,
            rs.admin_comment             AS admin_comment,

            /* original manuscript */
            om.stored_path AS original_ms_path,
            om.original_name AS original_ms_name,

            sf.uploaded_at AS first_file_date

        FROM submission_files sf
        JOIN submissions s           ON s.submission_id  = sf.submission_id
        LEFT JOIN users u            ON u.user_id        = s.user_id
        LEFT JOIN journals j         ON j.journal_id     = s.journal_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id

        LEFT JOIN (
            SELECT ed1.submission_id, ed1.decision, ed1.created_at
            FROM editorial_decisions ed1
            INNER JOIN (
                SELECT submission_id, MAX(created_at) AS mx FROM editorial_decisions GROUP BY submission_id
            ) ed2 ON ed1.submission_id=ed2.submission_id AND ed1.created_at=ed2.mx
        ) ed ON ed.submission_id = s.submission_id

        LEFT JOIN (
            SELECT f1.submission_id, f1.file_id, f1.stored_path, f1.original_name, f1.uploaded_at,
                   f1.publication_date, f1.author_declaration_status, f1.payment_proof_status, f1.admin_comment
            FROM submission_files f1
            INNER JOIN (
                SELECT submission_id, MAX(uploaded_at) AS mx
                FROM submission_files WHERE file_type='resubmission' GROUP BY submission_id
            ) f2 ON f1.submission_id=f2.submission_id AND f1.uploaded_at=f2.mx AND f1.file_type='resubmission'
        ) rs ON rs.submission_id = s.submission_id

        LEFT JOIN (
            SELECT f1.submission_id, f1.stored_path, f1.original_name
            FROM submission_files f1
            INNER JOIN (
                SELECT submission_id, MAX(uploaded_at) AS mx
                FROM submission_files WHERE file_type IN ('manuscript','manuscript_pdf') GROUP BY submission_id
            ) f2 ON f1.submission_id=f2.submission_id AND f1.uploaded_at=f2.mx
            AND f1.file_type IN ('manuscript','manuscript_pdf')
        ) om ON om.submission_id = s.submission_id

        $where_sql
        GROUP BY s.submission_id
        ORDER BY sf.uploaded_at DESC
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $dbError = $e->getMessage(); }

// ── Stats ──────────────────────────────────────────────────────────────────
$stats = ['total' => 0, 'pending' => 0, 'approved' => 0, 'not_approved' => 0, 'resubmit' => 0];
try {
    $sr = $pdo->query("
        SELECT
            COUNT(DISTINCT submission_id) AS total,
            COUNT(DISTINCT CASE WHEN author_declaration_status='pending' THEN submission_id END) AS pending,
            COUNT(DISTINCT CASE WHEN author_declaration_status='approved' THEN submission_id END) AS approved,
            COUNT(DISTINCT CASE WHEN author_declaration_status='not_approved' THEN submission_id END) AS not_approved,
            COUNT(DISTINCT CASE WHEN author_declaration_status='resubmit' THEN submission_id END) AS resubmit_count
        FROM submission_files WHERE file_type='resubmission'
    ")->fetch(PDO::FETCH_ASSOC);
    if ($sr) {
        $stats['total']       = $sr['total'];
        $stats['pending']     = $sr['pending'];
        $stats['approved']    = $sr['approved'];
        $stats['not_approved']= $sr['not_approved'];
        $stats['resubmit']    = $sr['resubmit_count'];
    }
} catch (PDOException $e) {}

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

// ── Status badge helper ────────────────────────────────────────────────────
function statusBadge($s) {
    $map = [
        'pending'      => ['bg-gray-100 text-gray-500',    '— Pending'],
        'approved'     => ['bg-green-100 text-green-700',  '✓ Approved'],
        'not_approved' => ['bg-red-100 text-red-700',      '✗ Not Approved'],
        'resubmit'     => ['bg-purple-100 text-purple-700','↻ Resubmit'],
    ];
    $info = $map[$s] ?? $map['pending'];
    return '<span class="badge-pill ' . $info[0] . '">' . $info[1] . '</span>';
}

$active_section = 'resubmissions';
$user_name = $_SESSION['username'] ?? 'Admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Resubmissions — Admin | Communeglobal</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; }
body.dark { background-color:#1a202c; color:#e2e8f0; }

/* Sidebar - matches your existing style */
.sidebar { width:250px; background:#2d3748; color:white; transition:all .3s; height:100%; position:fixed; top:0; left:0; z-index:10; overflow-y:auto; }
.sidebar.collapsed { width:70px; }
.sidebar.collapsed .sidebar-title,
.sidebar.collapsed nav ul li a span { display:none; }
.content { margin-left:250px; transition:margin-left .3s; height:100vh; overflow-y:auto; }
.content.collapsed-sidebar { margin-left:70px; }
.nav-item { padding:10px 15px; cursor:pointer; transition:background .2s; }
.nav-item:hover { background:#4a5568; }
.nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
@media(max-width:768px){ .sidebar{transform:translateX(-250px)} .sidebar.mobile-open{transform:translateX(0)} .content{margin-left:0} }

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

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

.badge-pill { display:inline-flex; align-items:center; padding:2px 8px; border-radius:9999px; font-size:11px; font-weight:600; }
.file-link { display:inline-flex; align-items:center; gap:3px; font-size:11px; font-weight:600; color:#2563eb; text-decoration:underline; }
.file-link:hover { color:#1d4ed8; }
.compact-table td,.compact-table th { padding-top:5px !important; padding-bottom:5px !important; vertical-align:middle !important; }
.row-resub td { background:#fefce8 !important; }
body.dark .row-resub td { background:#3b2f00 !important; }

.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()" class="text-gray-500 hover:text-gray-700 hidden md:block" id="toggleSidebar">
        <i class="fas fa-bars text-lg"></i>
      </button>
      <div class="flex items-center gap-2 text-sm text-gray-500">
        <a href="index.php" class="hover:text-blue-600"><i class="fas fa-home"></i></a>
        <i class="fas fa-chevron-right text-xs text-gray-300"></i>
        <h1 class="text-gray-800 font-bold flex items-center gap-2">
          <i class="fas fa-redo text-amber-500"></i> Resubmissions
        </h1>
      </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 Resubs',   (int)$stats['total'],        'text-blue-600',   'bg-blue-50',   'fa-redo'],
        ['Pending Review', (int)$stats['pending'],      'text-amber-600',  'bg-amber-50',  'fa-clock'],
        ['Approved',       (int)$stats['approved'],     'text-green-600',  'bg-green-50',  'fa-check-circle'],
        ['Not Approved',   (int)$stats['not_approved'], 'text-red-600',    'bg-red-50',    'fa-times-circle'],
        ['Need Resubmit',  (int)$stats['resubmit'],     'text-purple-600', 'bg-purple-50', 'fa-sync-alt'],
      ]; 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] ?>"><?= $c[1] ?></div>
        <div class="text-xs text-gray-500 font-medium"><?= $c[0] ?></div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow p-4 mb-4">
      <h2 class="text-sm font-semibold mb-3 flex items-center gap-2 text-gray-700">
        <i class="fas fa-filter text-blue-600"></i> Filter Resubmissions
      </h2>
      <form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-3">
        <div>
          <label class="block text-xs font-semibold text-gray-500 uppercase mb-1">Search</label>
          <input type="text" name="q" value="<?= htmlspecialchars($search) ?>"
                 placeholder="Tracking code / email / title…"
                 class="w-full border border-gray-300 rounded-lg p-2 text-sm">
        </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 p-2 text-sm">
            <option value="">All Journals</option>
            <?php foreach ($journals_list 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">Status</label>
          <select name="status" class="w-full border border-gray-300 rounded-lg p-2 text-sm">
            <option value="">All Statuses</option>
            <option value="submitted"    <?= $status_f === 'submitted'    ? 'selected' : '' ?>>Submitted</option>
            <option value="under_review" <?= $status_f === 'under_review' ? 'selected' : '' ?>>Under Review</option>
            <option value="accepted"     <?= $status_f === 'accepted'     ? 'selected' : '' ?>>Accepted</option>
            <option value="rejected"     <?= $status_f === 'rejected'     ? 'selected' : '' ?>>Rejected</option>
            <option value="draft"        <?= $status_f === 'draft'        ? 'selected' : '' ?>>Draft</option>
          </select>
        </div>
        <div class="flex items-end gap-2">
          <button type="submit" class="flex-1 bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 text-sm font-semibold flex items-center justify-center gap-1">
            <i class="fas fa-search"></i> Filter
          </button>
          <a href="resubmissions.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>

    <!-- Column toggles -->
    <div class="bg-white rounded-lg shadow p-3 mb-4">
      <h3 class="text-xs font-semibold text-gray-600 mb-2 flex items-center gap-1">
        <i class="fas fa-columns text-purple-500"></i> Toggle Columns
      </h3>
      <div class="flex flex-wrap gap-3 text-xs">
        <?php $colDefs = [
          'col-id'     => 'ID',        'col-tracking' => 'Tracking',
          'col-author' => 'Author',    'col-journal'  => 'Journal',
          'col-title'  => 'Title',     'col-date'     => 'Date',
          'col-country'=> 'Country',   'col-resub'    => 'Resub File',
          'col-orig'   => 'Orig. File','col-decision' => 'Decision',
          'col-decl'   => 'Decl. Verify','col-comment'=> 'Comment',
          'col-act'    => 'Actions',
        ]; foreach ($colDefs as $k => $lb): ?>
        <label class="flex items-center gap-1 cursor-pointer text-gray-600">
          <input type="checkbox" class="ccb" data-col="<?= $k ?>" checked> <?= $lb ?>
        </label>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
      <div class="flex items-center justify-between px-4 py-3 border-b border-gray-100 flex-wrap gap-2">
        <div class="flex items-center gap-2">
          <h2 class="text-sm font-bold text-gray-800 flex items-center gap-2">
            <i class="fas fa-redo text-amber-500"></i> Resubmissions List
          </h2>
          <span class="bg-amber-100 text-amber-700 text-xs font-bold px-2 py-0.5 rounded-full">
            <?= count($rows) ?>
          </span>
        </div>
        <button onclick="exportExcel()" class="bg-green-600 text-white px-3 py-1.5 rounded-lg hover:bg-green-700 flex items-center gap-2 text-xs font-semibold">
          <i class="fas fa-file-excel"></i> Export to Excel
        </button>
      </div>

      <?php if (empty($rows)): ?>
      <div class="text-center py-16 text-gray-400">
        <i class="fas fa-redo text-4xl mb-3 block opacity-30"></i>
        <p class="text-sm">No resubmissions found matching your filters.</p>
      </div>
      <?php else: ?>

      <div style="overflow-x:auto; max-height:calc(100vh - 420px)">
      <table class="w-full text-sm text-left text-gray-700 compact-table" id="resubTable">
        <thead class="bg-gray-50 sticky top-0 text-xs uppercase text-gray-500 border-b">
        <tr>
          <th class="px-3 py-2 w-8 text-center">
            <input type="checkbox" id="selAll" onchange="selAllRows(this)">
          </th>
          <th class="px-3 py-2 col-id cursor-pointer" onclick="srt(1)"># <span class="sort-arr" data-i="1"></span></th>
          <th class="px-3 py-2 col-tracking cursor-pointer" onclick="srt(2)">Tracking <span class="sort-arr" data-i="2"></span></th>
          <th class="px-3 py-2 col-author">Author</th>
          <th class="px-3 py-2 col-journal">Journal</th>
          <th class="px-3 py-2 col-title">Title</th>
          <th class="px-3 py-2 col-date cursor-pointer" onclick="srt(6)">Resub Date <span class="sort-arr" data-i="6"></span></th>
          <th class="px-3 py-2 col-country">Country</th>
          <th class="px-3 py-2 col-resub">Resub File</th>
          <th class="px-3 py-2 col-orig">Orig. File</th>
          <th class="px-3 py-2 col-decision">Decision</th>
          <th class="px-3 py-2 col-decl text-center">Decl. Status</th>
          <th class="px-3 py-2 col-comment">Comment</th>
          <th class="px-3 py-2 col-act text-center">Actions</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r):
          $sid      = (int)$r['submission_id'];
          $sStatus  = $r['submission_status'] ?? 'draft';
          $declSt   = $r['decl_status']  ?? 'pending';
          $paySt    = $r['pay_status']   ?? 'pending';
          $pubDate  = $r['pub_date']     ?? '';
          $comment  = $r['admin_comment'] ?? '';
          $hasResub = !empty($r['resub_path']);
          $hasOrig  = !empty($r['original_ms_path']);
          $resubUrl = htmlspecialchars(fsFileUrl($r['resub_path'] ?? ''), ENT_QUOTES);
          $origUrl  = htmlspecialchars(fsFileUrl($r['original_ms_path'] ?? ''), ENT_QUOTES);

          $decisionColors = [
            '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',
          ];
          $decisionColor = $decisionColors[$r['latest_decision'] ?? ''] ?? 'bg-gray-100 text-gray-500';

          $js = fn($v) => htmlspecialchars(addslashes((string)($v??'')), ENT_QUOTES);
        ?>
        <tr class="border-b hover:bg-gray-50 transition <?= $declSt === 'approved' ? 'row-resub' : '' ?>" id="row-<?= $sid ?>">

          <td class="px-3 py-2 text-center">
            <input type="checkbox" class="rcb" value="<?= $sid ?>">
          </td>

          <!-- ID -->
          <td class="px-3 py-2 col-id">
            <span class="font-mono text-xs bg-gray-100 px-1.5 py-0.5 rounded">#<?= $sid ?></span>
          </td>

          <!-- Tracking -->
          <td class="px-3 py-2 col-tracking">
            <?php if ($r['tracking_code']): ?>
            <span class="font-mono text-xs font-bold text-blue-800 bg-blue-50 border border-blue-200 rounded px-1.5 py-0.5">
              <?= htmlspecialchars($r['tracking_code']) ?>
            </span>
            <div class="mt-0.5">
              <span class="sbadge sb-<?= htmlspecialchars($sStatus) ?>"><?= ucfirst(str_replace('_',' ',$sStatus)) ?></span>
            </div>
            <?php else: ?>
              <span class="text-gray-400 text-xs">—</span>
            <?php endif; ?>
          </td>

          <!-- Author -->
          <td class="px-3 py-2 col-author">
            <div class="font-medium text-xs text-gray-800"><?= htmlspecialchars(trim((string)$r['author_name'])) ?></div>
            <div class="text-xs text-gray-400"><?= htmlspecialchars((string)$r['author_email']) ?></div>
          </td>

          <!-- Journal -->
          <td class="px-3 py-2 col-journal text-xs text-gray-600">
            <?= htmlspecialchars($r['journal_name'] ?? '—') ?>
          </td>

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

          <!-- Resub Date -->
          <td class="px-3 py-2 col-date text-xs text-gray-400 whitespace-nowrap">
            <?= htmlspecialchars(substr((string)$r['resub_date'], 0, 10)) ?>
          </td>

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

          <!-- Resubmission File -->
          <td class="px-3 py-2 col-resub">
            <?php if ($hasResub): ?>
            <a href="<?= $resubUrl ?>" target="_blank" class="file-link">
              <i class="fas fa-file-alt text-amber-500"></i> View
            </a>
            <div class="text-xs text-gray-400"><?= htmlspecialchars(mb_strimwidth($r['resub_name'] ?? '', 0, 25, '…')) ?></div>
            <?php else: ?>
              <span class="text-gray-300 text-xs">—</span>
            <?php endif; ?>
          </td>

          <!-- Original File -->
          <td class="px-3 py-2 col-orig">
            <?php if ($hasOrig): ?>
            <a href="<?= $origUrl ?>" target="_blank" class="file-link">
              <i class="fas fa-file-pdf text-blue-500"></i> View
            </a>
            <?php else: ?>
              <span class="text-gray-300 text-xs">—</span>
            <?php endif; ?>
          </td>

          <!-- Decision -->
          <td class="px-3 py-2 col-decision">
            <?php if ($r['latest_decision']): ?>
            <span class="badge-pill <?= $decisionColor ?>">
              <?= htmlspecialchars(ucwords(str_replace('_', ' ', $r['latest_decision']))) ?>
            </span>
            <div class="text-xs text-gray-400 mt-0.5"><?= htmlspecialchars(substr((string)$r['decision_date'], 0, 10)) ?></div>
            <?php else: ?>
              <span class="text-gray-300 text-xs">—</span>
            <?php endif; ?>
          </td>

          <!-- Decl Status -->
          <td class="px-3 py-2 col-decl text-center">
            <?= statusBadge($declSt) ?>
          </td>

          <!-- Comment -->
          <td class="px-3 py-2 col-comment text-xs text-gray-500 max-w-xs truncate" title="<?= htmlspecialchars($comment) ?>">
            <?= $comment ? htmlspecialchars(mb_strimwidth($comment, 0, 40, '…')) : '<span class="text-gray-300">—</span>' ?>
          </td>

          <!-- Actions -->
          <td class="px-3 py-2 col-act text-center whitespace-nowrap">
            <!-- Edit -->
            <button onclick='openEditModal(<?= json_encode([
              "sid"        => $sid,
              "tracking"   => $r['tracking_code'] ?? '',
              "title"      => mb_strimwidth($r['article_title'] ?? '', 0, 60, '…'),
              "pub_date"   => $pubDate,
              "decl_st"    => $declSt,
              "pay_st"     => $paySt,
              "comment"    => $comment,
              "resub_path" => $r['resub_path'] ?? '',
              "resub_was"  => $hasResub ? 1 : 0,
              "stage"      => $sStatus,
            ]) ?>)'
              title="Edit" class="text-yellow-500 hover:text-yellow-600 text-base mx-0.5">
              <i class="fas fa-edit"></i>
            </button>

            <!-- View Submission -->
            <a href="submission_view.php?id=<?= $sid ?>" title="View Details"
               class="text-blue-500 hover:text-blue-700 text-base mx-0.5">
              <i class="fas fa-eye"></i>
            </a>

     
            <!-- Review Assignment -->
            <a href="submission_review.php?id=<?= $sid ?>" title="Review Assignment"
               class="text-indigo-500 hover:text-indigo-700 text-base mx-0.5">
              <i class="fas fa-user-check"></i>
            </a>

            <!-- Send Email -->
            <button onclick="sendEmail('<?= $js($r['tracking_code']) ?>','<?= $js($r['author_email']) ?>')"
                    title="Send Email"
                    class="text-purple-500 hover:text-purple-700 text-base mx-0.5 bg-transparent border-none cursor-pointer">
              <i class="fas fa-envelope"></i>
            </button>
          </td>

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

      <div class="px-4 py-2 border-t text-xs text-gray-400">
        <?= count($rows) ?> resubmission(s) found &middot; Yellow rows = declaration approved
      </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 (matches your existing pattern) ── */
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);
}

/* ── Column toggles with localStorage ── */
document.querySelectorAll('.ccb').forEach(function(cb){
  cb.addEventListener('change', function(){
    var c = this.dataset.col;
    document.querySelectorAll('.' + c).forEach(function(el){ el.style.display = cb.checked ? '' : 'none'; });
    var s = {};
    document.querySelectorAll('.ccb').forEach(function(x){ s[x.dataset.col] = x.checked; });
    try{ localStorage.setItem('resubCols', JSON.stringify(s)); } catch(e){}
  });
});
try{
  var saved = JSON.parse(localStorage.getItem('resubCols') || '{}');
  document.querySelectorAll('.ccb').forEach(function(cb){
    if (saved.hasOwnProperty(cb.dataset.col) && !saved[cb.dataset.col]) {
      cb.checked = false; cb.dispatchEvent(new Event('change'));
    }
  });
} catch(e){}

/* ── Select all / sort / export ── */
function selAllRows(m){ document.querySelectorAll('.rcb').forEach(function(cb){ cb.checked = m.checked; }); }
var _sortCol = -1, _sortAsc = true;
function srt(col){
  _sortAsc = (_sortCol === col) ? !_sortAsc : true; _sortCol = col;
  document.querySelectorAll('.sort-arr').forEach(function(e){ e.textContent = ''; });
  var ic = document.querySelector('.sort-arr[data-i="' + col + '"]'); if(ic) ic.textContent = _sortAsc ? '▲' : '▼';
  var tb = document.querySelector('#resubTable tbody');
  var rws = Array.from(tb.querySelectorAll('tr'));
  rws.sort(function(a, b){
    var ta = a.cells[col] ? a.cells[col].textContent.trim() : '';
    var tb2 = b.cells[col] ? b.cells[col].textContent.trim() : '';
    return _sortAsc ? ta.localeCompare(tb2, undefined, {numeric:true}) : tb2.localeCompare(ta, undefined, {numeric:true});
  });
  rws.forEach(function(r){ tb.appendChild(r); });
}
function exportExcel(){
  var wb = XLSX.utils.table_to_book(document.getElementById('resubTable'), {sheet:'Resubmissions'});
  XLSX.writeFile(wb, 'Resubmissions_' + new Date().toISOString().slice(0,10) + '.xlsx');
}

/* ── EDIT MODAL ── */
function openEditModal(data){
  Swal.fire({
    title: '<div style="font-size:17px;font-weight:700;color:#1e293b;text-align:left">'
         + '<i class="fas fa-redo" style="color:#f59e0b;margin-right:8px"></i>Edit Resubmission'
         + '</div>'
         + '<div style="font-size:12px;font-weight:500;color:#64748b;font-family:monospace;margin-top:6px;text-align:left;background:#f1f5f9;border-radius:6px;padding:5px 10px;display:inline-block">'
         + (data.tracking ? data.tracking : '#'+data.sid)
         + (data.title ? '<span style="color:#94a3b8;font-weight:400"> — ' + data.title + '</span>' : '')
         + '</div>',
    width: '760px',
    padding: '28px 32px',
    html: buildEditHtml(data),
    showCancelButton: true,
    confirmButtonText: '<i class="fas fa-save" style="margin-right:6px"></i> Save Changes',
    cancelButtonText: '<i class="fas fa-times" style="margin-right:4px"></i> Cancel',
    confirmButtonColor: '#2563eb',
    cancelButtonColor: '#6b7280',
    focusConfirm: false,
    customClass: { popup: 'text-left' },
    preConfirm: function(){ return doSave(data); }
  }).then(function(res){
    if (res.isConfirmed && res.value !== false) {
      showToast('Resubmission updated successfully!');
      setTimeout(function(){ location.reload(); }, 900);
    }
  });
}

function buildEditHtml(d){
  var stOpts = [
    ['pending','— Pending —'],
    ['approved','✓ Approved'],
    ['not_approved','✗ Not Approved'],
    ['resubmit','↻ Resubmit Again']
  ];
  var stageOpts = [
    ['draft','Draft'],
    ['submitted','Submitted'],
    ['under_review','Under Review'],
    ['accepted','Accepted'],
    ['rejected','Rejected']
  ];

  function sel(id, val, opts){
    var html = '<select id="' + id + '" style="width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:10px 12px;font-size:13px;font-family:Roboto,sans-serif;outline:none;background:#fff;appearance:none;cursor:pointer;color:#1e293b;transition:border-color .15s" '
             + 'onfocus="this.style.borderColor=\'#2563eb\'" onblur="this.style.borderColor=\'#d1d5db\'">';
    opts.forEach(function(o){
      html += '<option value="' + o[0] + '"' + (val === o[0] ? ' selected' : '') + '>' + o[1] + '</option>';
    });
    html += '</select>';
    return html;
  }

  var inpStyle = 'width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:10px 12px;font-size:13px;font-family:Roboto,sans-serif;outline:none;box-sizing:border-box;transition:border-color .15s;color:#1e293b';
  var lblStyle = 'display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px';
  var rowStyle = 'display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px';
  var secStyle = 'background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:16px;margin-bottom:16px';
  var secTitleStyle = 'font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;display:flex;align-items:center;gap:6px';

  return `
  <div style="text-align:left;font-family:'Roboto',sans-serif;max-height:70vh;overflow-y:auto;padding-right:4px">

    <div style="${secStyle}">
      <div style="${secTitleStyle}"><i class="fas fa-layer-group" style="color:#f59e0b"></i> Submission Status & Publication</div>
      <div style="${rowStyle}">
        <div>
          <label style="${lblStyle}">📋 Submission Stage</label>
          ${sel('ef_stage', d.stage, stageOpts)}
        </div>
        <div>
          <label style="${lblStyle}">📅 Publication Date</label>
          <input id="ef_pub" type="date" style="${inpStyle}" value="${d.pub_date||''}"
            onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
        </div>
      </div>
    </div>

    <div style="${secStyle}">
      <div style="${secTitleStyle}"><i class="fas fa-check-circle" style="color:#059669"></i> Verification Status</div>
      <div style="${rowStyle}">
        <div>
          <label style="${lblStyle}">📄 Declaration Status</label>
          ${sel('ef_decl_st', d.decl_st, stOpts)}
        </div>
        <div>
          <label style="${lblStyle}">💰 Payment Proof Status</label>
          ${sel('ef_pay_st', d.pay_st, stOpts)}
        </div>
      </div>
    </div>

    <div style="${secStyle}">
      <div style="${secTitleStyle}"><i class="fas fa-comment-alt" style="color:#7c3aed"></i> Admin Comment</div>
      <textarea id="ef_comment" style="${inpStyle};resize:vertical;min-height:70px"
        onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'"
        placeholder="Internal note (not visible to author)…">${d.comment||''}</textarea>
    </div>

    <div style="${secStyle}">
      <div style="${secTitleStyle}"><i class="fas fa-folder-open" style="color:#d97706"></i> Resubmission File Path
        <span style="font-weight:400;color:#94a3b8;text-transform:none;letter-spacing:0;font-size:11px">(leave blank to remove)</span>
      </div>
      <div>
        <label style="${lblStyle}">🔄 Resubmission File</label>
        <input id="ef_resub" type="text" style="${inpStyle};font-family:monospace;font-size:12px"
          value="${d.resub_path}"
          placeholder="uploads/final_submissions/41/filename.docx"
          onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
      </div>
    </div>

  </div>`;
}

async function doSave(data){
  var fd = new FormData();
  fd.append('action',                    'save_edit');
  fd.append('submission_id',             data.sid);
  fd.append('publication_date',          document.getElementById('ef_pub').value);
  fd.append('author_declaration_status', document.getElementById('ef_decl_st').value);
  fd.append('payment_proof_status',      document.getElementById('ef_pay_st').value);
  fd.append('admin_comment',             document.getElementById('ef_comment').value);
  fd.append('resub_path',                document.getElementById('ef_resub').value.trim());
  fd.append('stage',                     document.getElementById('ef_stage').value);
  fd.append('resub_was_set',             data.resub_was || 0);

  try {
    var r = await fetch(window.location.pathname, {method:'POST', body:fd});
    var d = await r.json();
    if (!d.success){ Swal.showValidationMessage('❌ ' + (d.message || 'Save failed')); return false; }
    return true;
  } catch(e) {
    Swal.showValidationMessage('❌ Network error'); return false;
  }
}

/* ── Send Email ── */
function sendEmail(umi, email){
  Swal.fire({
    title: 'Send Email to Author',
    html: '<div style="text-align:left">'
        + '<label style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase">To</label>'
        + '<input id="e_to" class="swal2-input" value="' + email + '">'
        + '<label style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-top:8px;display:block">Subject</label>'
        + '<input id="e_sub" class="swal2-input" value="Resubmission Received | ' + umi + '">'
        + '<label style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-top:8px;display:block">Message</label>'
        + '<textarea id="e_msg" class="swal2-textarea" style="height:90px">Dear Author,\n\nWe have received your resubmission (' + umi + ') and it is currently under review. We will notify you of our decision shortly.\n\nRegards,\nEditorial Office\nCommuneglobal</textarea>'
        + '</div>',
    showCancelButton: true,
    confirmButtonText: 'Send',
    preConfirm: function(){
      var fd = new FormData();
      fd.append('to',      document.getElementById('e_to').value);
      fd.append('subject', document.getElementById('e_sub').value);
      fd.append('message', document.getElementById('e_msg').value);
      fd.append('tracking_code', umi);
      return fetch('ajax/send_final_email.php', {method:'POST', body:fd})
        .then(function(r){ return r.json(); })
        .then(function(d){ if(!d.success) throw new Error(d.message||'Failed'); return d; });
    }
  }).then(function(){ Swal.fire('Sent!','Email sent successfully.','success'); })
    .catch(function(err){ if(err && err.message) Swal.fire('Error', err.message, 'error'); });
}
</script>
</body>
</html>