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

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/') === 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 publication details ───────────────────────────────────────────
    if ($action === 'save_publication') {
        $sid       = (int)($_POST['submission_id'] ?? 0);
        $doi       = trim($_POST['doi']            ?? '');
        $pub_date  = trim($_POST['publication_date'] ?? '');
        $page_no   = trim($_POST['page_no']        ?? '');
        $reference = trim($_POST['reference']      ?? '');
        $pdf_path  = trim($_POST['published_pdf_path'] ?? '');
        $vol_id    = (int)($_POST['volume_id']     ?? 0);

        // Sanitize slug: lowercase, only a-z, 0-9, hyphens, max 100 chars
        $raw_slug  = trim($_POST['article_slug']   ?? '');
        $slug      = strtolower($raw_slug);
        $slug      = preg_replace('/[^a-z0-9\-]/', '', str_replace(' ', '-', $slug));
        $slug      = preg_replace('/-+/', '-', trim($slug, '-'));
        $slug      = substr($slug, 0, 100);

        if (!$sid) { echo json_encode(['success'=>false,'message'=>'Invalid submission']); exit; }

        try {
            // Check if a published record already exists
            $chk = $pdo->prepare(
                "SELECT file_id FROM submission_files
                 WHERE submission_id=? AND file_type='payment_receipt'
                 ORDER BY uploaded_at DESC LIMIT 1"
            );
            $chk->execute([$sid]);
            $file = $chk->fetch();

            if ($file) {
                $pdo->prepare(
                    "UPDATE submission_files
                     SET publication_date=?,
                         doi=?,
                         page_no=?,
                         reference=?,
                         published_pdf_path=?,
                         volume_id=?,
                         article_slug=?
                     WHERE submission_id=?
                       AND file_type IN ('payment_receipt','declaration_form','final_manuscript_revised','resubmission')"
                )->execute([
                    $pub_date ?: null,
                    $doi ?: null,
                    $page_no ?: null,
                    $reference ?: null,
                    $pdf_path ?: null,
                    $vol_id ?: null,
                    $slug ?: null,
                    $sid
                ]);
            }

            $pdo->prepare(
                "UPDATE submission_files
                 SET publication_date=?,
                     doi=?,
                     page_no=?,
                     reference=?,
                     published_pdf_path=?,
                     volume_id=?,
                     article_slug=?
                 WHERE submission_id=?
                   AND file_type IN ('payment_receipt','declaration_form','final_manuscript_revised','resubmission')"
            )->execute([
                $pub_date ?: null,
                $doi ?: null,
                $page_no ?: null,
                $reference ?: null,
                $pdf_path ?: null,
                $vol_id ?: null,
                $slug ?: null,
                $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;
}

// ── Fetch published submissions ────────────────────────────────────────────
$search    = trim($_GET['q']          ?? '');
$journal_f = trim($_GET['journal_id'] ?? '');

$where  = [
    "sf.file_type IN ('payment_receipt','declaration_form','final_manuscript_revised','resubmission')",
    "sf.publication_date IS NOT NULL"
];
$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,
            s.journal_id,
            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, mi.abstract,

            pr.stored_path               AS payment_receipt_path,
            pr.publication_date          AS pub_date,
            pr.doi                       AS doi,
            pr.page_no                   AS page_no,
            pr.reference                 AS reference,
            pr.published_pdf_path        AS published_pdf_path,
            pr.volume_id                 AS volume_id,
            pr.article_slug              AS article_slug,

            fm.stored_path               AS final_manuscript_path,

            jv.volume                    AS vol_number,
            jv.issue                     AS vol_issue,
            jv.title                     AS vol_title,
            jv.year                      AS vol_year,

            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 f1.submission_id, f1.stored_path, f1.publication_date,
                   f1.doi, f1.page_no, f1.reference, f1.published_pdf_path,
                   f1.volume_id, f1.article_slug
            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
            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 journal_volumes jv ON jv.id = pr.volume_id

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

// ── Load journals & volumes ────────────────────────────────────────────────
$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){}

$volumes_list = [];
try { $volumes_list = $pdo->query("SELECT id, journal_id, volume, issue, title, year FROM journal_volumes WHERE is_active=1 ORDER BY year DESC, volume DESC, issue DESC")->fetchAll(PDO::FETCH_ASSOC); } catch(PDOException $e){}

$active_section = 'published_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>Published 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; }
.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}}

.compact-table td,.compact-table th { padding-top:5px !important; padding-bottom:5px !important; vertical-align:middle !important; }

.badge-pill { display:inline-flex; align-items:center; padding:2px 9px; border-radius:9999px; font-size:11px; font-weight:600; }

.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-accepted::before { background:#059669; } .sb-accepted { background:rgba(16,185,129,.10); color:#059669; }
.sb-submitted::before { background:#2563eb; } .sb-submitted { background:rgba(59,130,246,.10); color:#2563eb; }

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

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

.pub-badge { display:inline-flex; align-items:center; gap:5px; background:#eff6ff; border:1px solid #bfdbfe; color:#1d4ed8; padding:3px 10px; border-radius:9999px; font-size:11px; font-weight:700; }

.doi-chip { font-family:monospace; font-size:11px; background:#f1f5f9; border:1px solid #e2e8f0; color:#334155; padding:2px 8px; border-radius:6px; display:inline-block; max-width:200px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }

.slug-chip { font-family:monospace; font-size:10px; background:#f0fdf4; border:1px solid #bbf7d0; color:#166534; padding:2px 7px; border-radius:6px; display:inline-block; max-width:160px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }

.abstract-preview { font-size:11px; color:#6b7280; line-height:1.4; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; max-width:260px; }
</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-newspaper text-blue-600"></i> Published 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) ?>
      <br><small>Run migration if columns are missing:
        <code>ALTER TABLE submission_files ADD COLUMN article_slug VARCHAR(100) DEFAULT NULL;</code>
      </small>
    </div>
    <?php endif; ?>

    <!-- Info banner -->
    <div class="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-5 flex items-start gap-3">
      <i class="fas fa-info-circle text-blue-500 mt-0.5 text-lg"></i>
      <div>
        <div class="font-semibold text-blue-800 text-sm">Published Articles Management</div>
        <div class="text-blue-600 text-xs mt-0.5">
          Showing only submissions that have a <strong>publication date</strong> set. Use the edit button to assign DOI, page numbers, references, article slug, upload the final PDF, and link to a journal issue/volume.
        </div>
      </div>
    </div>

    <!-- Stats -->
    <div class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-5">
      <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100">
        <div class="w-8 h-8 bg-blue-50 rounded-lg flex items-center justify-center mb-1.5">
          <i class="fas fa-newspaper text-blue-600 text-xs"></i>
        </div>
        <div class="text-xl font-bold text-blue-600"><?= count($rows) ?></div>
        <div class="text-xs text-gray-500 font-medium">Total Published</div>
      </div>
      <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100">
        <div class="w-8 h-8 bg-green-50 rounded-lg flex items-center justify-center mb-1.5">
          <i class="fas fa-fingerprint text-green-600 text-xs"></i>
        </div>
        <div class="text-xl font-bold text-green-600">
          <?= count(array_filter($rows, fn($r) => !empty($r['doi']))) ?>
        </div>
        <div class="text-xs text-gray-500 font-medium">With DOI</div>
      </div>
      <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100">
        <div class="w-8 h-8 bg-purple-50 rounded-lg flex items-center justify-center mb-1.5">
          <i class="fas fa-file-pdf text-purple-600 text-xs"></i>
        </div>
        <div class="text-xl font-bold text-purple-600">
          <?= count(array_filter($rows, fn($r) => !empty($r['published_pdf_path']))) ?>
        </div>
        <div class="text-xs text-gray-500 font-medium">PDF Uploaded</div>
      </div>
      <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100">
        <div class="w-8 h-8 bg-amber-50 rounded-lg flex items-center justify-center mb-1.5">
          <i class="fas fa-book text-amber-600 text-xs"></i>
        </div>
        <div class="text-xl font-bold text-amber-600">
          <?= count(array_filter($rows, fn($r) => !empty($r['volume_id']))) ?>
        </div>
        <div class="text-xs text-gray-500 font-medium">Assigned to Issue</div>
      </div>
      <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100">
        <div class="w-8 h-8 bg-emerald-50 rounded-lg flex items-center justify-center mb-1.5">
          <i class="fas fa-link text-emerald-600 text-xs"></i>
        </div>
        <div class="text-xl font-bold text-emerald-600">
          <?= count(array_filter($rows, fn($r) => !empty($r['article_slug']))) ?>
        </div>
        <div class="text-xs text-gray-500 font-medium">With Slug</div>
      </div>
    </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-4 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 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="published_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>

    <!-- 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-newspaper text-blue-600"></i> Published Articles
          </h2>
          <span class="bg-blue-100 text-blue-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
        </button>
      </div>

      <?php if (empty($rows)): ?>
      <div class="text-center py-16 text-gray-400">
        <i class="fas fa-newspaper text-4xl mb-3 block opacity-30"></i>
        <p class="text-sm font-medium">No published submissions found.</p>
        <p class="text-xs mt-1">Set a publication date in <a href="final_submissions.php" class="text-blue-500 underline">Final Submissions</a> to see articles here.</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="pubTable">
        <thead class="bg-gray-50 sticky top-0 text-xs uppercase text-gray-500 border-b">
        <tr>
          <th class="px-3 py-2 cursor-pointer" onclick="srt(0)">UMI / Status <span class="sort-arr" data-i="0"></span></th>
          <th class="px-3 py-2">Author</th>
          <th class="px-3 py-2">Article Title &amp; Abstract</th>
          <th class="px-3 py-2 cursor-pointer" onclick="srt(3)">Pub. Date <span class="sort-arr" data-i="3"></span></th>
          <th class="px-3 py-2">DOI</th>
          <th class="px-3 py-2">Slug</th>
          <th class="px-3 py-2">Pages</th>
          <th class="px-3 py-2">Issue / Volume</th>
          <th class="px-3 py-2">PDF</th>
          <th class="px-3 py-2 text-center">Actions</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r):
          $sid       = (int)$r['submission_id'];
          $sStatus   = $r['submission_status'] ?? 'draft';
          $pubDate   = $r['pub_date'] ?? '';
          $doi       = $r['doi'] ?? '';
          $pageNo    = $r['page_no'] ?? '';
          $ref       = $r['reference'] ?? '';
          $pdfPath   = $r['published_pdf_path'] ?? '';
          $volId     = (int)($r['volume_id'] ?? 0);
          $title     = $r['article_title'] ?? '';
          $abstract  = $r['abstract'] ?? '';
          $artSlug   = $r['article_slug'] ?? '';

          // Volume label
          $volLabel = '';
          if ($r['vol_number']) {
              $volLabel = 'Vol.'.$r['vol_number'].' Issue '.$r['vol_issue'];
              if ($r['vol_year']) $volLabel .= ' ('.$r['vol_year'].')';
          }

          $pdfUrl = $pdfPath ? htmlspecialchars(fsFileUrl($pdfPath), ENT_QUOTES) : '';

          // Auto-generate slug from title if none saved
          $displaySlug = $artSlug ?: '';
        ?>
        <tr class="border-b hover:bg-blue-50/30 transition" id="pub-row-<?= $sid ?>">

          <!-- UMI -->
          <td class="px-3 py-2">
            <?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>

          <!-- Author -->
          <td class="px-3 py-2">
            <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>
            <?php if ($r['country']): ?>
            <div class="text-xs text-gray-400"><?= htmlspecialchars($r['country']) ?></div>
            <?php endif; ?>
          </td>

          <!-- Title & Abstract -->
          <td class="px-3 py-2" style="min-width:200px; max-width:260px">
            <?php if ($title): ?>
            <div class="text-xs font-semibold text-gray-800 leading-tight mb-1" style="display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden">
              <?= htmlspecialchars($title) ?>
            </div>
            <?php endif; ?>
            <?php if ($abstract): ?>
            <div class="abstract-preview"><?= htmlspecialchars(mb_strimwidth($abstract,0,160,'…')) ?></div>
            <?php else: ?>
            <span class="text-gray-300 text-xs italic">No abstract</span>
            <?php endif; ?>
          </td>

          <!-- Pub Date -->
          <td class="px-3 py-2 whitespace-nowrap">
            <?php if ($pubDate): ?>
            <div class="pub-badge">
              <i class="fas fa-calendar-check text-blue-500" style="font-size:10px"></i>
              <?= htmlspecialchars(date('d M Y', strtotime($pubDate))) ?>
            </div>
            <?php else: ?>
            <span class="text-gray-300 text-xs">—</span>
            <?php endif; ?>
          </td>

          <!-- DOI -->
          <td class="px-3 py-2">
            <?php if ($doi): ?>
            <a href="https://doi.org/<?= htmlspecialchars($doi) ?>" target="_blank"
               class="doi-chip" title="<?= htmlspecialchars($doi) ?>">
              <?= htmlspecialchars($doi) ?>
            </a>
            <?php else: ?>
            <span class="text-amber-400 text-xs italic">Not set</span>
            <?php endif; ?>
          </td>

          <!-- Slug -->
          <td class="px-3 py-2">
            <?php if ($displaySlug): ?>
            <a href="<?= SITE_ROOT ?>/article/<?= htmlspecialchars($displaySlug) ?>" target="_blank"
               class="slug-chip" title="<?= htmlspecialchars($displaySlug) ?>">
              /<?= htmlspecialchars($displaySlug) ?>
            </a>
            <?php else: ?>
            <span class="text-gray-300 text-xs italic">Auto</span>
            <?php endif; ?>
          </td>

          <!-- Pages -->
          <td class="px-3 py-2 text-xs text-gray-600 whitespace-nowrap">
            <?= $pageNo ? htmlspecialchars($pageNo) : '<span class="text-gray-300">—</span>' ?>
          </td>

          <!-- Issue / Volume -->
          <td class="px-3 py-2 text-xs text-gray-600">
            <?php if ($volLabel): ?>
            <span class="badge-pill bg-purple-50 text-purple-700 border border-purple-100">
              <i class="fas fa-book-open mr-1" style="font-size:9px"></i>
              <?= htmlspecialchars($volLabel) ?>
            </span>
            <?php else: ?>
            <span class="text-gray-300 text-xs">—</span>
            <?php endif; ?>
          </td>

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

          <!-- Actions -->
          <td class="px-3 py-2 text-center whitespace-nowrap">
            <button onclick='openEditModal(<?= json_encode([
              "sid"          => $sid,
              "tracking"     => $r['tracking_code'] ?? '',
              "title"        => $title,
              "abstract"     => mb_strimwidth($abstract, 0, 500, '…'),
              "pub_date"     => $pubDate,
              "doi"          => $doi,
              "page_no"      => $pageNo,
              "reference"    => $ref,
              "pdf_path"     => $pdfPath,
              "volume_id"    => $volId,
              "journal_id"   => (int)($r['journal_id'] ?? 0),
              "article_slug" => $artSlug,
            ]) ?>)'
              title="Edit Publication Details"
              class="text-blue-500 hover:text-blue-700 text-base mx-0.5 bg-transparent border-none cursor-pointer">
              <i class="fas fa-edit"></i>
            </button>
            <a href="submission_view.php?id=<?= $sid ?>" title="View Submission"
               class="text-gray-500 hover:text-gray-700 text-base mx-0.5">
              <i class="fas fa-eye"></i>
            </a>
          </td>

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

      <div class="px-4 py-2 border-t text-xs text-gray-400">
        <?= count($rows) ?> published article(s) · Only submissions with a publication date are shown here
      </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>

<?php
$volumesJson = json_encode(array_map(fn($v) => [
    'id'        => (int)$v['id'],
    'journal_id'=> (int)$v['journal_id'],
    'label'     => 'Vol.'.$v['volume'].' Issue '.$v['issue'].($v['year']?' ('.$v['year'].')':'').($v['title']?' — '.$v['title']:''),
], $volumes_list));
?>

<script>
var VOLUMES   = <?= $volumesJson ?>;
var SITE_ROOT = '<?= SITE_ROOT ?>';

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

/* ── sort ── */
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('#pubTable tbody');
  if(!tb) return;
  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);});
}

/* ── export ── */
function exportExcel(){
  var wb=XLSX.utils.table_to_book(document.getElementById('pubTable'),{sheet:'Published'});
  XLSX.writeFile(wb,'Published_Articles_'+new Date().toISOString().slice(0,10)+'.xlsx');
}

/* ── Slug helpers ── */
function toSlugJS(str){
  return (str||'').toLowerCase()
    .replace(/[^a-z0-9\s\-]/g,'')
    .trim()
    .replace(/\s+/g,'-')
    .replace(/-+/g,'-')
    .slice(0,100);
}

function onSlugEdit(){
  var val = document.getElementById('pub_slug').value;
  // Update live preview
  document.getElementById('slug_live_preview').textContent = val || 'your-slug-here';
  // Switch badge to "Edited"
  var b = document.getElementById('slug_badge');
  b.textContent = '✎ Edited';
  b.style.cssText = 'display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:3px 9px;border-radius:9999px;font-weight:700;background:#fef3c7;color:#92400e;border:1px solid #fcd34d';
}

function regenSlug(title){
  var s = toSlugJS(title);
  document.getElementById('pub_slug').value = s;
  document.getElementById('slug_live_preview').textContent = s || 'your-slug-here';
  var b = document.getElementById('slug_badge');
  b.textContent = '✓ Auto';
  b.style.cssText = 'display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:3px 9px;border-radius:9999px;font-weight:700;background:#ecfdf5;color:#065f46;border:1px solid #a7f3d0';
}

function copySlugToClipboard(){
  var val = document.getElementById('pub_slug').value;
  if(navigator.clipboard){ navigator.clipboard.writeText(val); }
  var btn = document.getElementById('slug_copy_btn');
  btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
  setTimeout(function(){ btn.innerHTML = '<i class="fas fa-copy"></i> Copy'; }, 1600);
}

/* ── EDIT MODAL ── */
function openEditModal(d){
  var volOpts = '<option value="">— Not assigned —</option>';
  VOLUMES.forEach(function(v){
    volOpts += '<option value="'+v.id+'"'+(d.volume_id===v.id?' selected':'')+'>'+v.label+'</option>';
  });

  // Determine initial slug: use saved slug or auto-generate from title
  var initSlug   = d.article_slug || toSlugJS(d.title);
  var isAutoSlug = !d.article_slug;

  var badgeStyle = isAutoSlug
    ? 'display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:3px 9px;border-radius:9999px;font-weight:700;background:#ecfdf5;color:#065f46;border:1px solid #a7f3d0'
    : 'display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:3px 9px;border-radius:9999px;font-weight:700;background:#fef3c7;color:#92400e;border:1px solid #fcd34d';
  var badgeText  = isAutoSlug ? '✓ Auto' : '✎ Edited';

  var inp = 'width:100%;border:1.5px solid #d1d5db;border-radius:8px;padding:9px 12px;font-size:13px;font-family:Roboto,sans-serif;outline:none;box-sizing:border-box;transition:border-color .15s;color:#1e293b;background:#fff';
  var lbl = 'display:block;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:5px';
  var sec = 'background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:14px;margin-bottom:14px';
  var row = 'display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px';

  var esc = function(s){return (s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');};

  Swal.fire({
    title: '<div style="font-size:16px;font-weight:700;color:#1e293b;text-align:left">'
         + '<i class="fas fa-newspaper" style="color:#2563eb;margin-right:8px"></i>Publication Details'
         + '</div>'
         + '<div style="font-size:11px;font-weight:500;color:#64748b;font-family:monospace;margin-top:4px;text-align:left;background:#f1f5f9;border-radius:6px;padding:4px 10px;display:inline-block">'
         + esc(d.tracking || '#'+d.sid)
         + '</div>',
    width: '860px',
    padding: '24px 28px',
    html: buildPubHtml(d, volOpts, inp, lbl, sec, row, initSlug, badgeStyle, badgeText, esc),
    showCancelButton: true,
    confirmButtonText: '<i class="fas fa-save" style="margin-right:6px"></i> Save',
    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 doSavePub(d); }
  }).then(function(res){
    if(res.isConfirmed && res.value !== false){
      showToast('Publication details saved!');
      setTimeout(function(){ location.reload(); }, 900);
    }
  });
}

function buildPubHtml(d, inp, lbl, sec, row, initSlug, badgeStyle, badgeText, esc){
  // Note: volOpts is already embedded via openEditModal calling buildPubHtml
  // We receive all params correctly ordered
  var volOpts     = arguments[1]; // re-map correctly
  inp             = arguments[2];
  lbl             = arguments[3];
  sec             = arguments[4];
  row             = arguments[5];
  initSlug        = arguments[6];
  badgeStyle      = arguments[7];
  badgeText       = arguments[8];
  esc             = arguments[9];

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

    <!-- Article Info (read-only) -->
    <div style="${sec}">
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;display:flex;align-items:center;gap:6px">
        <i class="fas fa-file-alt" style="color:#2563eb"></i> Article Information
      </div>
      <div style="font-size:13px;font-weight:600;color:#1e293b;margin-bottom:6px;line-height:1.4">${esc(d.title) || '<span style="color:#94a3b8;font-style:italic">No title</span>'}</div>
      <div style="font-size:12px;color:#64748b;line-height:1.6;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden">${esc(d.abstract) || '<span style="font-style:italic">No abstract available</span>'}</div>
    </div>

    <!-- Article Slug -->
    <div style="background:#eff6ff;border:1.5px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:14px">
      <div style="font-size:11px;font-weight:700;color:#1d4ed8;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;display:flex;align-items:center;gap:6px">
        <i class="fas fa-link" style="color:#2563eb"></i> Article Slug
      </div>

      <!-- URL Preview row -->
      <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px">
        <span style="font-size:11px;color:#64748b;white-space:nowrap">URL preview:</span>
        <span style="font-family:monospace;font-size:11px;color:#1d4ed8;background:#dbeafe;border-radius:5px;padding:3px 9px;word-break:break-all;flex:1;min-width:0">
          ${esc(SITE_ROOT)}/article/<strong id="slug_live_preview">${esc(initSlug)}</strong>
        </span>
        <span id="slug_badge" style="${badgeStyle}">${badgeText}</span>
      </div>

      <!-- Slug input with /article/ prefix -->
      <div style="position:relative;margin-bottom:10px">
        <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);font-size:11px;color:#94a3b8;font-family:monospace;pointer-events:none;white-space:nowrap">/article/</span>
        <input id="pub_slug" type="text"
          style="${inp};padding-left:74px;font-family:monospace;font-size:12px"
          value="${esc(initSlug)}"
          placeholder="article-slug-here"
          oninput="onSlugEdit()"
          onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
      </div>

      <!-- Buttons row -->
      <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
        <button type="button"
          onclick="regenSlug(${JSON.stringify(d.title||'')})"
          style="display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:700;color:#2563eb;background:#dbeafe;border:1px solid #93c5fd;border-radius:6px;padding:5px 11px;cursor:pointer">
          <i class="fas fa-sync-alt" style="font-size:10px"></i> Regenerate from title
        </button>
        <button type="button" id="slug_copy_btn"
          onclick="copySlugToClipboard()"
          style="display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;color:#64748b;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:6px;padding:5px 11px;cursor:pointer">
          <i class="fas fa-copy" style="font-size:10px"></i> Copy
        </button>
      </div>
      <div style="font-size:10px;color:#94a3b8;margin-top:7px">
        Lowercase letters, numbers, and hyphens only. Max 100 characters. Auto-generated from the article title — edit manually if needed.
      </div>
    </div>

    <!-- Publication Date & Volume -->
    <div style="${sec}">
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;display:flex;align-items:center;gap:6px">
        <i class="fas fa-calendar-check" style="color:#059669"></i> Publication &amp; Issue
      </div>
      <div style="${row}">
        <div>
          <label style="${lbl}">📅 Publication Date</label>
          <input id="pub_date" type="date" style="${inp}" value="${esc(d.pub_date)}"
            onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
        </div>
        <div>
          <label style="${lbl}">📖 Issue / Volume</label>
          <select id="pub_volume" style="${inp};appearance:none;cursor:pointer;background:#fff"
            onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
            ${volOpts}
          </select>
        </div>
      </div>
    </div>

    <!-- DOI & Pages -->
    <div style="${sec}">
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;display:flex;align-items:center;gap:6px">
        <i class="fas fa-fingerprint" style="color:#7c3aed"></i> Identifiers
      </div>
      <div style="${row}">
        <div>
          <label style="${lbl}">🔗 DOI</label>
          <input id="pub_doi" type="text" style="${inp};font-family:monospace;font-size:12px"
            value="${esc(d.doi)}"
            placeholder="10.47772/IJRSS.2026.001"
            onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
          <div style="font-size:10px;color:#94a3b8;margin-top:3px">Enter DOI without https://doi.org/ prefix</div>
        </div>
        <div>
          <label style="${lbl}">📄 Page Numbers</label>
          <input id="pub_page_no" type="text" style="${inp};font-family:monospace;font-size:12px"
            value="${esc(d.page_no)}"
            placeholder="e.g. 1-12 or 45-58"
            onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
        </div>
      </div>
    </div>

    <!-- Reference & PDF -->
    <div style="${sec}">
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px;display:flex;align-items:center;gap:6px">
        <i class="fas fa-quote-right" style="color:#d97706"></i> Reference &amp; PDF
      </div>
      <div style="margin-bottom:12px">
        <label style="${lbl}">📚 Full Citation / Reference</label>
        <textarea id="pub_reference" style="${inp};resize:vertical;min-height:70px"
          onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'"
          placeholder="Author(s). (Year). Title. Journal Name, Vol(Issue), pp. DOI">${esc(d.reference)}</textarea>
      </div>
      <div>
        <label style="${lbl}">📎 Published PDF File Path</label>
        <input id="pub_pdf_path" type="text" style="${inp};font-family:monospace;font-size:12px"
          value="${esc(d.pdf_path)}"
          placeholder="uploads/published/submission_38_final.pdf"
          onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#d1d5db'">
        <div style="font-size:10px;color:#94a3b8;margin-top:3px">Relative path on server or full URL to the published PDF</div>
      </div>
    </div>

  </div>`;
}

async function doSavePub(data){
  // Sanitize slug client-side before sending
  var rawSlug = (document.getElementById('pub_slug').value || '').trim();
  var slug = rawSlug.toLowerCase().replace(/[^a-z0-9\-]/g,'').replace(/-+/g,'-').replace(/^-|-$/g,'').slice(0,100);

  var fd = new FormData();
  fd.append('action',              'save_publication');
  fd.append('submission_id',       data.sid);
  fd.append('publication_date',    document.getElementById('pub_date').value);
  fd.append('doi',                 document.getElementById('pub_doi').value.trim());
  fd.append('page_no',             document.getElementById('pub_page_no').value.trim());
  fd.append('reference',           document.getElementById('pub_reference').value);
  fd.append('published_pdf_path',  document.getElementById('pub_pdf_path').value.trim());
  fd.append('volume_id',           document.getElementById('pub_volume').value);
  fd.append('article_slug',        slug);

  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;
  }
}
</script>
</body>
</html>