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

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

$flash = ['type' => '', 'msg' => ''];

// ── DDL: ensure table exists ──────────────────────────────
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `journal_volumes` (
        `id`         INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `journal_id` INT UNSIGNED NOT NULL,
        `volume`     SMALLINT UNSIGNED NOT NULL,
        `issue`      SMALLINT UNSIGNED NOT NULL,
        `title`      VARCHAR(300) DEFAULT NULL,
        `is_active`  TINYINT(1) NOT NULL DEFAULT 1,
        `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY `uq_vol_issue` (`journal_id`, `volume`, `issue`),
        INDEX `idx_journal` (`journal_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (\Exception $e) {}

// ── All active journals ───────────────────────────────────
$journals = $pdo->query("SELECT journal_id, name FROM journals WHERE is_active=1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// ── Selected journal (filter) ─────────────────────────────
// Default = first journal (CIJSS = id 6)
$defaultJournalId = 6;
if (!in_array($defaultJournalId, array_column($journals, 'journal_id'))) {
    $defaultJournalId = (int)($journals[0]['journal_id'] ?? 0);
}
$JOURNAL_ID = (int)($_GET['journal_id'] ?? $_POST['journal_id'] ?? $defaultJournalId);
if (!$JOURNAL_ID) $JOURNAL_ID = $defaultJournalId;

$selectedJournal = array_values(array_filter($journals, fn($j) => $j['journal_id'] == $JOURNAL_ID))[0] ?? $journals[0] ?? [];
$JOURNAL_NAME    = $selectedJournal['name'] ?? '';

// ── AJAX: get single record ───────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'get' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM journal_volumes WHERE id = ?");
    $stmt->execute([(int)$_GET['id']]);
    header('Content-Type: application/json');
    echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
    exit;
}

// ── Handle POST ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action     = $_POST['_action'] ?? '';
    $post_jid   = (int)($_POST['modal_journal_id'] ?? $JOURNAL_ID);
    $volume     = (int)($_POST['volume'] ?? 0);
    $issue      = (int)($_POST['issue'] ?? 0);
    $title      = trim($_POST['title'] ?? '');
    $is_active  = isset($_POST['is_active']) ? 1 : 0;

    if ($action === 'create') {
        if (!$post_jid || !$volume || !$issue) {
            $flash = ['type' => 'error', 'msg' => 'Journal, Volume and Issue are required.'];
        } else {
            try {
                $pdo->prepare("INSERT INTO journal_volumes (journal_id,volume,issue,title,is_active) VALUES (?,?,?,?,?)")
                    ->execute([$post_jid, $volume, $issue, $title ?: null, $is_active]);
                $flash = ['type' => 'success', 'msg' => "Volume $volume Issue $issue created successfully."];
                $JOURNAL_ID = $post_jid; // stay on that journal
            } catch (\Exception $e) {
                $flash = ['type' => 'error', 'msg' => 'This Volume & Issue already exists for the selected journal.'];
            }
        }
    }

    if ($action === 'update') {
        $id = (int)($_POST['record_id'] ?? 0);
        if (!$id || !$post_jid || !$volume || !$issue) {
            $flash = ['type' => 'error', 'msg' => 'All required fields missing.'];
        } else {
            try {
                $pdo->prepare("UPDATE journal_volumes SET journal_id=?,volume=?,issue=?,title=?,is_active=?,updated_at=NOW() WHERE id=?")
                    ->execute([$post_jid, $volume, $issue, $title ?: null, $is_active, $id]);
                $flash = ['type' => 'success', 'msg' => 'Updated successfully.'];
                $JOURNAL_ID = $post_jid;
            } catch (\Exception $e) {
                $flash = ['type' => 'error', 'msg' => 'This Volume & Issue already exists for the selected journal.'];
            }
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['record_id'] ?? 0);
        if ($id) {
            $pdo->prepare("DELETE FROM journal_volumes WHERE id=?")->execute([$id]);
            $flash = ['type' => 'success', 'msg' => 'Deleted successfully.'];
        }
    }

    if ($action === 'toggle') {
        $id  = (int)($_POST['record_id'] ?? 0);
        $val = (int)($_POST['val'] ?? 0);
        $pdo->prepare("UPDATE journal_volumes SET is_active=? WHERE id=?")->execute([$val, $id]);
        header('Content-Type: application/json');
        echo json_encode(['ok' => true]);
        exit;
    }
}

// ── Fetch records for selected journal ────────────────────
$records = $pdo->prepare("SELECT * FROM journal_volumes WHERE journal_id = ? ORDER BY volume DESC, issue DESC");
$records->execute([$JOURNAL_ID]);
$records = $records->fetchAll(PDO::FETCH_ASSOC);

$totalRecords = count($records);
$activeCount  = count(array_filter($records, fn($r) => $r['is_active']));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Volumes & Issues — 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">
<style>
body { font-family:'Roboto',sans-serif; margin:0; }
.tbl { width:100%; border-collapse:collapse; }
.tbl th { padding:10px 14px; text-align:left; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.6px; color:#6B7280; border-bottom:1px solid #E5E7EB; background:#F9FAFB; }
.tbl td { padding:12px 14px; border-bottom:1px solid #F3F4F6; font-size:13px; vertical-align:middle; }
.tbl tr:hover td { background:#F8FAFC; }
.modal-overlay { position:fixed; inset:0; background:rgba(15,23,42,.5); backdrop-filter:blur(4px); z-index:200; display:none; align-items:center; justify-content:center; padding:20px; }
.modal-overlay.open { display:flex; }
.modal-box { background:white; border-radius:16px; width:100%; max-width:500px; box-shadow:0 24px 80px rgba(0,0,0,.2); }
.modal-header { padding:20px 24px; border-bottom:1px solid #E5E7EB; display:flex; align-items:center; justify-content:space-between; }
.modal-body   { padding:24px; }
.modal-footer { padding:16px 24px; border-top:1px solid #E5E7EB; display:flex; justify-content:flex-end; gap:10px; }
.finput { width:100%; border:1.5px solid #D1D5DB; border-radius:8px; padding:9px 12px; font-size:13px; color:#374151; outline:none; transition:border-color .15s; font-family:'Roboto',sans-serif; box-sizing:border-box; }
.finput:focus { border-color:#3B82F6; box-shadow:0 0 0 3px rgba(59,130,246,.1); }
.flabel { font-size:12px; font-weight:600; color:#374151; margin-bottom:4px; display:block; }
.confirm-overlay { position:fixed; inset:0; background:rgba(15,23,42,.5); backdrop-filter:blur(4px); z-index:300; display:none; align-items:center; justify-content:center; }
.confirm-overlay.open { display:flex; }
.stat-card { background:white; border-radius:12px; padding:16px 20px; border:1px solid #E5E7EB; display:flex; align-items:center; gap:14px; transition:box-shadow .2s; }
.stat-card:hover { box-shadow:0 4px 16px rgba(0,0,0,.08); }
.stat-icon { width:44px; height:44px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:18px; flex-shrink:0; }
.toggle-wrap { position:relative; display:inline-flex; align-items:center; gap:8px; cursor:pointer; user-select:none; }
.toggle-input { display:none; }
.toggle-track { width:40px; height:22px; background:#D1D5DB; border-radius:999px; transition:background .2s; flex-shrink:0; }
.toggle-input:checked ~ .toggle-track { background:#2563EB; }
.toggle-thumb { position:absolute; left:3px; top:50%; transform:translateY(-50%); width:16px; height:16px; background:white; border-radius:50%; box-shadow:0 1px 3px rgba(0,0,0,.2); transition:left .2s; }
.toggle-input:checked ~ .toggle-track ~ .toggle-thumb { left:21px; }
.journal-tab { padding:8px 16px; border-radius:8px; font-size:13px; font-weight:500; cursor:pointer; border:1.5px solid #E5E7EB; background:white; color:#64748b; transition:all .15s; white-space:nowrap; }
.journal-tab:hover { border-color:#93C5FD; color:#2563EB; background:#EFF6FF; }
.journal-tab.active { border-color:#2563EB; color:#2563EB; background:#EFF6FF; font-weight:700; }
body.dark-mode { background:#0f172a; color:#e2e8f0; }
body.dark-mode .bg-white, body.dark-mode .stat-card, body.dark-mode .modal-box { background:#1e293b !important; border-color:#334155 !important; }
body.dark-mode .tbl th { background:#1e293b; color:#94a3b8; border-color:#334155; }
body.dark-mode .tbl td { border-color:#1e293b; color:#e2e8f0; }
body.dark-mode .tbl tr:hover td { background:#334155; }
body.dark-mode .finput { background:#334155 !important; color:#f1f5f9 !important; border-color:#475569 !important; }
body.dark-mode .flabel, body.dark-mode .text-gray-800 { color:#e2e8f0 !important; }
body.dark-mode .modal-header, body.dark-mode .modal-footer { border-color:#334155; }
body.dark-mode .bg-gray-50, body.dark-mode .bg-gray-100 { background:#1e293b !important; }
body.dark-mode .border-gray-100, body.dark-mode .border-gray-200 { border-color:#334155 !important; }
body.dark-mode .journal-tab { background:#1e293b; border-color:#334155; color:#94a3b8; }
body.dark-mode .journal-tab.active { background:#1e3a5f; border-color:#3b82f6; color:#93c5fd; }
</style>
</head>
<body class="bg-gray-100">

<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="rsis-page" id="mainContent">
<main class="p-6 space-y-6">

    <?php if ($flash['msg']): ?>
    <div id="flash-bar"
         class="flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium
                <?= $flash['type']==='success' ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' : 'bg-red-50 text-red-800 border border-red-200' ?>">
        <i class="fas <?= $flash['type']==='success' ? 'fa-check-circle text-emerald-500' : 'fa-exclamation-circle text-red-500' ?>"></i>
        <span><?= htmlspecialchars($flash['msg']) ?></span>
        <button onclick="this.parentElement.remove()" class="ml-auto opacity-60 hover:opacity-100"><i class="fas fa-times"></i></button>
    </div>
    <?php endif; ?>

    <!-- Page heading -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                <i class="fas fa-layer-group text-blue-600"></i> Volumes &amp; Issues
            </h1>
            <p class="text-sm text-gray-500 mt-0.5">Manage volumes and issues for each journal</p>
        </div>
        <button onclick="openCreateModal()"
                class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors">
            <i class="fas fa-plus text-xs"></i> New Issue
        </button>
    </div>

    <!-- Journal Tabs -->
    <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4">
        <div class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Select Journal</div>
        <div class="flex flex-wrap gap-2">
            <?php foreach ($journals as $j): ?>
            <a href="?journal_id=<?= $j['journal_id'] ?>"
               class="journal-tab <?= $j['journal_id'] == $JOURNAL_ID ? 'active' : '' ?>">
                <?= htmlspecialchars($j['name']) ?>
            </a>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Stats -->
    <div class="grid grid-cols-3 gap-4">
        <div class="stat-card">
            <div class="stat-icon bg-blue-50 text-blue-600"><i class="fas fa-layer-group"></i></div>
            <div><div class="text-2xl font-bold text-gray-800"><?= $totalRecords ?></div><div class="text-xs text-gray-500 font-medium">Total Issues</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-emerald-50 text-emerald-600"><i class="fas fa-check-circle"></i></div>
            <div><div class="text-2xl font-bold text-gray-800"><?= $activeCount ?></div><div class="text-xs text-gray-500 font-medium">Active</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-red-50 text-red-500"><i class="fas fa-ban"></i></div>
            <div><div class="text-2xl font-bold text-gray-800"><?= $totalRecords - $activeCount ?></div><div class="text-xs text-gray-500 font-medium">Inactive</div></div>
        </div>
    </div>

    <!-- Table Card -->
    <div class="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">

        <!-- Header -->
        <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100">
            <div>
                <h2 class="font-bold text-gray-800 flex items-center gap-2 text-sm">
                    <i class="fas fa-book text-blue-500"></i>
                    <?= htmlspecialchars($JOURNAL_NAME) ?>
                    <span class="text-xs font-medium bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full"><?= $totalRecords ?> records</span>
                </h2>
            </div>
        </div>

        <!-- Table -->
        <div class="overflow-x-auto">
            <table class="tbl">
                <thead>
                    <tr>
                        <th style="width:44px">#</th>
                        <th>Volume</th>
                        <th>Issue</th>
                        <th>Title</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th style="text-align:right">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($records)): ?>
                    <tr><td colspan="7" class="text-center py-16 text-gray-400">
                        <i class="fas fa-layer-group text-4xl mb-3 block opacity-30"></i>
                        <p class="text-sm font-medium">No issues for this journal yet.</p>
                        <button onclick="openCreateModal()" class="mt-2 text-blue-600 hover:underline text-sm font-medium">Create first issue →</button>
                    </td></tr>
                <?php else: ?>
                <?php foreach ($records as $i => $r): ?>
                <tr>
                    <td class="text-gray-400 text-xs font-medium"><?= $i+1 ?></td>
                    <td>
                        <span class="inline-flex items-center gap-1.5 bg-blue-50 text-blue-700 text-xs font-bold px-3 py-1.5 rounded-full">
                            <i class="fas fa-layer-group text-xs"></i> Volume <?= $r['volume'] ?>
                        </span>
                    </td>
                    <td>
                        <span class="inline-flex items-center gap-1.5 bg-purple-50 text-purple-700 text-xs font-bold px-3 py-1.5 rounded-full">
                            <i class="fas fa-file-alt text-xs"></i> Issue <?= $r['issue'] ?>
                        </span>
                    </td>
                    <td class="text-gray-600 text-sm">
                        <?= $r['title'] ? htmlspecialchars($r['title']) : '<span class="text-gray-300 italic text-xs">No title</span>' ?>
                    </td>
                    <td>
                        <label class="toggle-wrap" title="Toggle active/inactive">
                            <input type="checkbox" class="toggle-input" <?= $r['is_active'] ? 'checked' : '' ?>
                                   onchange="toggleActive(<?= $r['id'] ?>, this.checked ? 1 : 0)">
                            <div class="toggle-track"></div>
                            <div class="toggle-thumb"></div>
                            <span class="text-xs font-semibold <?= $r['is_active'] ? 'text-emerald-600' : 'text-gray-400' ?>">
                                <?= $r['is_active'] ? 'Active' : 'Inactive' ?>
                            </span>
                        </label>
                    </td>
                    <td class="text-xs text-gray-400"><?= date('d M Y', strtotime($r['created_at'])) ?></td>
                    <td>
                        <div class="flex items-center justify-end gap-1">
                            <button onclick="openEditModal(<?= $r['id'] ?>)"
                                    class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-500 hover:text-blue-600 hover:border-blue-300 hover:bg-blue-50 transition-all"
                                    title="Edit"><i class="fas fa-edit text-xs"></i></button>
                            <button onclick="confirmDelete(<?= $r['id'] ?>, 'Vol <?= $r['volume'] ?> Issue <?= $r['issue'] ?>')"
                                    class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-500 hover:text-red-600 hover:border-red-300 hover:bg-red-50 transition-all"
                                    title="Delete"><i class="fas fa-trash-alt text-xs"></i></button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="px-5 py-3 border-t border-gray-100 text-xs text-gray-400 flex items-center justify-between">
            <span><?= $totalRecords ?> record<?= $totalRecords!==1?'s':'' ?> for selected journal</span>
            <span class="text-blue-400"><i class="fas fa-keyboard mr-1"></i>Ctrl+K → New Issue</span>
        </div>
    </div>

</main>
</div>

<!-- ═══ CREATE / EDIT MODAL ═══ -->
<div id="volModal" class="modal-overlay" onclick="if(event.target===this)closeModal()">
<div class="modal-box">
    <div class="modal-header">
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center">
                <i class="fas fa-layer-group text-blue-600"></i>
            </div>
            <div>
                <h3 id="modalTitle" class="font-bold text-gray-800 text-base">Create Volume / Issue</h3>
                <p id="modalSub" class="text-xs text-gray-400 mt-0.5">Select journal and fill details</p>
            </div>
        </div>
        <button onclick="closeModal()" class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-gray-600 hover:bg-gray-50">
            <i class="fas fa-times text-sm"></i>
        </button>
    </div>
    <div class="modal-body">
        <form id="volForm" method="POST">
            <input type="hidden" name="_action"   id="fAction"   value="create">
            <input type="hidden" name="record_id" id="fRecordId">

            <div class="space-y-4">

                <!-- Journal -->
                <div>
                    <label class="flabel">Journal <span class="text-red-500">*</span></label>
                    <select name="modal_journal_id" id="fJournalId" class="finput" required>
                        <option value="">— Select Journal —</option>
                        <?php foreach ($journals as $j): ?>
                        <option value="<?= $j['journal_id'] ?>" <?= $j['journal_id']==$JOURNAL_ID?'selected':'' ?>>
                            <?= htmlspecialchars($j['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Volume + Issue -->
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="flabel">Volume <span class="text-red-500">*</span></label>
                        <input type="number" name="volume" id="fVolume" min="1" class="finput" placeholder="e.g. 1" required>
                    </div>
                    <div>
                        <label class="flabel">Issue <span class="text-red-500">*</span></label>
                        <input type="number" name="issue" id="fIssue" min="1" class="finput" placeholder="e.g. 1" required>
                    </div>
                </div>

                <!-- Title -->
                <div>
                    <label class="flabel">Issue Title <span class="text-gray-400 font-normal">(optional)</span></label>
                    <input type="text" name="title" id="fTitle" class="finput" placeholder="e.g. Special Issue on AI">
                </div>

                <!-- Status -->
                <div class="pt-1">
                    <label class="toggle-wrap">
                        <input type="checkbox" name="is_active" id="fIsActive" class="toggle-input" checked>
                        <div class="toggle-track"></div>
                        <div class="toggle-thumb"></div>
                        <span class="text-sm text-gray-600" id="activeLabel">Active</span>
                    </label>
                </div>

            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button onclick="closeModal()" class="px-4 py-2 text-sm text-gray-600 border border-gray-200 rounded-lg hover:bg-gray-50">Cancel</button>
        <button onclick="document.getElementById('volForm').submit()"
                class="px-5 py-2 text-sm font-semibold bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2">
            <i class="fas fa-save text-xs"></i>
            <span id="submitLabel">Create</span>
        </button>
    </div>
</div>
</div>

<!-- ═══ DELETE CONFIRM ═══ -->
<div id="confirmOverlay" class="confirm-overlay" onclick="if(event.target===this)closeConfirm()">
<div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-sm mx-4">
    <div class="flex items-center gap-3 mb-4">
        <div class="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
            <i class="fas fa-trash-alt text-red-500 text-lg"></i>
        </div>
        <div>
            <h3 class="font-bold text-gray-800">Delete Record?</h3>
            <p class="text-sm text-gray-500">This cannot be undone.</p>
        </div>
    </div>
    <p class="text-sm text-gray-600 mb-5">Deleting <strong id="deleteLabel"></strong>.</p>
    <form method="POST" action="?journal_id=<?= $JOURNAL_ID ?>">
        <input type="hidden" name="_action"   value="delete">
        <input type="hidden" name="record_id" id="deleteId">
        <input type="hidden" name="journal_id" value="<?= $JOURNAL_ID ?>">
        <div class="flex gap-2">
            <button type="button" onclick="closeConfirm()" class="flex-1 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50">Cancel</button>
            <button type="submit" class="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg text-sm font-semibold hover:bg-red-700">Delete</button>
        </div>
    </form>
</div>
</div>

<script>
const currentJournalId = <?= $JOURNAL_ID ?>;

function openCreateModal() {
    document.getElementById('volForm').reset();
    document.getElementById('fAction').value      = 'create';
    document.getElementById('fRecordId').value    = '';
    document.getElementById('fJournalId').value   = currentJournalId;
    document.getElementById('fIsActive').checked  = true;
    document.getElementById('activeLabel').textContent = 'Active';
    document.getElementById('modalTitle').textContent  = 'Create Volume / Issue';
    document.getElementById('modalSub').textContent    = 'Select journal and fill details';
    document.getElementById('submitLabel').textContent = 'Create';
    document.getElementById('volModal').classList.add('open');
    setTimeout(() => document.getElementById('fVolume').focus(), 100);
}

function openEditModal(id) {
    fetch(`?action=get&id=${id}&journal_id=${currentJournalId}`)
        .then(r => r.json())
        .then(d => {
            if (!d) return;
            document.getElementById('fAction').value      = 'update';
            document.getElementById('fRecordId').value    = d.id;
            document.getElementById('fJournalId').value   = d.journal_id;
            document.getElementById('fVolume').value      = d.volume;
            document.getElementById('fIssue').value       = d.issue;
            document.getElementById('fTitle').value       = d.title || '';
            document.getElementById('fIsActive').checked  = d.is_active == 1;
            document.getElementById('activeLabel').textContent = d.is_active == 1 ? 'Active' : 'Inactive';
            document.getElementById('modalTitle').textContent  = `Edit Vol ${d.volume} Issue ${d.issue}`;
            document.getElementById('modalSub').textContent    = 'Update journal, volume and issue details';
            document.getElementById('submitLabel').textContent = 'Save Changes';
            document.getElementById('volModal').classList.add('open');
        });
}

function closeModal() { document.getElementById('volModal').classList.remove('open'); }

function confirmDelete(id, label) {
    document.getElementById('deleteId').value = id;
    document.getElementById('deleteLabel').textContent = label;
    document.getElementById('confirmOverlay').classList.add('open');
}
function closeConfirm() { document.getElementById('confirmOverlay').classList.remove('open'); }

function toggleActive(id, val) {
    const fd = new FormData();
    fd.append('_action',   'toggle');
    fd.append('record_id', id);
    fd.append('val',       val);
    fetch(location.href, { method:'POST', body:fd });
}

document.getElementById('fIsActive')?.addEventListener('change', function () {
    document.getElementById('activeLabel').textContent = this.checked ? 'Active' : 'Inactive';
});

document.addEventListener('keydown', e => {
    if (e.key === 'Escape') { closeModal(); closeConfirm(); }
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') { e.preventDefault(); openCreateModal(); }
});
</script>
</body>
</html>