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

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

if (!function_exists('str_starts_with')) {
    function str_starts_with($h, $n) { return strpos($h, $n) === 0; }
}

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']        ?? '');

        $payPath   = trim($_POST['pay_path']   ?? '');
        $declPath  = trim($_POST['decl_path']  ?? '');
        $fmPath    = trim($_POST['fm_path']    ?? '');
        $resubPath = trim($_POST['resub_path'] ?? '');
        $bankSt    = trim($_POST['bank_status'] ?? '');

        $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 {
            $errors = [];

            // Helper: upsert a file record
            $upsertFile = function($fileType, $path) use ($pdo, $sid, &$errors,
                $pub_date, $decl_st, $pay_st, $comment) {
                if ($path === '') {
                    // remove record
                    $pdo->prepare("DELETE FROM submission_files WHERE submission_id=? AND file_type=?")
                        ->execute([$sid, $fileType]);
                    return;
                }
                $chk = $pdo->prepare("SELECT file_id FROM submission_files WHERE submission_id=? AND file_type=?");
                $chk->execute([$sid, $fileType]);
                $row = $chk->fetch();
                if ($row) {
                    $pdo->prepare(
                        "UPDATE submission_files
                         SET stored_path=?, original_name=?,
                             publication_date=?,
                             author_declaration_status=?,
                             payment_proof_status=?,
                             admin_comment=?,
                             uploaded_at=uploaded_at
                         WHERE submission_id=? AND file_type=?"
                    )->execute([
                        $path, basename($path),
                        $pub_date ?: null,
                        $decl_st, $pay_st, $comment,
                        $sid, $fileType
                    ]);
                } 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, $fileType, basename($path), $path,
                        $pub_date ?: null,
                        $decl_st, $pay_st, $comment
                    ]);
                }
            };

            // Update each file type
            if ($payPath !== '' || !empty($_POST['pay_was_set'])) $upsertFile('payment_receipt', $payPath);
            if ($declPath !== '' || !empty($_POST['decl_was_set'])) $upsertFile('declaration_form', $declPath);
            if ($fmPath !== '' || !empty($_POST['fm_was_set'])) $upsertFile('final_manuscript_revised', $fmPath);
            if ($resubPath !== '' || !empty($_POST['resub_was_set'])) $upsertFile('resubmission', $resubPath);

            // Also update pub_date / status / comment on ALL existing 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 IN ('payment_receipt','declaration_form','final_manuscript_revised','resubmission')"
            )->execute([$pub_date ?: null, $decl_st, $pay_st, $comment, $sid]);

            // Update bank payment status
            if ($bankSt !== '') {
                $allowed = ['PENDING_VERIFICATION','COMPLETED','FAILED'];
                if (in_array($bankSt, $allowed)) {
                    $pdo->prepare(
                        "UPDATE payments SET status=?, updated_at=NOW()
                         WHERE submission_id=? AND gateway='bank'
                         ORDER BY created_at DESC LIMIT 1"
                    )->execute([$bankSt, $sid]);
                }
            }

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

    // ── Quick verify bank payment ───────────────────────────────────────────
    if ($action === 'verify_bank') {
        $sid    = (int)($_POST['submission_id'] ?? 0);
        $status = $_POST['status'] ?? 'COMPLETED';
        if (!$sid) { echo json_encode(['success'=>false,'message'=>'Invalid']); exit; }
        try {
            $pdo->prepare(
                "UPDATE payments SET status=?, updated_at=NOW()
                 WHERE submission_id=? AND gateway='bank'
                 ORDER BY created_at DESC LIMIT 1"
            )->execute([$status, $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'] ?? '');
$type_f    = trim($_GET['file_type']  ?? '');

$where  = ["sf.file_type IN ('payment_receipt','declaration_form','final_manuscript_revised','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; }
$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,

            /* payment_receipt */
            pr.stored_path                  AS payment_receipt_path,
            pr.original_name                AS payment_receipt_name,
            pr.uploaded_at                  AS payment_receipt_date,
            pr.publication_date             AS pub_date,
            pr.author_declaration_status    AS author_decl_status,
            pr.payment_proof_status         AS payment_proof_status,
            pr.admin_comment                AS admin_comment,

            /* declaration_form */
            df.stored_path   AS declaration_form_path,
            df.original_name AS declaration_form_name,
            df.uploaded_at   AS declaration_form_date,

            /* final_manuscript_revised */
            fm.stored_path   AS final_manuscript_path,
            fm.original_name AS final_manuscript_name,
            fm.uploaded_at   AS final_manuscript_date,

            /* resubmission */
            rs.stored_path   AS resubmission_path,
            rs.original_name AS resubmission_name,
            rs.uploaded_at   AS resubmission_date,

            /* payments — FIXED: pay_count only counts non-bank (online) COMPLETED payments */
            COALESCE(pp.pay_count,0) AS sys_pay_count,
            pp.total_paid            AS sys_total_paid,
            pp.last_currency         AS sys_currency,
            pp.bank_status           AS bank_status,
            pp.bank_ref              AS bank_ref,

            MIN(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.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='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'
        ) pr ON pr.submission_id = s.submission_id

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

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

        LEFT JOIN (
            SELECT f1.submission_id, f1.stored_path, f1.original_name, f1.uploaded_at
            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 submission_id,
                   /* FIX: only count online gateway (non-bank) COMPLETED payments as sys_pay_count */
                   COUNT(CASE WHEN status='COMPLETED' AND gateway != 'bank' THEN 1 END)                    AS pay_count,
                   SUM(CASE WHEN status='COMPLETED' AND gateway != 'bank' THEN amount ELSE 0 END)           AS total_paid,
                   MAX(CASE WHEN status='COMPLETED' AND gateway != 'bank' THEN currency END)                AS last_currency,
                   MAX(CASE WHEN gateway='bank' THEN status END)                                            AS bank_status,
                   MAX(CASE WHEN gateway='bank' THEN gateway_order_id END)                                  AS bank_ref
            FROM payments GROUP BY submission_id
        ) pp ON pp.submission_id = s.submission_id

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

// ── Stats ──────────────────────────────────────────────────────────────────
$stats = ['total'=>0,'has_payment'=>0,'has_declaration'=>0,'has_final_ms'=>0,'has_resubmission'=>0];
try {
    $sr = $pdo->query("
        SELECT COUNT(DISTINCT submission_id) AS total,
               COUNT(DISTINCT CASE WHEN file_type='payment_receipt'          THEN submission_id END) AS has_payment,
               COUNT(DISTINCT CASE WHEN file_type='declaration_form'         THEN submission_id END) AS has_declaration,
               COUNT(DISTINCT CASE WHEN file_type='final_manuscript_revised' THEN submission_id END) AS has_final_ms,
               COUNT(DISTINCT CASE WHEN file_type='resubmission'             THEN submission_id END) AS has_resubmission
        FROM submission_files
        WHERE file_type IN ('payment_receipt','declaration_form','final_manuscript_revised','resubmission')
    ")->fetch(PDO::FETCH_ASSOC);
    if ($sr) $stats = $sr;
} catch (PDOException $e) {}

$allDoneCount = 0;
foreach ($rows as $r) {
    $payOk = !empty($r['payment_receipt_path']) || (int)$r['sys_pay_count'] > 0;
    if ($payOk && !empty($r['declaration_form_path']) && !empty($r['final_manuscript_path'])) $allDoneCount++;
}

// ── PHP-side filter ────────────────────────────────────────────────────────
$displayRows = $rows;
if ($type_f === 'complete') {
    $displayRows = array_values(array_filter($rows, function($r){
        return (!empty($r['payment_receipt_path'])||(int)$r['sys_pay_count']>0)
            && !empty($r['declaration_form_path']) && !empty($r['final_manuscript_path']);
    }));
} elseif ($type_f === 'bank_pending') {
    $displayRows = array_values(array_filter($rows,
        fn($r) => !empty($r['payment_receipt_path']) && (int)$r['sys_pay_count']===0
                  && ($r['bank_status']??'') === 'PENDING_VERIFICATION'));
} elseif ($type_f === 'missing_payment') {
    $displayRows = array_values(array_filter($rows,
        fn($r) => empty($r['payment_receipt_path']) && (int)$r['sys_pay_count']===0));
} elseif ($type_f === 'missing_decl') {
    $displayRows = array_values(array_filter($rows, fn($r) => empty($r['declaration_form_path'])));
} elseif ($type_f === 'missing_final') {
    $displayRows = array_values(array_filter($rows, fn($r) => empty($r['final_manuscript_path'])));
}

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

// ── Helpers ────────────────────────────────────────────────────────────────
function statusBadge($s) {
    $map = [
        'pending'      => ['bg-gray-100 text-gray-500',   '—'],
        '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 = 'final_submissions';
$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>Final Submissions — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<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 { 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; }
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; }
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}

.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; }

.compact-table td,.compact-table th { padding-top:4px !important; padding-bottom:4px !important; vertical-align:middle !important; }
.row-done td { background:#f0fdf4 !important; }
body.dark .row-done td { background:#052e16 !important; }
.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; }
.badge-pill { display:inline-flex; align-items:center; padding:2px 8px; border-radius:9999px; font-size:11px; font-weight:600; }

.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; }

/* Edit modal */
.ef-label { display:block; font-size:11px; font-weight:700; color:#374151; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.ef-input  { width:100%; border:1.5px solid #d1d5db; border-radius:8px; padding:8px 10px; font-size:12.5px; font-family:'Roboto',sans-serif; outline:none; transition:border-color .15s; }
.ef-input:focus { border-color:#2563eb; }
.ef-select { width:100%; border:1.5px solid #d1d5db; border-radius:8px; padding:8px 10px; font-size:12.5px; font-family:'Roboto',sans-serif; outline:none; background:#fff; transition:border-color .15s; }
.ef-select:focus { border-color:#2563eb; }
.ef-section { background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; padding:14px; margin-bottom:10px; }
.ef-section-title { font-size:11px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:.5px; margin-bottom:10px; display:flex; align-items:center; gap:5px; }
</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">
        <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-flag-checkered text-green-600"></i> Final Submissions
        </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-6 gap-3 mb-5">
      <?php $sc = [
        ['Total',       (int)$stats['total'],            'text-blue-600',   'bg-blue-50',    'fa-layer-group'],
        ['Payment',     (int)$stats['has_payment'],      'text-green-600',  'bg-green-50',   'fa-receipt'],
        ['Declaration', (int)$stats['has_declaration'],  'text-purple-600', 'bg-purple-50',  'fa-file-signature'],
        ['Final MS',    (int)$stats['has_final_ms'],     'text-amber-600',  'bg-amber-50',   'fa-file-alt'],
        ['Resubmit',    (int)$stats['has_resubmission'], 'text-cyan-600',   'bg-cyan-50',    'fa-redo'],
        ['All Done',    $allDoneCount,                   'text-emerald-600','bg-emerald-50', 'fa-check-double'],
      ]; 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> Filters
      </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="UMI / 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">File Status</label>
          <select name="file_type" class="w-full border border-gray-300 rounded-lg p-2 text-sm">
            <option value="">All</option>
            <option value="complete"        <?= $type_f==='complete'?'selected':''        ?>>All 3 files done</option>
            <option value="bank_pending"    <?= $type_f==='bank_pending'?'selected':''    ?>>Bank slip pending</option>
            <option value="missing_payment" <?= $type_f==='missing_payment'?'selected':'' ?>>Missing payment</option>
            <option value="missing_decl"    <?= $type_f==='missing_decl'?'selected':''    ?>>Missing declaration</option>
            <option value="missing_final"   <?= $type_f==='missing_final'?'selected':''   ?>>Missing final MS</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="final_submissions.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-umi'  => 'UMI ID',  'col-email' => 'Email',   'col-jnl'  => 'Journal',
          'col-date' => 'Created', 'col-cty'   => 'Country',
          'col-fm'   => 'Final MS','col-decl'  => 'Decl.',   'col-pay'  => 'Payment',
          'col-adv'  => 'Decl. Verify', 'col-pv' => 'Pay Verify',
          'col-cmt'  => '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-flag-checkered text-green-600"></i> Final Submissions
          </h2>
          <span class="bg-blue-100 text-blue-700 text-xs font-bold px-2 py-0.5 rounded-full">
            <?= count($displayRows) ?>
          </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
        </button>
      </div>

      <?php if (empty($displayRows)): ?>
      <div class="text-center py-16 text-gray-400">
        <i class="fas fa-inbox text-4xl mb-3 block"></i>
        <p class="text-sm">No records match the current filters.</p>
      </div>
      <?php else: ?>

      <div style="overflow-x:auto; max-height:calc(100vh - 380px)">
      <table class="w-full text-sm text-left text-gray-700 compact-table" id="fsTable">
        <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-umi cursor-pointer"  onclick="srt(1)">UMI ID <span class="sort-arr" data-i="1"></span></th>
          <th class="px-3 py-2 col-email cursor-pointer" onclick="srt(2)">Email <span class="sort-arr" data-i="2"></span></th>
          <th class="px-3 py-2 col-jnl">Journal</th>
          <th class="px-3 py-2 col-pub cursor-pointer" onclick="srt(11)">
              Pub. Date <span class="sort-arr" data-i="11"></span>
          </th>
          <th class="px-3 py-2 col-date cursor-pointer" onclick="srt(4)">Created <span class="sort-arr" data-i="4"></span></th>
          <th class="px-3 py-2 col-cty">Country</th>
          <th class="px-3 py-2 col-fm">Final MS</th>
          <th class="px-3 py-2 col-decl">Decl.</th>
          <th class="px-3 py-2 col-pay">Payment</th>
          <th class="px-3 py-2 col-adv text-center">Decl. Verify</th>
          <th class="px-3 py-2 col-pv text-center">Pay Verify</th>
          <th class="px-3 py-2 col-cmt">Comment</th>
          <th class="px-3 py-2 col-act text-center">Actions</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($displayRows as $r):
          $sid      = (int)$r['submission_id'];
          $hasPay   = !empty($r['payment_receipt_path']);
          $hasDecl  = !empty($r['declaration_form_path']);
          $hasFm    = !empty($r['final_manuscript_path']);
          $hasResub = !empty($r['resubmission_path']);
          $sysPaid  = (int)$r['sys_pay_count'] > 0;   // only online (non-bank) payments
          $payOk    = $hasPay || $sysPaid;
          $allDone  = $payOk && $hasDecl && $hasFm;

          // FIX: bank verified = bank payment marked COMPLETED by admin
          $bankVerified = !$sysPaid && ($r['bank_status'] ?? '') === 'COMPLETED';
          $bankPend     = !$sysPaid && $hasPay && ($r['bank_status'] ?? '') === 'PENDING_VERIFICATION';

          $sStatus  = $r['submission_status'] ?? 'draft';

          $declSt   = $r['author_decl_status']    ?? 'pending';
          $paySt    = $r['payment_proof_status']   ?? 'pending';
          $pubDate  = $r['pub_date']               ?? '';
          $comment  = $r['admin_comment']          ?? '';

          $js = fn($v) => htmlspecialchars(addslashes((string)($v??'')), ENT_QUOTES);

          $payUrl   = htmlspecialchars(fsFileUrl($r['payment_receipt_path']),  ENT_QUOTES);
          $declUrl  = htmlspecialchars(fsFileUrl($r['declaration_form_path']),  ENT_QUOTES);
          $fmUrl    = htmlspecialchars(fsFileUrl($r['final_manuscript_path']),  ENT_QUOTES);
          $resubUrl = htmlspecialchars(fsFileUrl($r['resubmission_path']),      ENT_QUOTES);
        ?>
        <tr class="border-b hover:bg-gray-50 transition <?= $allDone ? 'row-done' : '' ?>"
            id="row-<?= $sid ?>">

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

          <!-- UMI -->
          <td class="px-3 py-2 col-umi">
            <?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>
            <?php else: ?><span class="text-gray-400 text-xs">#<?= $sid ?></span><?php endif; ?>
            <div class="mt-0.5">
              <span class="sbadge sb-<?= htmlspecialchars($sStatus) ?>" style="font-size:10px">
                <?= ucfirst(str_replace('_',' ',$sStatus)) ?>
              </span>
            </div>
          </td>

          <!-- Email -->
          <td class="px-3 py-2 col-email">
            <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-jnl text-xs text-gray-600">
            <?= htmlspecialchars($r['journal_name'] ?? '—') ?>
          </td>
          
          <td class="px-3 py-2 col-pub text-xs text-gray-500 whitespace-nowrap">
              <?= $pubDate ? htmlspecialchars(substr($pubDate, 0, 10)) : '<span class="text-gray-300">—</span>' ?>
            </td>

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

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

          <!-- Final MS -->
          <td class="px-3 py-2 col-fm">
            <?php if ($hasFm): ?>
            <a href="<?= $fmUrl ?>" target="_blank" class="file-link">
              <i class="fas fa-file-word text-blue-500"></i> View
            </a>
            <div class="text-xs text-gray-400"><?= htmlspecialchars(substr((string)$r['final_manuscript_date'],0,10)) ?></div>
            <?php else: ?><span class="text-gray-300 text-xs">—</span><?php endif; ?>
          </td>

          <!-- Declaration -->
          <td class="px-3 py-2 col-decl">
            <?php if ($hasDecl): ?>
            <a href="<?= $declUrl ?>" target="_blank" class="file-link">
              <i class="fas fa-file-signature text-purple-500"></i> View
            </a>
            <div class="text-xs text-gray-400"><?= htmlspecialchars(substr((string)$r['declaration_form_date'],0,10)) ?></div>
            <?php else: ?><span class="text-gray-300 text-xs">—</span><?php endif; ?>
          </td>

          <!-- Payment -->
          <td class="px-3 py-2 col-pay">
            <?php if ($sysPaid && !$hasPay): ?>
              <span class="badge-pill bg-green-100 text-green-700">✓ Online</span>
              <?php if ($r['sys_total_paid']): ?>
              <div class="text-xs text-gray-400"><?= $r['sys_currency']==='USD'?'$':'₹' ?><?= number_format((float)$r['sys_total_paid'],0) ?></div>
              <?php endif; ?>
            <?php elseif ($hasPay): ?>
              <a href="<?= $payUrl ?>" target="_blank" class="file-link">
                <i class="fas fa-receipt text-teal-600"></i> View
              </a>
              <?php if ($bankPend): ?>
              <div class="mt-0.5 flex items-center gap-1 flex-wrap">
                <span class="badge-pill bg-amber-100 text-amber-700">⏳ Pending</span>
                <?php if ($r['bank_ref']): ?>
                <span class="text-xs text-gray-400 font-mono"><?= htmlspecialchars($r['bank_ref']) ?></span>
                <?php endif; ?>
              </div>
              <?php endif; ?>
            <?php else: ?><span class="text-gray-300 text-xs">—</span><?php endif; ?>
          </td>

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

          <!-- Pay Verify — FIXED logic -->
          <td class="px-3 py-2 col-pv text-center">
            <?php if ($sysPaid): ?>
              <!-- Online payment via Razorpay / Stripe / PayPal etc. -->
              <span class="badge-pill bg-emerald-100 text-emerald-700 border border-emerald-200 font-bold">
                System ✓
              </span>
            <?php elseif ($bankVerified): ?>
              <!-- Bank slip uploaded AND admin manually verified it as COMPLETED -->
              <span class="badge-pill bg-blue-100 text-blue-700 border border-blue-200 font-bold">
                ✓ Manual
              </span>
            <?php elseif ($bankPend): ?>
              <!-- Bank slip uploaded but not yet verified -->
              <button onclick="quickVerify(<?= $sid ?>)"
                      class="badge-pill bg-amber-100 text-amber-700 border border-amber-300 cursor-pointer hover:bg-amber-200">
                ⏳ Verify?
              </button>
            <?php else: ?>
              <?= statusBadge($paySt) ?>
            <?php endif; ?>
          </td>

          <!-- Comment -->
          <td class="px-3 py-2 col-cmt 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">
            <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,
              "pay_path"   => $r['payment_receipt_path']  ?? '',
              "decl_path"  => $r['declaration_form_path'] ?? '',
              "fm_path"    => $r['final_manuscript_path'] ?? '',
              "resub_path" => $r['resubmission_path']     ?? '',
              "bank_st"    => $r['bank_status']           ?? '',
              "bank_ref"   => $r['bank_ref']              ?? '',
              "pay_was"    => $hasPay  ? 1 : 0,
              "decl_was"   => $hasDecl ? 1 : 0,
              "fm_was"     => $hasFm   ? 1 : 0,
              "resub_was"  => $hasResub? 1 : 0,
            ]) ?>)'
              title="Edit" class="text-yellow-500 hover:text-yellow-600 text-base mx-0.5">
              <i class="fas fa-edit"></i>
            </button>
            <a href="submission_view.php?id=<?= $sid ?>" title="View" class="text-blue-500 hover:text-blue-700 text-base mx-0.5">
              <i class="fas fa-eye"></i>
            </a>
            <button onclick="sendEmail('<?= $js($r['tracking_code']) ?>','<?= $js($r['author_email']) ?>')"
                    title="Email" class="text-indigo-500 hover:text-indigo-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($displayRows) ?> record(s) &middot; Green rows = all 3 files present
      </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);
}

/* ── column toggles ── */
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('fsCols8',JSON.stringify(s));}catch(e){}
  });
});
try{
  var saved=JSON.parse(localStorage.getItem('fsCols8')||'{}');
  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('#fsTable 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('fsTable'),{sheet:'Final Submissions'});
  XLSX.writeFile(wb,'Final_Submissions_'+new Date().toISOString().slice(0,10)+'.xlsx');
}

/* ── Quick verify bank payment ── */
function quickVerify(sid){
  Swal.fire({
    title:'Verify Bank Payment?',
    text:'Mark this bank transfer as COMPLETED / Verified?',
    icon:'question',
    showCancelButton:true,
    confirmButtonText:'✓ Approve',
    confirmButtonColor:'#059669',
  }).then(function(res){
    if(!res.isConfirmed)return;
    var fd=new FormData(); fd.append('action','verify_bank'); fd.append('submission_id',sid); fd.append('status','COMPLETED');
    fetch(window.location.pathname,{method:'POST',body:fd})
      .then(function(r){return r.json();})
      .then(function(d){
        if(d.success){showToast('Payment verified!');setTimeout(function(){location.reload();},900);}
        else showToast('Error: '+(d.message||'Failed'),'e');
      }).catch(function(){showToast('Network error','e');});
  });
}

/* ── 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-edit" style="color:#2563eb;margin-right:8px"></i>Edit Final Submission'
         + '</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: '860px',
    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('Submission updated successfully!');
      setTimeout(function(){ location.reload(); }, 900);
    }
  });
}

function buildEditHtml(d){
  function sel(id, val, opts, icon){
    var html = '<div style="position:relative">'
             + '<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>'
          + '<div style="position:absolute;right:12px;top:50%;transform:translateY(-50%);pointer-events:none;color:#94a3b8;font-size:12px">▼</div>'
          + '</div>';
    return html;
  }

  var stOpts   = [['pending','— Pending —'],['approved','✓ Approved'],['not_approved','✗ Not Approved'],['resubmit','↻ Resubmit']];
  var bankOpts = [['','— No change —'],['PENDING_VERIFICATION','⏳ Pending Verification'],['COMPLETED','✓ Completed / Verified'],['FAILED','✗ Failed / Rejected']];

  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:72vh;overflow-y:auto;padding-right:4px">

    <!-- ── Section 1: Publication & Bank ── -->
    <div style="${secStyle}">
      <div style="${secTitleStyle}">
        <i class="fas fa-calendar-check" style="color:#2563eb"></i> Publication & Payment
      </div>
      <div style="${rowStyle}">
        <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>
          <label style="${lblStyle}">🏦 Bank Payment Status</label>
          ${sel('ef_bank', d.bank_st, bankOpts)}
          ${d.bank_ref ? '<div style="font-size:11px;color:#64748b;margin-top:4px">Ref No: <code style="background:#f1f5f9;padding:1px 5px;border-radius:4px">'+d.bank_ref+'</code></div>' : ''}
        </div>
      </div>
    </div>

    <!-- ── Section 2: Verification Statuses ── -->
    <div style="${secStyle}">
      <div style="${secTitleStyle}">
        <i class="fas fa-check-circle" style="color:#059669"></i> Verification Statuses
      </div>
      <div style="${rowStyle}">
        <div>
          <label style="${lblStyle}">📄 Author 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>

    <!-- ── Section 3: Admin Comment ── -->
    <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>

    <!-- ── Section 4: File Paths ── -->
    <div style="${secStyle}">
      <div style="${secTitleStyle}">
        <i class="fas fa-folder-open" style="color:#d97706"></i> File Paths
        <span style="font-weight:400;color:#94a3b8;text-transform:none;letter-spacing:0;font-size:11px">(leave blank to remove a file)</span>
      </div>

      <div style="margin-bottom:10px">
        <label style="${lblStyle}">💰 Payment Receipt</label>
        <input id="ef_pay" type="text"
          style="${inpStyle};font-family:monospace;font-size:12px"
          value="${d.pay_path}"
          placeholder="uploads/final_submissions/41/filename.jpg"
          onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
      </div>

      <div style="margin-bottom:10px">
        <label style="${lblStyle}">📄 Author Declaration</label>
        <input id="ef_decl" type="text"
          style="${inpStyle};font-family:monospace;font-size:12px"
          value="${d.decl_path}"
          placeholder="uploads/final_submissions/41/filename.docx"
          onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
      </div>

      <div style="margin-bottom:10px">
        <label style="${lblStyle}">📤 Final Manuscript</label>
        <input id="ef_fm" type="text"
          style="${inpStyle};font-family:monospace;font-size:12px"
          value="${d.fm_path}"
          placeholder="uploads/final_submissions/41/filename.docx"
          onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
      </div>

      <div>
        <label style="${lblStyle}">🔄 Resubmission</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('pay_path',                  document.getElementById('ef_pay').value.trim());
  fd.append('decl_path',                 document.getElementById('ef_decl').value.trim());
  fd.append('fm_path',                   document.getElementById('ef_fm').value.trim());
  fd.append('resub_path',                document.getElementById('ef_resub').value.trim());
  fd.append('bank_status',               document.getElementById('ef_bank').value);
  // flags so server knows the original had a file (to handle blank = delete)
  fd.append('pay_was_set',   data.pay_was   || 0);
  fd.append('decl_was_set',  data.decl_was  || 0);
  fd.append('fm_was_set',    data.fm_was    || 0);
  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',
    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="Final Submission | '+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 final documents ('+umi+'). Your article is being processed.\n\nRegards,\nEditorial Office</textarea>'
        +'</div>',
    showCancelButton:true, confirmButtonText:'Send',
    preConfirm:function(){
      var fd=new FormData();
      fd.append('tracking_code',umi);
      fd.append('to',document.getElementById('e_to').value);
      fd.append('subject',document.getElementById('e_sub').value);
      fd.append('message',document.getElementById('e_msg').value);
      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!','','success');})
    .catch(function(err){if(err&&err.message)Swal.fire('Error',err.message,'error');});
}
</script>
</body>
</html>