<?php
// admin/categories.php
// ══════════════════════════════════════════════════════
// Manage: Journal Categories, Specialties, Article Types
// ══════════════════════════════════════════════════════
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set('display_errors', 1);
session_start();

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

// ── Auto-create/patch tables ──────────────────────────
$tablesDDL = [
    "CREATE TABLE IF NOT EXISTS `journal_categories` (
        `category_id`   INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `name`          VARCHAR(120) NOT NULL,
        `display_order` INT UNSIGNED DEFAULT 0,
        UNIQUE KEY `uq_name` (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

    "CREATE TABLE IF NOT EXISTS `specialties` (
        `specialty_id`  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `journal_id`    INT UNSIGNED NOT NULL,
        `name`          VARCHAR(200) NOT NULL,
        `description`   TEXT NULL,
        `is_active`     TINYINT(1) DEFAULT 1,
        `created_at`    DATETIME DEFAULT NOW(),
        KEY `idx_journal` (`journal_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

    "CREATE TABLE IF NOT EXISTS `article_types` (
        `article_type_id`      INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `specialty_id`         INT UNSIGNED NULL,
        `name`                 VARCHAR(200) NOT NULL,
        `description`          TEXT NULL,
        `summary_length`       INT UNSIGNED DEFAULT 350,
        `figures_tables_limit` INT UNSIGNED DEFAULT 10,
        `preliminary_fee_chf`  DECIMAL(10,2) DEFAULT 0.00,
        `display_order`        INT UNSIGNED DEFAULT 0,
        KEY `idx_specialty` (`specialty_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",
];
foreach ($tablesDDL as $sql) {
    try { $pdo->exec($sql); } catch(PDOException $e) {}
}

// ── Helpers ───────────────────────────────────────────
function p($v): string { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

$msg = ''; $msgType = ''; $activeSection = $_GET['section'] ?? 'journal_categories';

// ══════════════════════════════════════════════════════
// AJAX HANDLERS
// ══════════════════════════════════════════════════════
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $action = $_GET['ajax'];
    $id     = (int)($_GET['id'] ?? 0);

    if ($action === 'get_journal_category') {
        $q = $pdo->prepare("SELECT * FROM journal_categories WHERE category_id=?");
        $q->execute([$id]);
        echo json_encode($q->fetch(PDO::FETCH_ASSOC) ?: []);
        exit;
    }
    if ($action === 'get_specialty') {
        $q = $pdo->prepare("
            SELECT sp.*, j.name AS journal_name
            FROM specialties sp
            LEFT JOIN journals j ON j.journal_id = sp.journal_id
            WHERE sp.specialty_id=?
        ");
        $q->execute([$id]);
        echo json_encode($q->fetch(PDO::FETCH_ASSOC) ?: []);
        exit;
    }
    if ($action === 'get_article_type') {
        $q = $pdo->prepare("SELECT * FROM article_types WHERE article_type_id=?");
        $q->execute([$id]);
        echo json_encode($q->fetch(PDO::FETCH_ASSOC) ?: []);
        exit;
    }
    if ($action === 'toggle_specialty') {
        $pdo->prepare("UPDATE specialties SET is_active = 1 - is_active WHERE specialty_id=?")->execute([$id]);
        echo json_encode(['success' => true]);
        exit;
    }
    if ($action === 'get_article_type_for_modal') {
        // alias kept for compatibility
        $q = $pdo->prepare("SELECT * FROM article_types WHERE article_type_id=?");
        $q->execute([$id]);
        echo json_encode($q->fetch(PDO::FETCH_ASSOC) ?: []);
        exit;
    }
    exit;
}

// ══════════════════════════════════════════════════════
// POST — JOURNAL CATEGORIES
// ══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_journal_category'])) {
    $activeSection = 'journal_categories';
    try {
        $id    = (int)($_POST['category_id'] ?? 0);
        $name  = trim($_POST['name'] ?? '');
        $order = (int)($_POST['display_order'] ?? 0);
        if (empty($name)) throw new Exception("Category name is required.");

        $chk = $pdo->prepare("SELECT category_id FROM journal_categories WHERE name=? AND category_id!=?");
        $chk->execute([$name, $id]);
        if ($chk->fetch()) throw new Exception("Category '$name' already exists.");

        if ($id > 0) {
            $pdo->prepare("UPDATE journal_categories SET name=?, display_order=? WHERE category_id=?")
                ->execute([$name, $order, $id]);
            $msg = "Category '$name' updated.";
        } else {
            $pdo->prepare("INSERT INTO journal_categories (name, display_order) VALUES (?,?)")
                ->execute([$name, $order]);
            $msg = "Category '$name' added.";
        }
        $msgType = 'success';
    } catch(Exception $e) { $msg = $e->getMessage(); $msgType = 'error'; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_journal_category'])) {
    $activeSection = 'journal_categories';
    $id = (int)$_POST['category_id'];
    $chk = $pdo->prepare("SELECT COUNT(*) FROM journals WHERE category_id=?");
    $chk->execute([$id]);
    if ($chk->fetchColumn() > 0) {
        $msg = "Cannot delete — journals are using this category."; $msgType = 'error';
    } else {
        $pdo->prepare("DELETE FROM journal_categories WHERE category_id=?")->execute([$id]);
        $msg = "Category deleted."; $msgType = 'success';
    }
}

// ══════════════════════════════════════════════════════
// POST — SPECIALTIES
// ══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_specialty'])) {
    $activeSection = 'specialties';
    try {
        $id          = (int)($_POST['specialty_id'] ?? 0);
        $journal_id  = (int)($_POST['journal_id'] ?? 0);
        $name        = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $is_active   = isset($_POST['is_active']) ? 1 : 0;
        if (empty($name))       throw new Exception("Specialty name is required.");
        if ($journal_id <= 0)   throw new Exception("Please select a journal.");

        if ($id > 0) {
            $pdo->prepare("
                UPDATE specialties SET journal_id=?, name=?, description=?, is_active=?
                WHERE specialty_id=?
            ")->execute([$journal_id, $name, $description, $is_active, $id]);
            $msg = "Specialty '$name' updated.";
        } else {
            $pdo->prepare("
                INSERT INTO specialties (journal_id, name, description, is_active, created_at)
                VALUES (?,?,?,?,NOW())
            ")->execute([$journal_id, $name, $description, $is_active]);
            // Update journal specialty_count
            $pdo->prepare("UPDATE journals SET specialty_count = (SELECT COUNT(*) FROM specialties WHERE journal_id=? AND is_active=1) WHERE journal_id=?")
                ->execute([$journal_id, $journal_id]);
            $msg = "Specialty '$name' added.";
        }
        $msgType = 'success';
    } catch(Exception $e) { $msg = $e->getMessage(); $msgType = 'error'; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_specialty'])) {
    $activeSection = 'specialties';
    $id = (int)$_POST['specialty_id'];
    $chk = $pdo->prepare("SELECT COUNT(*) FROM submissions WHERE specialty_id=?");
    $chk->execute([$id]);
    if ($chk->fetchColumn() > 0) {
        $msg = "Cannot delete — submissions are using this specialty."; $msgType = 'error';
    } else {
        $pdo->prepare("DELETE FROM specialties WHERE specialty_id=?")->execute([$id]);
        $msg = "Specialty deleted."; $msgType = 'success';
    }
}

// ══════════════════════════════════════════════════════
// POST — ARTICLE TYPES
// ══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_article_type'])) {
    $activeSection = 'article_types';
    try {
        $id             = (int)($_POST['article_type_id'] ?? 0);
        $specialty_id   = !empty($_POST['specialty_id']) ? (int)$_POST['specialty_id'] : null;
        $name           = trim($_POST['name'] ?? '');
        $description    = trim($_POST['description'] ?? '');
        $fee            = (float)($_POST['preliminary_fee_chf'] ?? 0);
        $summary_length = (int)($_POST['summary_length'] ?? 350);
        $fig_limit      = (int)($_POST['figures_tables_limit'] ?? 10);
        $display_order  = (int)($_POST['display_order'] ?? 0);
        if (empty($name)) throw new Exception("Article type name is required.");

        if ($id > 0) {
            $pdo->prepare("
                UPDATE article_types SET specialty_id=?, name=?, description=?,
                summary_length=?, figures_tables_limit=?, preliminary_fee_chf=?, display_order=?
                WHERE article_type_id=?
            ")->execute([$specialty_id, $name, $description, $summary_length, $fig_limit, $fee, $display_order, $id]);
            $msg = "Article type '$name' updated.";
        } else {
            $pdo->prepare("
                INSERT INTO article_types
                (specialty_id, name, description, summary_length, figures_tables_limit, preliminary_fee_chf, display_order)
                VALUES (?,?,?,?,?,?,?)
            ")->execute([$specialty_id, $name, $description, $summary_length, $fig_limit, $fee, $display_order]);
            $msg = "Article type '$name' added.";
        }
        $msgType = 'success';
    } catch(Exception $e) { $msg = $e->getMessage(); $msgType = 'error'; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_article_type'])) {
    $activeSection = 'article_types';
    $id = (int)$_POST['article_type_id'];
    $chk = $pdo->prepare("SELECT COUNT(*) FROM submissions WHERE article_type_id=?");
    $chk->execute([$id]);
    if ($chk->fetchColumn() > 0) {
        $msg = "Cannot delete — submissions are using this article type."; $msgType = 'error';
    } else {
        $pdo->prepare("DELETE FROM article_types WHERE article_type_id=?")->execute([$id]);
        $msg = "Article type deleted."; $msgType = 'success';
    }
}

// ══════════════════════════════════════════════════════
// FETCH DATA
// ══════════════════════════════════════════════════════
$searchJC  = trim($_GET['search_jc'] ?? '');
$searchSP  = trim($_GET['search_sp'] ?? '');
$searchAT  = trim($_GET['search_at'] ?? '');
$filterJournal = (int)($_GET['journal'] ?? 0);

// Journal Categories
$jcWhere = $searchJC ? "WHERE name LIKE ?" : "WHERE 1=1";
$jcParams = $searchJC ? ["%$searchJC%"] : [];
$journalCategories = $pdo->prepare("
    SELECT c.*, 
           COUNT(j.journal_id) AS journal_count
    FROM journal_categories c
    LEFT JOIN journals j ON j.category_id = c.category_id
    $jcWhere
    GROUP BY c.category_id
    ORDER BY c.display_order ASC, c.name ASC
");
$journalCategories->execute($jcParams);
$journalCategories = $journalCategories->fetchAll(PDO::FETCH_ASSOC);

// Specialties
$spWhere = "WHERE 1=1";
$spParams = [];
if ($searchSP) { $spWhere .= " AND sp.name LIKE ?"; $spParams[] = "%$searchSP%"; }
if ($filterJournal > 0) { $spWhere .= " AND sp.journal_id = ?"; $spParams[] = $filterJournal; }
$specialties = $pdo->prepare("
    SELECT sp.*, j.name AS journal_name,
           (SELECT COUNT(*) FROM submissions sub WHERE sub.specialty_id = sp.specialty_id) AS submission_count
    FROM specialties sp
    LEFT JOIN journals j ON j.journal_id = sp.journal_id
    $spWhere
    ORDER BY j.name ASC, sp.name ASC
");
$specialties->execute($spParams);
$specialties = $specialties->fetchAll(PDO::FETCH_ASSOC);

// Article Types
$atWhere = $searchAT ? "WHERE name LIKE ?" : "WHERE 1=1";
$atParams = $searchAT ? ["%$searchAT%"] : [];
$articleTypes = $pdo->prepare("
    SELECT at.*,
           sp.name AS specialty_name,
           (SELECT COUNT(*) FROM submissions sub WHERE sub.article_type_id = at.article_type_id) AS submission_count
    FROM article_types at
    LEFT JOIN specialties sp ON sp.specialty_id = at.specialty_id
    $atWhere
    ORDER BY at.display_order ASC, at.name ASC
");
$articleTypes->execute($atParams);
$articleTypes = $articleTypes->fetchAll(PDO::FETCH_ASSOC);

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

// Stats
$stats = [
    'journal_categories' => count($journalCategories),
    'specialties'        => count($specialties),
    'article_types'      => count($articleTypes),
    'active_specialties' => count(array_filter($specialties, fn($s) => $s['is_active'])),
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Categories Management — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
body { font-family:'Inter',sans-serif; }
.sidebar { width:240px; height:100vh; position:fixed; top:0; left:0; background:#1e293b; z-index:100; overflow-y:auto; }
.content { margin-left:240px; min-height:100vh; }
.sec-tab { padding:10px 20px; border-bottom:3px solid transparent; font-size:13px; font-weight:500; color:#64748b; cursor:pointer; white-space:nowrap; transition:all .15s; }
.sec-tab.active { border-bottom-color:#2563eb; color:#1d4ed8; font-weight:600; }
.sec-tab:hover:not(.active) { color:#374151; border-bottom-color:#e5e7eb; }
.badge { padding:2px 10px; border-radius:20px; font-size:11px; font-weight:600; display:inline-flex; align-items:center; gap:4px; }
.modal-bd { background:rgba(0,0,0,.5); }
.toggle { position:relative; display:inline-flex; align-items:center; cursor:pointer; }
.toggle input { opacity:0; width:0; height:0; position:absolute; }
.toggle-track { width:42px; height:24px; background:#d1d5db; border-radius:12px; transition:.2s; }
.toggle input:checked ~ .toggle-track { background:#2563eb; }
.toggle-thumb { position:absolute; left:3px; top:50%; transform:translateY(-50%); width:18px; height:18px; background:white; border-radius:50%; box-shadow:0 1px 3px rgba(0,0,0,.2); transition:.2s; pointer-events:none; }
.toggle input:checked ~ .toggle-thumb { left:21px; }
tr:hover td { background:#f8faff; }
</style>
</head>
<body class="bg-gray-50">

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

<div class="content">

<!-- ── HEADER ─────────────────────────────────────────── -->
<div class="bg-white border-b border-gray-200 px-6 py-4 sticky top-0 z-10 shadow-sm">
  <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-purple-600"></i>
        Categories Management
      </h1>
      <p class="text-xs text-gray-400 mt-0.5">
        Journal categories · Specialties · Article types
      </p>
    </div>
    <div id="addBtnWrap">
      <!-- Dynamic — changes per tab -->
    </div>
  </div>
</div>

<!-- ── FLASH ──────────────────────────────────────────── -->
<?php if($msg): ?>
<div id="flashMsg" class="mx-6 mt-4 p-3 rounded-lg text-sm font-medium flex items-center gap-2
  <?=$msgType==='success'?'bg-green-50 border border-green-200 text-green-700':'bg-red-50 border border-red-200 text-red-700'?>">
  <i class="fas <?=$msgType==='success'?'fa-check-circle':'fa-exclamation-circle'?>"></i>
  <?=p($msg)?>
</div>
<script>setTimeout(()=>{const e=document.getElementById('flashMsg');if(e){e.style.opacity='0';e.style.transition='opacity .5s';setTimeout(()=>e.remove(),500);}},4000);</script>
<?php endif; ?>

<div class="p-6">

<!-- ── STATS ─────────────────────────────────────────── -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
  <?php
  $statCards = [
    ['Journal Categories', $stats['journal_categories'], 'fas fa-tags',         'bg-blue-100',   'text-blue-600',   'journal_categories'],
    ['Specialties',        $stats['specialties'],        'fas fa-microscope',   'bg-purple-100', 'text-purple-600', 'specialties'],
    ['Active Specialties', $stats['active_specialties'], 'fas fa-check-circle', 'bg-green-100',  'text-green-600',  'specialties'],
    ['Article Types',      $stats['article_types'],      'fas fa-file-alt',     'bg-orange-100', 'text-orange-600', 'article_types'],
  ];
  foreach($statCards as [$label, $count, $icon, $bg, $color, $sec]):
  ?>
  <div class="bg-white rounded-xl border border-gray-200 p-5 flex items-center gap-4 cursor-pointer hover:border-blue-300 transition"
       onclick="switchSection('<?=$sec?>')">
    <div class="w-11 h-11 rounded-xl <?=$bg?> flex items-center justify-center flex-shrink-0">
      <i class="<?=$icon?> <?=$color?> text-lg"></i>
    </div>
    <div>
      <div class="text-2xl font-bold text-gray-800"><?=$count?></div>
      <div class="text-xs text-gray-400"><?=$label?></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- ── SECTION TABS ───────────────────────────────────── -->
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">

  <div class="flex border-b border-gray-100 overflow-x-auto">
    <button class="sec-tab <?=$activeSection==='journal_categories'?'active':''?>"
            onclick="switchSection('journal_categories')" id="tab-journal_categories">
      <i class="fas fa-tags mr-1.5"></i> Journal Categories
      <span class="ml-1.5 bg-gray-100 text-gray-500 text-xs px-1.5 py-0.5 rounded-full"><?=count($journalCategories)?></span>
    </button>
    <button class="sec-tab <?=$activeSection==='specialties'?'active':''?>"
            onclick="switchSection('specialties')" id="tab-specialties">
      <i class="fas fa-microscope mr-1.5"></i> Specialties
      <span class="ml-1.5 bg-gray-100 text-gray-500 text-xs px-1.5 py-0.5 rounded-full"><?=count($specialties)?></span>
    </button>
    <button class="sec-tab <?=$activeSection==='article_types'?'active':''?>"
            onclick="switchSection('article_types')" id="tab-article_types">
      <i class="fas fa-file-alt mr-1.5"></i> Article Types
      <span class="ml-1.5 bg-gray-100 text-gray-500 text-xs px-1.5 py-0.5 rounded-full"><?=count($articleTypes)?></span>
    </button>
  </div>

  <!-- ════════════════════════════════════════
       SECTION 1: JOURNAL CATEGORIES
  ════════════════════════════════════════ -->
  <div id="sec-journal_categories" class="<?=$activeSection==='journal_categories'?'':'hidden'?>">

    <!-- Toolbar -->
    <div class="px-5 py-3 border-b border-gray-50 flex items-center justify-between gap-3 flex-wrap">
      <form method="GET" class="flex items-center gap-2">
        <input type="hidden" name="section" value="journal_categories">
        <div class="relative">
          <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-300 text-xs"></i>
          <input type="text" name="search_jc" value="<?=p($searchJC)?>"
                 placeholder="Search categories..."
                 class="border border-gray-200 rounded-lg pl-8 pr-3 py-2 text-sm w-56 focus:ring-2 focus:ring-blue-400 focus:outline-none">
        </div>
        <button class="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg text-sm hover:bg-gray-200">
          <i class="fas fa-search"></i>
        </button>
        <?php if($searchJC): ?>
        <a href="?section=journal_categories" class="text-gray-400 hover:text-gray-600 text-sm">
          <i class="fas fa-times"></i>
        </a>
        <?php endif; ?>
      </form>
      <button onclick="openJCModal()"
              class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-blue-700 flex items-center gap-2">
        <i class="fas fa-plus"></i> Add Category
      </button>
    </div>

    <!-- Table -->
    <?php if(empty($journalCategories)): ?>
    <div class="text-center py-12 text-gray-400">
      <i class="fas fa-tags text-4xl mb-3 opacity-20"></i>
      <p class="text-sm">No journal categories found</p>
    </div>
    <?php else: ?>
    <table class="w-full text-sm">
      <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
        <tr>
          <th class="px-5 py-3 text-left w-12">#</th>
          <th class="px-5 py-3 text-left">Category Name</th>
          <th class="px-5 py-3 text-center">Display Order</th>
          <th class="px-5 py-3 text-center">Journals</th>
          <th class="px-5 py-3 text-right">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-50">
        <?php foreach($journalCategories as $c): ?>
        <tr>
          <td class="px-5 py-3 text-gray-400 font-mono text-xs"><?=$c['category_id']?></td>
          <td class="px-5 py-3">
            <div class="flex items-center gap-3">
              <div class="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center text-blue-600 font-bold text-xs">
                <?=strtoupper(substr($c['name'],0,1))?>
              </div>
              <span class="font-medium text-gray-800"><?=p($c['name'])?></span>
            </div>
          </td>
          <td class="px-5 py-3 text-center">
            <span class="bg-gray-100 text-gray-600 px-2 py-0.5 rounded font-mono text-xs"><?=$c['display_order']?></span>
          </td>
          <td class="px-5 py-3 text-center">
            <a href="journals.php?cat=<?=$c['category_id']?>"
               class="font-semibold <?=$c['journal_count']>0?'text-blue-600 hover:underline':'text-gray-300'?>">
              <?=$c['journal_count']?>
            </a>
          </td>
          <td class="px-5 py-3 text-right">
            <div class="flex items-center justify-end gap-1.5">
              <button onclick="editJC(<?=$c['category_id']?>)"
                      class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-blue-600 hover:bg-blue-50 hover:border-blue-200 transition"
                      title="Edit">
                <i class="fas fa-edit text-xs"></i>
              </button>
              <button onclick="deleteJC(<?=$c['category_id']?>, '<?=p($c['name'])?>')"
                      class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-red-600 hover:bg-red-50 hover:border-red-200 transition"
                      title="Delete">
                <i class="fas fa-trash text-xs"></i>
              </button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <!-- ════════════════════════════════════════
       SECTION 2: SPECIALTIES
  ════════════════════════════════════════ -->
  <div id="sec-specialties" class="<?=$activeSection==='specialties'?'':'hidden'?>">

    <!-- Toolbar -->
    <div class="px-5 py-3 border-b border-gray-50 flex items-center justify-between gap-3 flex-wrap">
      <form method="GET" class="flex items-center gap-2 flex-wrap">
        <input type="hidden" name="section" value="specialties">
        <div class="relative">
          <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-300 text-xs"></i>
          <input type="text" name="search_sp" value="<?=p($searchSP)?>"
                 placeholder="Search specialties..."
                 class="border border-gray-200 rounded-lg pl-8 pr-3 py-2 text-sm w-48 focus:ring-2 focus:ring-blue-400 focus:outline-none">
        </div>
        <select name="journal" class="border border-gray-200 rounded-lg px-3 py-2 text-sm">
          <option value="">All Journals</option>
          <?php foreach($allJournals as $j): ?>
          <option value="<?=$j['journal_id']?>" <?=$filterJournal==$j['journal_id']?'selected':''?>>
            <?=p($j['name'])?>
          </option>
          <?php endforeach; ?>
        </select>
        <button class="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg text-sm hover:bg-gray-200">
          <i class="fas fa-filter"></i>
        </button>
        <?php if($searchSP||$filterJournal): ?>
        <a href="?section=specialties" class="text-gray-400 hover:text-gray-600 text-sm"><i class="fas fa-times"></i></a>
        <?php endif; ?>
      </form>
      <button onclick="openSPModal()"
              class="bg-purple-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-purple-700 flex items-center gap-2">
        <i class="fas fa-plus"></i> Add Specialty
      </button>
    </div>

    <!-- Table -->
    <?php if(empty($specialties)): ?>
    <div class="text-center py-12 text-gray-400">
      <i class="fas fa-microscope text-4xl mb-3 opacity-20"></i>
      <p class="text-sm">No specialties found</p>
    </div>
    <?php else: ?>
    <table class="w-full text-sm">
      <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
        <tr>
          <th class="px-5 py-3 text-left w-12">#</th>
          <th class="px-5 py-3 text-left">Specialty Name</th>
          <th class="px-5 py-3 text-left">Journal</th>
          <th class="px-5 py-3 text-left">Description</th>
          <th class="px-5 py-3 text-center">Submissions</th>
          <th class="px-5 py-3 text-center">Status</th>
          <th class="px-5 py-3 text-right">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-50">
        <?php foreach($specialties as $sp): ?>
        <tr>
          <td class="px-5 py-3 text-gray-400 font-mono text-xs"><?=$sp['specialty_id']?></td>
          <td class="px-5 py-3 font-medium text-gray-800"><?=p($sp['name'])?></td>
          <td class="px-5 py-3">
            <span class="badge bg-blue-50 text-blue-700">
              <?=p($sp['journal_name'] ?? '—')?>
            </span>
          </td>
          <td class="px-5 py-3 text-gray-500 text-xs max-w-xs truncate">
            <?=p(substr($sp['description']??'',0,60))?><?=strlen($sp['description']??'')>60?'...':''?>
          </td>
          <td class="px-5 py-3 text-center">
            <span class="<?=$sp['submission_count']>0?'font-semibold text-blue-600':'text-gray-300'?>">
              <?=$sp['submission_count']?>
            </span>
          </td>
          <td class="px-5 py-3 text-center">
            <button onclick="toggleSpecialty(<?=$sp['specialty_id']?>, this)"
                    id="sp-status-<?=$sp['specialty_id']?>"
                    class="badge <?=$sp['is_active']?'bg-green-100 text-green-700':'bg-gray-100 text-gray-500'?> cursor-pointer hover:opacity-80 transition">
              <span class="w-1.5 h-1.5 rounded-full <?=$sp['is_active']?'bg-green-500':'bg-gray-400'?>"></span>
              <?=$sp['is_active']?'Active':'Inactive'?>
            </button>
          </td>
          <td class="px-5 py-3 text-right">
            <div class="flex items-center justify-end gap-1.5">
              <button onclick="editSP(<?=$sp['specialty_id']?>)"
                      class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-purple-600 hover:bg-purple-50 hover:border-purple-200 transition">
                <i class="fas fa-edit text-xs"></i>
              </button>
              <button onclick="deleteSP(<?=$sp['specialty_id']?>, '<?=p($sp['name'])?>')"
                      class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-red-600 hover:bg-red-50 hover:border-red-200 transition">
                <i class="fas fa-trash text-xs"></i>
              </button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <!-- ════════════════════════════════════════
       SECTION 3: ARTICLE TYPES
  ════════════════════════════════════════ -->
  <div id="sec-article_types" class="<?=$activeSection==='article_types'?'':'hidden'?>">

    <!-- Toolbar -->
    <div class="px-5 py-3 border-b border-gray-50 flex items-center justify-between gap-3 flex-wrap">
      <form method="GET" class="flex items-center gap-2">
        <input type="hidden" name="section" value="article_types">
        <div class="relative">
          <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-300 text-xs"></i>
          <input type="text" name="search_at" value="<?=p($searchAT)?>"
                 placeholder="Search article types..."
                 class="border border-gray-200 rounded-lg pl-8 pr-3 py-2 text-sm w-56 focus:ring-2 focus:ring-blue-400 focus:outline-none">
        </div>
        <button class="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg text-sm hover:bg-gray-200">
          <i class="fas fa-search"></i>
        </button>
        <?php if($searchAT): ?>
        <a href="?section=article_types" class="text-gray-400 hover:text-gray-600 text-sm"><i class="fas fa-times"></i></a>
        <?php endif; ?>
      </form>
      <button onclick="openATModal()"
              class="bg-orange-500 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-orange-600 flex items-center gap-2">
        <i class="fas fa-plus"></i> Add Article Type
      </button>
    </div>

    <!-- Table -->
    <?php if(empty($articleTypes)): ?>
    <div class="text-center py-12 text-gray-400">
      <i class="fas fa-file-alt text-4xl mb-3 opacity-20"></i>
      <p class="text-sm">No article types found</p>
    </div>
    <?php else: ?>
    <table class="w-full text-sm">
      <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
        <tr>
          <th class="px-5 py-3 text-left w-12">#</th>
          <th class="px-5 py-3 text-left">Article Type</th>
          <th class="px-5 py-3 text-left">Specialty</th>
          <th class="px-5 py-3 text-center">Fee (CHF)</th>
          <th class="px-5 py-3 text-center">Summary</th>
          <th class="px-5 py-3 text-center">Figures</th>
          <th class="px-5 py-3 text-center">Order</th>
          <th class="px-5 py-3 text-center">Submissions</th>
          <th class="px-5 py-3 text-right">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-50">
        <?php foreach($articleTypes as $at): ?>
        <tr>
          <td class="px-5 py-3 text-gray-400 font-mono text-xs"><?=$at['article_type_id']?></td>
          <td class="px-5 py-3">
            <div class="flex items-center gap-2">
              <div class="w-7 h-7 rounded-lg bg-orange-100 flex items-center justify-center text-orange-600 text-xs flex-shrink-0">
                <i class="fas fa-file-alt"></i>
              </div>
              <div>
                <div class="font-medium text-gray-800"><?=p($at['name'])?></div>
                <?php if(!empty($at['description'])): ?>
                <div class="text-xs text-gray-400 mt-0.5 max-w-xs truncate">
                  <?=p(substr($at['description'],0,55))?><?=strlen($at['description'])>55?'...':''?>
                </div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td class="px-5 py-3">
            <?php if(!empty($at['specialty_name'])): ?>
            <span class="badge bg-purple-50 text-purple-700 text-xs"><?=p($at['specialty_name'])?></span>
            <?php else: ?>
            <span class="text-xs text-gray-300">All</span>
            <?php endif; ?>
          </td>
          <td class="px-5 py-3 text-center">
            <span class="font-semibold text-gray-700 font-mono text-sm"><?=number_format((float)$at['preliminary_fee_chf'],2)?></span>
          </td>
          <td class="px-5 py-3 text-center text-xs text-gray-500"><?=$at['summary_length']?> w</td>
          <td class="px-5 py-3 text-center text-xs text-gray-500"><?=$at['figures_tables_limit']?></td>
          <td class="px-5 py-3 text-center">
            <span class="bg-gray-100 text-gray-600 px-2 py-0.5 rounded font-mono text-xs"><?=$at['display_order']?></span>
          </td>
          <td class="px-5 py-3 text-center">
            <span class="<?=$at['submission_count']>0?'font-semibold text-blue-600':'text-gray-300'?>">
              <?=$at['submission_count']?>
            </span>
          </td>
          <td class="px-5 py-3 text-right">
            <div class="flex items-center justify-end gap-1.5">
              <button onclick="editAT(<?=$at['article_type_id']?>)"
                      class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-orange-600 hover:bg-orange-50 hover:border-orange-200 transition">
                <i class="fas fa-edit text-xs"></i>
              </button>
              <button onclick="deleteAT(<?=$at['article_type_id']?>, '<?=p($at['name'])?>')"
                      class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-red-600 hover:bg-red-50 hover:border-red-200 transition">
                <i class="fas fa-trash text-xs"></i>
              </button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

</div><!-- /tabs card -->
</div><!-- /p-6 -->
</div><!-- /content -->

<!-- ══════════════════════════════════════════════════════
     MODAL: JOURNAL CATEGORY
══════════════════════════════════════════════════════ -->
<div id="jcModal" class="fixed inset-0 modal-bd hidden z-50 flex items-center justify-center p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md">
    <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
      <h2 class="font-bold text-gray-800" id="jcModalTitle">Add Journal Category</h2>
      <button onclick="closeJCModal()" class="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <form method="POST" class="p-6 space-y-4">
      <input type="hidden" name="save_journal_category" value="1">
      <input type="hidden" name="category_id" id="jcId" value="0">

      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
          Category Name <span class="text-red-500">*</span>
        </label>
        <input type="text" name="name" id="jcName" required
               placeholder="e.g. Engineering, Health Sciences..."
               class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none">
      </div>

      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
          Display Order
          <span class="font-normal text-gray-400">(lower = shown first)</span>
        </label>
        <input type="number" name="display_order" id="jcOrder" value="0" min="0"
               class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none">
        <p class="text-xs text-gray-400 mt-1">Controls the tab order in journal selection dropdowns</p>
      </div>

      <div class="flex gap-3 pt-2">
        <button type="button" onclick="closeJCModal()"
                class="flex-1 border border-gray-300 text-gray-600 py-2.5 rounded-lg text-sm font-medium hover:bg-gray-50">
          Cancel
        </button>
        <button type="submit"
                class="flex-1 bg-blue-600 text-white py-2.5 rounded-lg text-sm font-semibold hover:bg-blue-700 flex items-center justify-center gap-2">
          <i class="fas fa-save"></i> <span id="jcSaveBtn">Save Category</span>
        </button>
      </div>
    </form>
  </div>
</div>

<!-- ══════════════════════════════════════════════════════
     MODAL: SPECIALTY
══════════════════════════════════════════════════════ -->
<div id="spModal" class="fixed inset-0 modal-bd hidden z-50 flex items-center justify-center p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
    <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
      <h2 class="font-bold text-gray-800" id="spModalTitle">Add Specialty</h2>
      <button onclick="closeSPModal()" class="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <form method="POST" class="p-6 space-y-4">
      <input type="hidden" name="save_specialty" value="1">
      <input type="hidden" name="specialty_id" id="spId" value="0">

      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
          Journal <span class="text-red-500">*</span>
        </label>
        <select name="journal_id" id="spJournal" required
                class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-purple-500 focus:outline-none">
          <option value="">— Select Journal —</option>
          <?php foreach($allJournals as $j): ?>
          <option value="<?=$j['journal_id']?>"><?=p($j['name'])?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
          Specialty Name <span class="text-red-500">*</span>
        </label>
        <input type="text" name="name" id="spName" required
               placeholder="e.g. Acoustics and Vibration"
               class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-purple-500 focus:outline-none">
      </div>

      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">Description</label>
        <textarea name="description" id="spDescription" rows="3"
                  placeholder="Brief description of this specialty area..."
                  class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm resize-none focus:ring-2 focus:ring-purple-500 focus:outline-none"></textarea>
      </div>

      <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
        <label class="relative inline-flex items-center cursor-pointer">
          <input type="checkbox" name="is_active" id="spActive" value="1" checked class="sr-only peer">
          <div class="w-10 h-5 bg-gray-200 rounded-full peer peer-checked:bg-purple-600 after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-5 relative"></div>
        </label>
        <span class="text-sm text-gray-700 font-medium">Active (visible to authors)</span>
      </div>

      <div class="flex gap-3 pt-2">
        <button type="button" onclick="closeSPModal()"
                class="flex-1 border border-gray-300 text-gray-600 py-2.5 rounded-lg text-sm font-medium hover:bg-gray-50">
          Cancel
        </button>
        <button type="submit"
                class="flex-1 bg-purple-600 text-white py-2.5 rounded-lg text-sm font-semibold hover:bg-purple-700 flex items-center justify-center gap-2">
          <i class="fas fa-save"></i> <span id="spSaveBtn">Save Specialty</span>
        </button>
      </div>
    </form>
  </div>
</div>

<!-- ══════════════════════════════════════════════════════
     MODAL: ARTICLE TYPE
══════════════════════════════════════════════════════ -->
<div id="atModal" class="fixed inset-0 modal-bd hidden z-50 flex items-center justify-center p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
    <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
      <h2 class="font-bold text-gray-800" id="atModalTitle">Add Article Type</h2>
      <button onclick="closeATModal()" class="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <form method="POST" class="p-6 space-y-4">
      <input type="hidden" name="save_article_type" value="1">
      <input type="hidden" name="article_type_id" id="atId" value="0">

      <!-- Specialty (optional) -->
      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
          Specialty
          <span class="font-normal text-gray-400">(leave blank = applies to all)</span>
        </label>
        <select name="specialty_id" id="atSpecialty"
                class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-orange-500 focus:outline-none">
          <option value="">— Global / All Specialties —</option>
          <?php foreach($specialties as $sp): ?>
          <option value="<?=$sp['specialty_id']?>"><?=p($sp['journal_name'].' → '.$sp['name'])?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- Name -->
      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
          Article Type Name <span class="text-red-500">*</span>
        </label>
        <input type="text" name="name" id="atName" required
               placeholder="e.g. Original Research, Review Article..."
               class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-orange-500 focus:outline-none">
      </div>

      <!-- Description -->
      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">Description</label>
        <textarea name="description" id="atDescription" rows="2"
                  placeholder="Full description shown below dropdowns..."
                  class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm resize-none focus:ring-2 focus:ring-orange-500 focus:outline-none"></textarea>
      </div>

      <!-- Fee + Summary + Figures row -->
      <div class="grid grid-cols-3 gap-3">
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1.5">Fee (CHF)</label>
          <div class="relative">
            <span class="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-medium">CHF</span>
            <input type="number" name="preliminary_fee_chf" id="atFee"
                   value="0" min="0" step="0.01"
                   class="w-full border border-gray-200 rounded-lg pl-10 pr-2 py-2 text-sm focus:ring-2 focus:ring-orange-500 focus:outline-none">
          </div>
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1.5">
            Summary (words)
          </label>
          <input type="number" name="summary_length" id="atSummary"
                 value="350" min="0" step="50"
                 class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-orange-500 focus:outline-none">
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1.5">
            Fig/Table limit
          </label>
          <input type="number" name="figures_tables_limit" id="atFigures"
                 value="10" min="0"
                 class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-orange-500 focus:outline-none">
        </div>
      </div>

      <!-- Display Order -->
      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1.5">Display Order</label>
        <input type="number" name="display_order" id="atOrder"
               value="0" min="0"
               class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-orange-500 focus:outline-none">
        <p class="text-xs text-gray-400 mt-1">Lower number = shown first in dropdowns</p>
      </div>

      <div class="flex gap-3 pt-2">
        <button type="button" onclick="closeATModal()"
                class="flex-1 border border-gray-300 text-gray-600 py-2.5 rounded-lg text-sm font-medium hover:bg-gray-50">
          Cancel
        </button>
        <button type="submit"
                class="flex-1 bg-orange-500 text-white py-2.5 rounded-lg text-sm font-semibold hover:bg-orange-600 flex items-center justify-center gap-2">
          <i class="fas fa-save"></i> <span id="atSaveBtn">Save Article Type</span>
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Hidden delete forms -->
<form id="delJCForm" method="POST" class="hidden">
  <input type="hidden" name="delete_journal_category" value="1">
  <input type="hidden" name="category_id" id="delJCId">
</form>
<form id="delSPForm" method="POST" class="hidden">
  <input type="hidden" name="delete_specialty" value="1">
  <input type="hidden" name="specialty_id" id="delSPId">
</form>
<form id="delATForm" method="POST" class="hidden">
  <input type="hidden" name="delete_article_type" value="1">
  <input type="hidden" name="article_type_id" id="delATId">
</form>

<script>
// ══════════════════════════
// SECTION TABS
// ══════════════════════════
function switchSection(sec) {
  ['journal_categories','specialties','article_types'].forEach(s => {
    document.getElementById('sec-'+s)?.classList.toggle('hidden', s !== sec);
    document.getElementById('tab-'+s)?.classList.toggle('active', s === sec);
  });
  history.replaceState(null,'','?section='+sec);

  // Update header add button
  const btnMap = {
    journal_categories: `<button onclick="openJCModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-blue-700 flex items-center gap-2"><i class="fas fa-plus"></i> Add Category</button>`,
    specialties: `<button onclick="openSPModal()" class="bg-purple-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-purple-700 flex items-center gap-2"><i class="fas fa-plus"></i> Add Specialty</button>`,
    article_types: `<button onclick="openATModal()" class="bg-orange-500 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-orange-600 flex items-center gap-2"><i class="fas fa-plus"></i> Add Article Type</button>`,
  };
  document.getElementById('addBtnWrap').innerHTML = btnMap[sec] || '';
}

// Init header button
switchSection('<?=$activeSection?>');

// Close on backdrop click
['jcModal','spModal','atModal'].forEach(id => {
  document.getElementById(id).addEventListener('click', function(e) {
    if(e.target===this) this.classList.add('hidden');
  });
});

// ══════════════════════════
// JOURNAL CATEGORY
// ══════════════════════════
function openJCModal(data=null) {
  if(data){
    document.getElementById('jcModalTitle').textContent = 'Edit Journal Category';
    document.getElementById('jcSaveBtn').textContent    = 'Update Category';
    document.getElementById('jcId').value    = data.category_id;
    document.getElementById('jcName').value  = data.name || '';
    document.getElementById('jcOrder').value = data.display_order || 0;
  } else {
    document.getElementById('jcModalTitle').textContent = 'Add Journal Category';
    document.getElementById('jcSaveBtn').textContent    = 'Save Category';
    document.getElementById('jcId').value    = 0;
    document.getElementById('jcName').value  = '';
    document.getElementById('jcOrder').value = 0;
  }
  document.getElementById('jcModal').classList.remove('hidden');
  setTimeout(()=>document.getElementById('jcName').focus(),100);
}
async function editJC(id) {
  const d = await fetch(`?ajax=get_journal_category&id=${id}`).then(r=>r.json());
  openJCModal(d);
}
function closeJCModal() { document.getElementById('jcModal').classList.add('hidden'); }
function deleteJC(id, name) {
  if(!confirm(`Delete category "${name}"?\nMake sure no journals are using it.`)) return;
  document.getElementById('delJCId').value = id;
  document.getElementById('delJCForm').submit();
}

// ══════════════════════════
// SPECIALTY
// ══════════════════════════
function openSPModal(data=null) {
  if(data){
    document.getElementById('spModalTitle').textContent = 'Edit Specialty';
    document.getElementById('spSaveBtn').textContent    = 'Update Specialty';
    document.getElementById('spId').value          = data.specialty_id;
    document.getElementById('spJournal').value     = data.journal_id || '';
    document.getElementById('spName').value        = data.name || '';
    document.getElementById('spDescription').value = data.description || '';
    document.getElementById('spActive').checked    = data.is_active == 1;
  } else {
    document.getElementById('spModalTitle').textContent = 'Add Specialty';
    document.getElementById('spSaveBtn').textContent    = 'Save Specialty';
    document.getElementById('spId').value          = 0;
    document.getElementById('spJournal').value     = '';
    document.getElementById('spName').value        = '';
    document.getElementById('spDescription').value = '';
    document.getElementById('spActive').checked    = true;
  }
  document.getElementById('spModal').classList.remove('hidden');
  setTimeout(()=>document.getElementById('spName').focus(),100);
}
async function editSP(id) {
  const d = await fetch(`?ajax=get_specialty&id=${id}`).then(r=>r.json());
  openSPModal(d);
}
function closeSPModal() { document.getElementById('spModal').classList.add('hidden'); }
async function toggleSpecialty(id, btn) {
  await fetch(`?ajax=toggle_specialty&id=${id}`);
  const isActive = btn.textContent.trim().includes('Active') && !btn.textContent.trim().includes('Inactive');
  if(isActive){
    btn.className='badge bg-gray-100 text-gray-500 cursor-pointer hover:opacity-80 transition';
    btn.innerHTML='<span class="w-1.5 h-1.5 rounded-full bg-gray-400"></span> Inactive';
  } else {
    btn.className='badge bg-green-100 text-green-700 cursor-pointer hover:opacity-80 transition';
    btn.innerHTML='<span class="w-1.5 h-1.5 rounded-full bg-green-500"></span> Active';
  }
}
function deleteSP(id, name) {
  if(!confirm(`Delete specialty "${name}"?`)) return;
  document.getElementById('delSPId').value = id;
  document.getElementById('delSPForm').submit();
}

// ══════════════════════════
// ARTICLE TYPE
// ══════════════════════════
function openATModal(data=null) {
  if(data){
    document.getElementById('atModalTitle').textContent = 'Edit Article Type';
    document.getElementById('atSaveBtn').textContent    = 'Update Article Type';
    document.getElementById('atId').value          = data.article_type_id;
    document.getElementById('atSpecialty').value   = data.specialty_id || '';
    document.getElementById('atName').value        = data.name || '';
    document.getElementById('atDescription').value = data.description || '';
    document.getElementById('atFee').value         = data.preliminary_fee_chf || 0;
    document.getElementById('atSummary').value     = data.summary_length || 350;
    document.getElementById('atFigures').value     = data.figures_tables_limit || 10;
    document.getElementById('atOrder').value       = data.display_order || 0;
  } else {
    document.getElementById('atModalTitle').textContent = 'Add Article Type';
    document.getElementById('atSaveBtn').textContent    = 'Save Article Type';
    document.getElementById('atId').value          = 0;
    document.getElementById('atSpecialty').value   = '';
    document.getElementById('atName').value        = '';
    document.getElementById('atDescription').value = '';
    document.getElementById('atFee').value         = 0;
    document.getElementById('atSummary').value     = 350;
    document.getElementById('atFigures').value     = 10;
    document.getElementById('atOrder').value       = 0;
  }
  document.getElementById('atModal').classList.remove('hidden');
  setTimeout(()=>document.getElementById('atName').focus(),100);
}
async function editAT(id) {
  const d = await fetch(`?ajax=get_article_type&id=${id}`).then(r=>r.json());
  openATModal(d);
}
function closeATModal() { document.getElementById('atModal').classList.add('hidden'); }
// toggleArticleType removed (no is_active column in article_types)
function deleteAT(id, name) {
  if(!confirm(`Delete article type "${name}"?`)) return;
  document.getElementById('delATId').value = id;
  document.getElementById('delATForm').submit();
}
</script>

</body>
</html>