<?php
// admin/journals.php — Journals & Categories Management (with SEO + Dynamic Sections)
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();

$msg = ''; $msgType = '';

// ══════════════════════════════════════════════════════
// HELPERS
// ══════════════════════════════════════════════════════
function handleUpload(string $field, string $subfolder = 'journals'): ?string {
    if (empty($_FILES[$field]['tmp_name'])) return null;
    $f = $_FILES[$field];
    $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) throw new Exception("Invalid image format for '$field'.");
    if ($f['size'] > 5*1024*1024) throw new Exception("Image too large (max 5 MB) for '$field'.");
    $dir = __DIR__ . "/../assets/images/$subfolder/";
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $name = uniqid('img_', true) . ".$ext";
    if (!move_uploaded_file($f['tmp_name'], $dir.$name)) throw new Exception("Upload failed for '$field'.");
    return "assets/images/$subfolder/$name";
}

function handleIndexedUpload(string $fieldPrefix, int $idx, string $subfolder): ?string {
    if (!isset($_FILES[$fieldPrefix]) || empty($_FILES[$fieldPrefix]['tmp_name'][$idx])) return null;
    $ext = strtolower(pathinfo($_FILES[$fieldPrefix]['name'][$idx], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) return null;
    if ($_FILES[$fieldPrefix]['size'][$idx] > 5*1024*1024) return null;
    $dir = __DIR__ . "/../assets/images/$subfolder/";
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $fname = uniqid('img_', true) . ".$ext";
    if (!move_uploaded_file($_FILES[$fieldPrefix]['tmp_name'][$idx], $dir.$fname)) return null;
    return "assets/images/$subfolder/$fname";
}

function makeSlug(string $s): string { return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($s)), '-'); }
function p($v): string { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

function syncCards(PDO $pdo, string $table, string $pkCol, int $journalId, array $post, array $files, string $subfolder): void {
    $ids = array_map('intval', (array)($post[$table.'_id'] ?? []));
    $titles = (array)($post[$table.'_title'] ?? []);
    $descs  = (array)($post[$table.'_desc']  ?? []);
    $links  = (array)($post[$table.'_link']  ?? []);
    $urls   = (array)($post[$table.'_url']   ?? []);
    $keepIds = array_values(array_filter($ids));
    if ($keepIds) {
        $ph = implode(',', array_fill(0, count($keepIds), '?'));
        $pdo->prepare("DELETE FROM `$table` WHERE journal_id=? AND `$pkCol` NOT IN ($ph)")->execute(array_merge([$journalId], $keepIds));
    } else {
        $pdo->prepare("DELETE FROM `$table` WHERE journal_id=?")->execute([$journalId]);
    }
    foreach ($titles as $i => $title) {
        $title = trim($title); if ($title === '') continue;
        $sid = (int)($ids[$i] ?? 0);
        $desc = trim($descs[$i] ?? ''); $link = trim($links[$i] ?? ''); $imgUrl = trim($urls[$i] ?? '');
        if (isset($files[$table.'_image']['tmp_name'][$i]) && !empty($files[$table.'_image']['tmp_name'][$i])) {
            try { $up = handleIndexedUpload($table.'_image', $i, $subfolder); if ($up) $imgUrl = $up; } catch(Exception $e) {}
        }
        if ($sid > 0)
            $pdo->prepare("UPDATE `$table` SET sort_order=?,title=?,description=?,image_url=?,link=? WHERE `$pkCol`=? AND journal_id=?")->execute([$i,$title,$desc,$imgUrl?:null,$link?:null,$sid,$journalId]);
        else
            $pdo->prepare("INSERT INTO `$table` (journal_id,sort_order,title,description,image_url,link) VALUES (?,?,?,?,?,?)")->execute([$journalId,$i,$title,$desc,$imgUrl?:null,$link?:null]);
    }
}

// ── Save per-journal sections helper ─────────────────────────
function saveSections(PDO $pdo, int $jid, array $payload): void {
    // Stats
    $pdo->prepare("DELETE FROM jl_stats WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_stats'] ?? []) as $i => $r) {
        if (empty($r['number'])) continue;
        $pdo->prepare("INSERT INTO jl_stats (journal_id,sort_order,number,label) VALUES (?,?,?,?)")->execute([$jid,$i,$r['number'],$r['label']??'']);
    }
    // Scope tags
    $pdo->prepare("DELETE FROM jl_scope_tags WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_scope_tags'] ?? []) as $i => $r) {
        if (empty($r['label'])) continue;
        $pdo->prepare("INSERT INTO jl_scope_tags (journal_id,sort_order,label,link_url) VALUES (?,?,?,?)")->execute([$jid,$i,$r['label'],$r['link_url']??null]);
    }
    // Steps
    $pdo->prepare("DELETE FROM jl_steps WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_steps'] ?? []) as $i => $r) {
        if (empty($r['title'])) continue;
        $pdo->prepare("INSERT INTO jl_steps (journal_id,sort_order,step_number,title,description) VALUES (?,?,?,?,?)")->execute([$jid,$i,$r['step_number']??($i+1),$r['title'],$r['description']??null]);
    }
    // Board
    $pdo->prepare("DELETE FROM jl_board WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_board'] ?? []) as $i => $r) {
        if (empty($r['name'])) continue;
        $initials = $r['initials'] ?? strtoupper(implode('', array_map(fn($w)=>$w[0], array_filter(explode(' ',$r['name'])))));
        $pdo->prepare("INSERT INTO jl_board (journal_id,sort_order,name,initials,role,institution) VALUES (?,?,?,?,?,?)")->execute([$jid,$i,$r['name'],$initials,$r['role']??null,$r['institution']??null]);
    }
    // Indexing
    $pdo->prepare("DELETE FROM jl_indexing WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_indexing'] ?? []) as $i => $r) {
        if (empty($r['label'])) continue;
        $pdo->prepare("INSERT INTO jl_indexing (journal_id,sort_order,label,badge) VALUES (?,?,?,?)")->execute([$jid,$i,$r['label'],$r['badge']??null]);
    }
    // Ethics
    $pdo->prepare("DELETE FROM jl_ethics WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_ethics'] ?? []) as $i => $r) {
        if (empty($r['title'])) continue;
        $pdo->prepare("INSERT INTO jl_ethics (journal_id,sort_order,title,description) VALUES (?,?,?,?)")->execute([$jid,$i,$r['title'],$r['description']??null]);
    }
    // Why
    $pdo->prepare("DELETE FROM jl_why WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_why'] ?? []) as $i => $r) {
        if (empty($r['title'])) continue;
        $pdo->prepare("INSERT INTO jl_why (journal_id,sort_order,title,description) VALUES (?,?,?,?)")->execute([$jid,$i,$r['title'],$r['description']??null]);
    }
    // Contact
    $pdo->prepare("DELETE FROM jl_contact WHERE journal_id=?")->execute([$jid]);
    foreach (($payload['jl_contact'] ?? []) as $i => $r) {
        if (empty($r['title'])) continue;
        $pdo->prepare("INSERT INTO jl_contact (journal_id,sort_order,title,description,link_text,link_url) VALUES (?,?,?,?,?,?)")->execute([$jid,$i,$r['title'],$r['description']??null,$r['link_text']??null,$r['link_url']??null]);
    }
    // Section headers
    foreach (($payload['headers'] ?? []) as $key => $hdr) {
        $pdo->prepare("INSERT INTO jl_section_headers (journal_id,section_key,eyebrow,title,description) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE eyebrow=VALUES(eyebrow),title=VALUES(title),description=VALUES(description)")
            ->execute([$jid,$key,$hdr['eyebrow']??null,$hdr['title']??null,$hdr['description']??null]);
    }
}

// ══════════════════════════════════════════════════════
// AJAX
// ══════════════════════════════════════════════════════
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');

    if ($_GET['ajax'] === 'get_journal' && isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $q = $pdo->prepare("SELECT * FROM journals WHERE journal_id=?"); $q->execute([$id]);
        $row = $q->fetch(PDO::FETCH_ASSOC) ?: [];
        $sq = $pdo->prepare("SELECT * FROM journal_sliders    WHERE journal_id=? ORDER BY sort_order"); $sq->execute([$id]); $row['sliders']    = $sq->fetchAll(PDO::FETCH_ASSOC);
        $iq = $pdo->prepare("SELECT * FROM journal_info_cards WHERE journal_id=? ORDER BY sort_order"); $iq->execute([$id]); $row['info_cards'] = $iq->fetchAll(PDO::FETCH_ASSOC);
        $nq = $pdo->prepare("SELECT * FROM journal_notices    WHERE journal_id=? ORDER BY sort_order"); $nq->execute([$id]); $row['notices']    = $nq->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($row); exit;
    }

    if ($_GET['ajax'] === 'get_journal_sections' && isset($_GET['id'])) {
        $jid = (int)$_GET['id'];
        $out = [];
        foreach (['jl_stats','jl_scope_tags','jl_steps','jl_board','jl_indexing','jl_ethics','jl_why','jl_contact'] as $t) {
            $q = $pdo->prepare("SELECT * FROM `$t` WHERE journal_id=? ORDER BY sort_order"); $q->execute([$jid]); $out[$t] = $q->fetchAll(PDO::FETCH_ASSOC);
        }
        $q = $pdo->prepare("SELECT * FROM jl_section_headers WHERE journal_id=?"); $q->execute([$jid]);
        foreach ($q->fetchAll(PDO::FETCH_ASSOC) as $h) $out['headers'][$h['section_key']] = $h;
        echo json_encode($out); exit;
    }

    if ($_GET['ajax'] === 'save_journal_sections') {
        $raw = json_decode(file_get_contents('php://input'), true) ?? [];
        $jid = (int)($raw['journal_id'] ?? 0);
        if (!$jid) { echo json_encode(['success'=>false,'error'=>'No journal ID']); exit; }
        try { saveSections($pdo, $jid, $raw); echo json_encode(['success'=>true]); }
        catch(Exception $e) { echo json_encode(['success'=>false,'error'=>$e->getMessage()]); }
        exit;
    }

    if ($_GET['ajax'] === 'get_category' && isset($_GET['id'])) {
        $q = $pdo->prepare("SELECT * FROM journal_categories WHERE category_id=?"); $q->execute([(int)$_GET['id']]);
        echo json_encode($q->fetch(PDO::FETCH_ASSOC) ?: []); exit;
    }
    if ($_GET['ajax'] === 'toggle_journal' && isset($_GET['id'])) {
        $pdo->prepare("UPDATE journals SET is_active=1-is_active WHERE journal_id=?")->execute([(int)$_GET['id']]);
        echo json_encode(['success'=>true]); exit;
    }
    exit;
}

// ══════════════════════════════════════════════════════
// POST: SAVE JOURNAL
// ══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_journal'])) {
    try {
        $journal_id  = (int)($_POST['journal_id'] ?? 0);
        $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
        $name        = trim($_POST['name'] ?? '');
        $slug        = trim($_POST['slug'] ?? '') ?: makeSlug($name);
        $description = trim($_POST['description'] ?? '');
        $is_active   = isset($_POST['is_active']) ? 1 : 0;
        $stat_citations = trim($_POST['stat_citations'] ?? '');
        $stat_hindex    = trim($_POST['stat_hindex']    ?? '');
        $stat_articles  = trim($_POST['stat_articles']  ?? '');
        $meta_title          = trim($_POST['meta_title']          ?? '');
        $meta_description    = trim($_POST['meta_description']    ?? '');
        $meta_keywords       = trim($_POST['meta_keywords']       ?? '');
        $canonical_url       = trim($_POST['canonical_url']       ?? '');
        $og_title            = trim($_POST['og_title']            ?? '');
        $og_description      = trim($_POST['og_description']      ?? '');
        $og_image            = trim($_POST['og_image']            ?? '');
        $og_type             = in_array($_POST['og_type']??'',['article','website','blog','profile']) ? $_POST['og_type'] : 'website';
        $twitter_card        = in_array($_POST['twitter_card']??'',['summary','summary_large_image','app']) ? $_POST['twitter_card'] : 'summary_large_image';
        $twitter_title       = trim($_POST['twitter_title']       ?? '');
        $twitter_description = trim($_POST['twitter_description'] ?? '');
        $twitter_image       = trim($_POST['twitter_image']       ?? '');
        $twitter_site        = trim($_POST['twitter_site']        ?? '');
        $schema_markup       = trim($_POST['schema_markup']       ?? '');
        $ai_summary          = trim($_POST['ai_summary']          ?? '');
        $focus_keyword       = trim($_POST['focus_keyword']       ?? '');
        $faqs_raw = trim($_POST['faqs'] ?? '[]');
        if (!json_decode($faqs_raw)) $faqs_raw = '[]';

        if (empty($name)) throw new Exception("Journal name is required.");
        if (empty($slug)) throw new Exception("Slug is required.");
        $chk = $pdo->prepare("SELECT journal_id FROM journals WHERE slug=? AND journal_id!=?"); $chk->execute([$slug,$journal_id]);
        if ($chk->fetch()) throw new Exception("Slug '$slug' already exists.");

        $cover = trim($_POST['cover_image_url'] ?? '');
        if (!empty($_FILES['cover_file']['tmp_name'])) $cover = handleUpload('cover_file');
        $bg = trim($_POST['bg_image_url'] ?? '');
        if (!empty($_FILES['bg_file']['tmp_name'])) $bg = handleUpload('bg_file', 'journals/bg');

        if ($journal_id > 0) {
            $pdo->prepare("UPDATE journals SET category_id=?,name=?,slug=?,description=?,cover_image_url=?,bg_image_url=?,stat_citations=?,stat_hindex=?,stat_articles=?,is_active=?,meta_title=?,meta_description=?,meta_keywords=?,canonical_url=?,og_title=?,og_description=?,og_image=?,og_type=?,twitter_card=?,twitter_title=?,twitter_description=?,twitter_image=?,twitter_site=?,schema_markup=?,ai_summary=?,faqs=?,focus_keyword=? WHERE journal_id=?")
                ->execute([$category_id,$name,$slug,$description,$cover?:null,$bg?:null,$stat_citations?:null,$stat_hindex?:null,$stat_articles?:null,$is_active,$meta_title?:null,$meta_description?:null,$meta_keywords?:null,$canonical_url?:null,$og_title?:null,$og_description?:null,$og_image?:null,$og_type,$twitter_card,$twitter_title?:null,$twitter_description?:null,$twitter_image?:null,$twitter_site?:null,$schema_markup?:null,$ai_summary?:null,$faqs_raw,$focus_keyword?:null,$journal_id]);
            $msg = "Journal '$name' updated.";
        } else {
            $pdo->prepare("INSERT INTO journals (category_id,name,slug,description,cover_image_url,bg_image_url,stat_citations,stat_hindex,stat_articles,is_active,created_at,meta_title,meta_description,meta_keywords,canonical_url,og_title,og_description,og_image,og_type,twitter_card,twitter_title,twitter_description,twitter_image,twitter_site,schema_markup,ai_summary,faqs,focus_keyword) VALUES (?,?,?,?,?,?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                ->execute([$category_id,$name,$slug,$description,$cover?:null,$bg?:null,$stat_citations?:null,$stat_hindex?:null,$stat_articles?:null,$is_active,$meta_title?:null,$meta_description?:null,$meta_keywords?:null,$canonical_url?:null,$og_title?:null,$og_description?:null,$og_image?:null,$og_type,$twitter_card,$twitter_title?:null,$twitter_description?:null,$twitter_image?:null,$twitter_site?:null,$schema_markup?:null,$ai_summary?:null,$faqs_raw,$focus_keyword?:null]);
            $journal_id = (int)$pdo->lastInsertId();
            $msg = "Journal '$name' created.";
        }

        $keepIds = array_values(array_filter(array_map('intval', (array)($_POST['slider_id'] ?? []))));
        if ($keepIds) { $ph=implode(',',array_fill(0,count($keepIds),'?')); $pdo->prepare("DELETE FROM journal_sliders WHERE journal_id=? AND slider_id NOT IN ($ph)")->execute(array_merge([$journal_id],$keepIds)); }
        else $pdo->prepare("DELETE FROM journal_sliders WHERE journal_id=?")->execute([$journal_id]);
        $sTitles=(array)($_POST['slider_title']??[]); $sDescs=(array)($_POST['slider_desc']??[]); $sBtnNames=(array)($_POST['slider_btn_name']??[]); $sBtnLinks=(array)($_POST['slider_btn_link']??[]); $sIds=(array)($_POST['slider_id']??[]);
        foreach ($sTitles as $i => $stitle) {
            $stitle=trim($stitle); if($stitle==='') continue;
            $sid=(int)($sIds[$i]??0);
            if($sid>0) $pdo->prepare("UPDATE journal_sliders SET sort_order=?,title=?,description=?,btn_name=?,btn_link=? WHERE slider_id=? AND journal_id=?")->execute([$i,trim($stitle),trim($sDescs[$i]??''),trim($sBtnNames[$i]??'')?:null,trim($sBtnLinks[$i]??'')?:null,$sid,$journal_id]);
            else $pdo->prepare("INSERT INTO journal_sliders (journal_id,sort_order,title,description,btn_name,btn_link) VALUES (?,?,?,?,?,?)")->execute([$journal_id,$i,trim($stitle),trim($sDescs[$i]??''),trim($sBtnNames[$i]??'')?:null,trim($sBtnLinks[$i]??'')?:null]);
        }
        syncCards($pdo,'journal_info_cards','card_id',$journal_id,$_POST,$_FILES,'journals/cards');
        syncCards($pdo,'journal_notices','notice_id',$journal_id,$_POST,$_FILES,'journals/notices');
        $msgType='success';
    } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}

// ══════════════════════════════════════════════════════
// POST: DELETE JOURNAL  ← FIXED
// ══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_journal'])) {
    $id = (int)$_POST['journal_id'];
    try {
        // Nullify journal_id on submissions so they are preserved but unlinked
        try {
            $pdo->prepare("UPDATE submissions SET journal_id=NULL WHERE journal_id=?")->execute([$id]);
        } catch(PDOException $e) {
            // submissions table may not exist — safe to ignore
        }

        foreach ([
            'journal_sliders','journal_info_cards','journal_notices',
            'jl_stats','jl_scope_tags','jl_steps','jl_board',
            'jl_indexing','jl_ethics','jl_why','jl_contact','jl_section_headers'
        ] as $t) {
            $pdo->prepare("DELETE FROM `$t` WHERE journal_id=?")->execute([$id]);
        }
        $pdo->prepare("DELETE FROM journals WHERE journal_id=?")->execute([$id]);
        $msg = "Journal deleted.";
        $msgType = 'success';
    } catch(PDOException $e) {
        $msg = "Delete failed: " . $e->getMessage();
        $msgType = 'error';
    }
}

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_category'])) {
    try {
        $category_id=(int)($_POST['category_id']??0); $name=trim($_POST['cat_name']??''); $display_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,$category_id]);
        if($chk->fetch()) throw new Exception("Category '$name' already exists.");
        if($category_id>0) $pdo->prepare("UPDATE journal_categories SET name=?,display_order=? WHERE category_id=?")->execute([$name,$display_order,$category_id]);
        else $pdo->prepare("INSERT INTO journal_categories (name,display_order) VALUES (?,?)")->execute([$name,$display_order]);
        $msg="Category saved."; $msgType='success';
    } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_category'])) {
    $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'; }
}

// ══════════════════════════════════════════════════════
// FETCH DATA
// ══════════════════════════════════════════════════════
$search=$_GET['search']??''; $filterCat=(int)($_GET['cat']??0); $filterStatus=$_GET['status']??'';
$whereClause="WHERE 1=1"; $params=[];
if($search){$whereClause.=" AND (j.name LIKE ? OR j.slug LIKE ? OR j.description LIKE ?)";$params[]="%$search%";$params[]="%$search%";$params[]="%$search%";}
if($filterCat>0){$whereClause.=" AND j.category_id=?";$params[]=$filterCat;}
if($filterStatus==='active') $whereClause.=" AND j.is_active=1";
elseif($filterStatus==='inactive') $whereClause.=" AND j.is_active=0";

$jStmt=$pdo->prepare("SELECT j.*,c.name AS category_name,
    (SELECT COUNT(*) FROM specialties sp WHERE sp.journal_id=j.journal_id) AS actual_specialty_count,
    (SELECT COUNT(*) FROM submissions sub WHERE sub.journal_id=j.journal_id) AS submission_count,
    (SELECT COUNT(*) FROM journal_sliders sl WHERE sl.journal_id=j.journal_id) AS slider_count,
    (SELECT COUNT(*) FROM journal_info_cards ic WHERE ic.journal_id=j.journal_id) AS info_card_count,
    (SELECT COUNT(*) FROM journal_notices jn WHERE jn.journal_id=j.journal_id) AS notice_count
    FROM journals j LEFT JOIN journal_categories c ON c.category_id=j.category_id
    $whereClause ORDER BY j.is_active DESC,c.display_order ASC,j.name ASC");
$jStmt->execute($params); $journals=$jStmt->fetchAll(PDO::FETCH_ASSOC);
$categories=$pdo->query("SELECT c.*,COUNT(j.journal_id) AS journal_count FROM journal_categories c LEFT JOIN journals j ON j.category_id=c.category_id GROUP BY c.category_id ORDER BY c.display_order ASC,c.name ASC")->fetchAll(PDO::FETCH_ASSOC);
$allStats=$pdo->query("SELECT is_active FROM journals")->fetchAll(PDO::FETCH_ASSOC);
$totalJournals=count($allStats);
$activeJournals=count(array_filter($allStats,fn($j)=>$j['is_active']));
$inactiveJournals=$totalJournals-$activeJournals;
$totalCats=count($categories);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Journals 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;}
  .modal-backdrop{background:rgba(0,0,0,.58);backdrop-filter:blur(3px);}
  input:focus,select:focus,textarea:focus{outline:none;}
  .badge{padding:2px 10px;border-radius:20px;font-size:11px;font-weight:600;display:inline-flex;align-items:center;gap:4px;}
  .modal-tab{padding:7px 14px;border-radius:8px;font-size:12.5px;font-weight:500;cursor:pointer;color:#64748b;border:none;background:transparent;transition:all .15s;white-space:nowrap;}
  .modal-tab.active{background:#eff6ff;color:#1d4ed8;font-weight:600;}
  .tab-panel{display:none;}.tab-panel.active{display:block;}
  .seo-tab{padding:6px 12px;border-radius:7px;font-size:11.5px;font-weight:500;cursor:pointer;color:#64748b;border:none;background:transparent;transition:all .15s;white-space:nowrap;border-bottom:2px solid transparent;}
  .seo-tab.active{background:#f0fdf4;color:#15803d;border-bottom-color:#22c55e;font-weight:600;}
  .seo-sub-panel{display:none;}.seo-sub-panel.active{display:block;}
  .sec-subtab{padding:6px 12px;border-radius:7px;font-size:11.5px;font-weight:500;cursor:pointer;color:#64748b;border:none;background:transparent;transition:all .15s;white-space:nowrap;border-bottom:2px solid transparent;}
  .sec-subtab.active{background:#fff7ed;color:#c2410c;border-bottom-color:#f97316;font-weight:600;}
  .sec-subpanel{display:none;}.sec-subpanel.active{display:block;}
  .rep-card{background:#f8faff;border:1px solid #dbeafe;border-radius:12px;padding:16px 16px 14px;position:relative;transition:box-shadow .15s;}
  .rep-card:hover{box-shadow:0 2px 12px rgba(59,130,246,.12);}
  .rep-card .rm-btn{position:absolute;top:10px;right:10px;width:26px;height:26px;border-radius:6px;border:1px solid #fecaca;background:#fff5f5;color:#ef4444;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:11px;transition:all .15s;}
  .rep-card .rm-btn:hover{background:#fee2e2;}
  .rep-card.notice-card{background:#fffbeb;border-color:#fde68a;}
  .rep-card.notice-card .rm-btn{border-color:#fde68a;background:#fffde7;color:#b45309;}
  .card-num{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:6px;font-size:11px;font-weight:700;}
  .card-num.blue{background:#dbeafe;color:#1d4ed8;}.card-num.amber{background:#fde68a;color:#92400e;}
  .upload-zone{border:2px dashed #cbd5e1;border-radius:10px;padding:16px;text-align:center;cursor:pointer;transition:all .2s;background:#fafafa;}
  .upload-zone:hover{border-color:#3b82f6;background:#f0f7ff;}
  .upload-zone.has-file{border-color:#93c5fd;background:#eff6ff;border-style:solid;}
  .mini-upload{border:2px dashed #e2e8f0;border-radius:8px;padding:10px;text-align:center;cursor:pointer;transition:all .2s;background:#fff;font-size:11px;color:#94a3b8;}
  .mini-upload:hover{border-color:#3b82f6;background:#f0f7ff;color:#3b82f6;}
  .mini-upload.has-file{border-color:#86efac;background:#f0fdf4;color:#16a34a;border-style:solid;}
  .stat-card{transition:box-shadow .2s,transform .2s;}.stat-card:hover{box-shadow:0 4px 20px rgba(0,0,0,.08);transform:translateY(-2px);}
  .journal-row{transition:background .15s;}.journal-row:hover{background:#f8faff;}
  #fab-create{position:fixed;bottom:28px;right:28px;z-index:200;width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,#2563eb,#1d4ed8);color:white;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:20px;box-shadow:0 4px 20px rgba(37,99,235,.5);transition:all .2s;}
  #fab-create:hover{transform:scale(1.1) rotate(90deg);}
  #fab-create .fab-tip{position:absolute;right:62px;white-space:nowrap;background:#1e293b;color:#fff;font-size:12px;font-weight:600;padding:5px 12px;border-radius:8px;opacity:0;pointer-events:none;transition:opacity .2s;}
  #fab-create:hover .fab-tip{opacity:1;}
  .btn-primary{background:linear-gradient(135deg,#2563eb,#1d4ed8);color:#fff;border:none;cursor:pointer;transition:all .2s;box-shadow:0 2px 8px rgba(37,99,235,.3);}
  .btn-primary:hover{box-shadow:0 4px 16px rgba(37,99,235,.45);transform:translateY(-1px);}
  .btn-amber{background:linear-gradient(135deg,#f59e0b,#d97706);color:#fff;border:none;cursor:pointer;transition:all .2s;}
  .btn-amber:hover{transform:translateY(-1px);}
  .btn-purple{background:linear-gradient(135deg,#7c3aed,#6d28d9);color:#fff;border:none;cursor:pointer;transition:all .2s;}
  .btn-purple:hover{transform:translateY(-1px);}
  #heroPreview{background:linear-gradient(135deg,#0f172a 0%,#1e3a5f 100%);}
  .img-thumb{width:56px;height:56px;border-radius:8px;overflow:hidden;border:2px solid #e5e7eb;flex-shrink:0;background:#f1f5f9;display:flex;align-items:center;justify-content:center;color:#94a3b8;}
  .img-thumb img{width:100%;height:100%;object-fit:cover;}
  .seo-result-row{padding:.75rem 1rem;display:flex;align-items:flex-start;gap:.75rem;border-bottom:1px solid #f1f5f9;}
  .seo-result-row:last-child{border-bottom:none;}
  .seo-icon{width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.65rem;flex-shrink:0;margin-top:1px;}
  .seo-icon.pass{background:#d1fae5;color:#059669;}.seo-icon.improve{background:#fef3c7;color:#d97706;}.seo-icon.fail{background:#fee2e2;color:#dc2626;}
  .seo-result-title{font-size:.75rem;font-weight:600;color:#374151;}
  .seo-result-detail{font-size:.7rem;color:#6b7280;margin-top:.15rem;line-height:1.5;}
  .seo-result-detail .found{color:#059669;font-weight:600;}.seo-result-detail .warn{color:#d97706;font-weight:600;}.seo-result-detail .bad{color:#dc2626;font-weight:600;}
  .seo-badge{font-size:.6rem;font-weight:700;padding:.12rem .45rem;border-radius:9999px;flex-shrink:0;}
  .badge-pass{background:#d1fae5;color:#065f46;}.badge-improve{background:#fef3c7;color:#92400e;}.badge-fail{background:#fee2e2;color:#991b1b;}
  .char-bar{height:4px;border-radius:2px;background:#e5e7eb;overflow:hidden;margin-top:4px;}
  .char-bar-fill{height:100%;border-radius:2px;transition:width .3s,background .3s;}
  .form-field{width:100%;border:1px solid #e2e8f0;border-radius:.5rem;padding:.55rem .75rem;font-size:.8rem;color:#374151;transition:border-color .15s,box-shadow .15s;background:#fff;}
  .form-field:focus{border-color:#3b82f6;box-shadow:0 0 0 2px rgba(59,130,246,.12);outline:none;}
  .faq-row-seo{background:#fffbeb;border:1px solid #fde68a;border-radius:10px;padding:12px;position:relative;}
  .faq-row-seo .faq-rm{position:absolute;top:8px;right:8px;width:22px;height:22px;background:#fef3c7;border:1px solid #fde68a;border-radius:5px;color:#b45309;display:flex;align-items:center;justify-content:center;font-size:10px;cursor:pointer;}
  .sec-row{background:#f8faff;border:1px solid #e2e8f0;border-radius:10px;padding:10px 12px;position:relative;margin-bottom:8px;}
  .sec-row .rm-sec{position:absolute;top:8px;right:8px;width:22px;height:22px;border-radius:5px;border:1px solid #fecaca;background:#fff5f5;color:#ef4444;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:10px;}
  .sec-row .rm-sec:hover{background:#fee2e2;}
  .sec-chip{display:inline-flex;align-items:center;gap:5px;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:6px;padding:4px 10px;font-size:12px;font-weight:500;color:#374151;margin:3px;}
  .sec-chip .rm-chip{cursor:pointer;color:#94a3b8;font-size:10px;}.sec-chip .rm-chip:hover{color:#ef4444;}
  .sec-hdr-field{width:100%;border:1px solid #e2e8f0;border-radius:6px;padding:5px 8px;font-size:11px;color:#374151;background:#fff;}
  .sec-hdr-field:focus{border-color:#3b82f6;outline:none;}
  .sec-board-avatar{width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,#0f2443,#2563eb);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:#fff;flex-shrink:0;}
</style>
</head>
<body class="bg-gray-50">
<?php include __DIR__ . '/include/sidebar.php'; ?>
<div class="content">

<div class="bg-white border-b border-gray-200 px-6 py-4 sticky top-0 z-10 shadow-sm" style="margin-top:50px;">
  <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-book-open text-blue-600"></i> Journals Management</h1>
      <p class="text-xs text-gray-400 mt-0.5">Manage journals, sliders, info cards, notices, categories &amp; page sections</p>
    </div>
    <div class="flex gap-2">
      <button onclick="openJournalModal()" class="btn-primary px-5 py-2 rounded-lg text-sm font-semibold flex items-center gap-2"><i class="fas fa-plus"></i> Create Journal</button>
    </div>
  </div>
</div>

<?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">
<div class="grid grid-cols-4 gap-4 mb-6">
  <?php foreach([['fa-book','bg-blue-100','text-blue-600',$totalJournals,'Total Journals'],['fa-check-circle','bg-green-100','text-green-600',$activeJournals,'Active'],['fa-pause-circle','bg-orange-100','text-orange-500',$inactiveJournals,'Inactive'],['fa-tags','bg-purple-100','text-purple-600',$totalCats,'Categories']] as [$icon,$bg,$tc,$val,$lbl]): ?>
  <div class="stat-card bg-white rounded-xl border border-gray-200 p-5 flex items-center gap-4">
    <div class="w-11 h-11 rounded-xl <?=$bg?> flex items-center justify-center"><i class="fas <?=$icon?> <?=$tc?> text-lg"></i></div>
    <div><div class="text-2xl font-bold text-gray-800"><?=$val?></div><div class="text-xs text-gray-400"><?=$lbl?></div></div>
  </div>
  <?php endforeach; ?>
</div>

<form method="GET" class="bg-white rounded-xl border border-gray-200 p-4 mb-5 flex flex-wrap gap-3 items-end">
  <div class="flex-1 min-w-[200px]">
    <label class="block text-xs font-semibold text-gray-500 mb-1">Search</label>
    <div class="relative"><i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
    <input type="text" name="search" value="<?=p($search)?>" placeholder="Journal name or slug..." class="w-full border border-gray-200 rounded-lg pl-8 pr-3 py-2 text-sm focus:ring-2 focus:ring-blue-500"></div>
  </div>
  <div><label class="block text-xs font-semibold text-gray-500 mb-1">Category</label>
    <select name="cat" class="border border-gray-200 rounded-lg px-3 py-2 text-sm"><option value="">All Categories</option><?php foreach($categories as $c): ?><option value="<?=$c['category_id']?>" <?=$filterCat==$c['category_id']?'selected':''?>><?=p($c['name'])?> (<?=$c['journal_count']?>)</option><?php endforeach; ?></select></div>
  <div><label class="block text-xs font-semibold text-gray-500 mb-1">Status</label>
    <select name="status" class="border border-gray-200 rounded-lg px-3 py-2 text-sm"><option value="">All</option><option value="active" <?=$filterStatus==='active'?'selected':''?>>Active</option><option value="inactive" <?=$filterStatus==='inactive'?'selected':''?>>Inactive</option></select></div>
  <button type="submit" class="btn-primary px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-1.5"><i class="fas fa-filter text-xs"></i> Filter</button>
  <?php if($search||$filterCat||$filterStatus): ?><a href="journals.php" class="border border-gray-300 text-gray-500 px-4 py-2 rounded-lg text-sm hover:bg-gray-50 flex items-center gap-1.5"><i class="fas fa-times text-xs"></i> Clear</a><?php endif; ?>
  <div class="ml-auto"><button type="button" onclick="openJournalModal()" class="btn-primary px-4 py-2 rounded-lg text-sm font-semibold flex items-center gap-2"><i class="fas fa-plus text-xs"></i> Create Journal</button></div>
</form>

<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
  <div class="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
    <h2 class="font-semibold text-gray-800">Journals <span class="ml-2 text-xs font-normal text-gray-400"><?=count($journals)?> result<?=count($journals)!==1?'s':''?></span></h2>
    <span class="text-xs text-gray-400 italic">Hover row for actions</span>
  </div>
  <?php if(empty($journals)): ?>
  <div class="text-center py-16 text-gray-400">
    <div class="w-16 h-16 rounded-2xl bg-blue-50 flex items-center justify-center mx-auto mb-4"><i class="fas fa-book-open text-blue-300 text-2xl"></i></div>
    <p class="text-base font-medium text-gray-500 mb-1">No journals found</p>
    <p class="text-sm text-gray-400 mb-4"><?=($search||$filterCat||$filterStatus)?'Try adjusting your filters.':'Get started by creating your first journal.'?></p>
    <?php if(!$search&&!$filterCat&&!$filterStatus): ?><button onclick="openJournalModal()" class="btn-primary px-5 py-2.5 rounded-lg text-sm font-semibold inline-flex items-center gap-2 mx-auto"><i class="fas fa-plus text-xs"></i> Create Your First Journal</button><?php endif; ?>
  </div>
  <?php else: ?>
  <div class="overflow-x-auto">
  <table class="w-full text-sm">
    <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
      <tr>
        <th class="px-4 py-3 text-left w-8">#</th><th class="px-4 py-3 text-left">Journal</th><th class="px-4 py-3 text-left">Category</th>
        <th class="px-4 py-3 text-center">Specs</th><th class="px-4 py-3 text-center">Subs</th><th class="px-4 py-3 text-center">Slides</th>
        <th class="px-4 py-3 text-center">Cards</th><th class="px-4 py-3 text-center">Notices</th><th class="px-4 py-3 text-center">Stats</th>
        <th class="px-4 py-3 text-center">SEO</th><th class="px-4 py-3 text-center">Status</th><th class="px-4 py-3 text-left">Created</th><th class="px-4 py-3 text-right">Actions</th>
      </tr>
    </thead>
    <tbody class="divide-y divide-gray-50">
    <?php foreach($journals as $j):
      $seoFields=['meta_title','meta_description','meta_keywords','og_title','schema_markup','ai_summary'];
      $seoFilled=count(array_filter($seoFields,fn($f)=>!empty($j[$f])));
      $seoPct=round(($seoFilled/count($seoFields))*100);
      $seoColor=$seoPct>=80?'text-green-600 bg-green-50':($seoPct>=40?'text-yellow-600 bg-yellow-50':'text-red-500 bg-red-50');
    ?>
    <tr class="journal-row">
      <td class="px-4 py-3 text-gray-400 font-mono text-xs"><?=$j['journal_id']?></td>
      <td class="px-4 py-3">
        <div class="flex items-center gap-3">
          <?php if(!empty($j['cover_image_url'])): ?>
          <div class="w-10 h-10 rounded-lg overflow-hidden border border-gray-100 flex-shrink-0"><img src="/<?=p(ltrim($j['cover_image_url'],'/'))?>" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" class="w-full h-full object-cover"><div class="w-full h-full bg-blue-100 hidden items-center justify-center"><i class="fas fa-book text-blue-400 text-xs"></i></div></div>
          <?php else: ?><div class="w-10 h-10 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0 border border-blue-100"><i class="fas fa-book text-blue-400 text-sm"></i></div><?php endif; ?>
          <div><div class="font-semibold text-gray-800"><?=p($j['name'])?></div><div class="text-xs text-gray-400 font-mono mt-0.5">/<?=p($j['slug'])?></div></div>
        </div>
      </td>
      <td class="px-4 py-3"><?php if($j['category_name']): ?><span class="badge bg-purple-50 text-purple-700"><i class="fas fa-tag text-[10px]"></i><?=p($j['category_name'])?></span><?php else: ?><span class="badge bg-gray-100 text-gray-400"><i class="fas fa-tag text-[10px]"></i>All</span><?php endif; ?></td>
      <td class="px-4 py-3 text-center font-semibold text-gray-700"><?=$j['actual_specialty_count']?></td>
      <td class="px-4 py-3 text-center"><?php if($j['submission_count']>0): ?><a href="submissions.php?journal=<?=$j['journal_id']?>" class="font-semibold text-blue-600 hover:underline"><?=$j['submission_count']?></a><?php else: ?><span class="text-gray-300">0</span><?php endif; ?></td>
      <td class="px-4 py-3 text-center"><span class="badge <?=$j['slider_count']>0?'bg-blue-50 text-blue-600':'bg-gray-100 text-gray-400'?>"><i class="fas fa-layer-group text-[10px]"></i><?=$j['slider_count']?></span></td>
      <td class="px-4 py-3 text-center"><span class="badge <?=$j['info_card_count']>0?'bg-indigo-50 text-indigo-600':'bg-gray-100 text-gray-400'?>"><i class="fas fa-th-large text-[10px]"></i><?=$j['info_card_count']?></span></td>
      <td class="px-4 py-3 text-center"><span class="badge <?=$j['notice_count']>0?'bg-amber-50 text-amber-600':'bg-gray-100 text-gray-400'?>"><i class="fas fa-bell text-[10px]"></i><?=$j['notice_count']?></span></td>
      <td class="px-4 py-3 text-center"><?php $hasStats=$j['stat_citations']||$j['stat_hindex']||$j['stat_articles']; if($hasStats): ?><span class="badge bg-teal-50 text-teal-700"><i class="fas fa-chart-line text-[10px]"></i>Set</span><?php else: ?><span class="text-gray-300 text-xs">—</span><?php endif; ?></td>
      <td class="px-4 py-3 text-center"><span class="badge <?=$seoColor?>" title="SEO: <?=$seoPct?>%"><i class="fas fa-search text-[10px]"></i><?=$seoPct?>%</span></td>
      <td class="px-4 py-3 text-center">
        <button onclick="toggleActive(<?=$j['journal_id']?>,this)" class="badge <?=$j['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 <?=$j['is_active']?'bg-green-500':'bg-gray-400'?>"></span><?=$j['is_active']?'Active':'Inactive'?>
        </button>
      </td>
      <td class="px-4 py-3 text-xs text-gray-400"><?php if(!empty($j['created_at'])): ?><div><?=date('d M',strtotime($j['created_at']))?></div><div><?=date('Y',strtotime($j['created_at']))?></div><?php else: ?>—<?php endif; ?></td>
      <td class="px-4 py-3 text-right">
        <div class="flex items-center justify-end gap-2">
          <button onclick="editJournal(<?=$j['journal_id']?>)" class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-blue-50 hover:text-blue-600 hover:border-blue-200 transition" title="Edit"><i class="fas fa-edit text-xs"></i></button>
          <button onclick="deleteJournal(<?=$j['journal_id']?>,'<?=p($j['name'])?>')" class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-red-50 hover:text-red-600 hover:border-red-200 transition" title="Delete"><i class="fas fa-trash text-xs"></i></button>
        </div>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>
</div>
</div>

<!-- Single FAB button (duplicate removed) -->
<button id="fab-create" onclick="openJournalModal()"><span class="fab-tip">Create Journal</span><i class="fas fa-plus"></i></button>

<!-- ══════════════════════════════════════════════════════
     JOURNAL MODAL
══════════════════════════════════════════════════════ -->
<div id="journalModal" class="fixed inset-0 modal-backdrop hidden z-50 flex items-center justify-center p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[92vh] overflow-hidden flex flex-col">
    <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between flex-shrink-0">
      <h2 class="font-bold text-gray-800 text-lg flex items-center gap-2" id="journalModalTitle"><i class="fas fa-book-open text-blue-500"></i> Create New Journal</h2>
      <button onclick="closeJournalModal()" class="text-gray-400 hover:text-red-500 w-8 h-8 rounded-lg hover:bg-red-50 flex items-center justify-center transition" title="Close"><i class="fas fa-times"></i></button>
    </div>

    <div class="px-4 pt-3 pb-0 border-b border-gray-100 flex gap-1 flex-shrink-0 overflow-x-auto">
      <button class="modal-tab active" onclick="switchTab('basic')"     id="tab-basic">    <i class="fas fa-info-circle mr-1 text-xs"></i>Basic</button>
      <button class="modal-tab"        onclick="switchTab('images')"    id="tab-images">   <i class="fas fa-image mr-1 text-xs"></i>Images</button>
      <button class="modal-tab"        onclick="switchTab('stats')"     id="tab-stats">    <i class="fas fa-chart-bar mr-1 text-xs"></i>Stats</button>
      <button class="modal-tab"        onclick="switchTab('sliders')"   id="tab-sliders">  <i class="fas fa-layer-group mr-1 text-xs"></i>Sliders</button>
      <button class="modal-tab"        onclick="switchTab('infocards')" id="tab-infocards"><i class="fas fa-th-large mr-1 text-xs"></i>Info Cards</button>
      <button class="modal-tab"        onclick="switchTab('notices')"   id="tab-notices">  <i class="fas fa-bell mr-1 text-xs"></i>Notices</button>
      <button class="modal-tab"        onclick="switchTab('seo')"       id="tab-seo">      <i class="fas fa-search mr-1 text-xs text-green-600"></i>SEO</button>
      <button class="modal-tab"        onclick="switchTab('sections')"  id="tab-sections"> <i class="fas fa-layer-group mr-1 text-xs text-orange-500"></i>Sections</button>
    </div>

    <form method="POST" id="journalForm" enctype="multipart/form-data" class="flex-1 overflow-y-auto flex flex-col">
      <input type="hidden" name="save_journal" value="1">
      <input type="hidden" name="journal_id" id="journalId" value="0">
      <div class="p-6 flex-1">

        <!-- BASIC -->
        <div id="panel-basic" class="tab-panel active space-y-5">
          <div class="grid grid-cols-2 gap-4">
            <div><label class="block text-xs font-semibold text-gray-600 mb-1.5">Journal Name <span class="text-red-500">*</span></label>
              <input type="text" name="name" id="jName" required placeholder="e.g. Frontiers in Acoustics" oninput="autoSlug();syncPreviewName();" class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-blue-500"></div>
            <div><label class="block text-xs font-semibold text-gray-600 mb-1.5">Slug <span class="text-red-500">*</span></label>
              <input type="text" name="slug" id="jSlug" required placeholder="frontiers-in-acoustics" class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm font-mono focus:ring-2 focus:ring-blue-500"></div>
          </div>
          <div><label class="block text-xs font-semibold text-gray-600 mb-1.5">Category</label>
            <select name="category_id" id="jCategory" class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-blue-500"><option value="">— No category —</option><?php foreach($categories as $c): ?><option value="<?=$c['category_id']?>"><?=p($c['name'])?></option><?php endforeach; ?></select></div>
          <div><label class="block text-xs font-semibold text-gray-600 mb-1.5">Description</label>
            <textarea name="description" id="jDescription" rows="3" placeholder="A brief description..." class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm resize-none focus:ring-2 focus:ring-blue-500"></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="jActive" value="1" checked class="sr-only peer"><div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-blue-100 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div></label>
            <div><div class="text-sm font-medium text-gray-700">Active</div><div class="text-xs text-gray-400">Visible to authors during submission</div></div>
          </div>
        </div>

        <!-- IMAGES -->
        <div id="panel-images" class="tab-panel space-y-7">
          <div>
            <div class="flex items-center gap-2 mb-2"><div class="w-6 h-6 rounded-md bg-blue-100 flex items-center justify-center"><i class="fas fa-image text-blue-500 text-xs"></i></div><label class="text-xs font-semibold text-gray-700">Cover / Thumbnail Image</label></div>
            <div class="flex gap-4 items-start">
              <div class="flex-1 space-y-2">
                <div class="upload-zone" id="coverZone" onclick="document.getElementById('coverFile').click()"><i class="fas fa-cloud-upload-alt text-3xl text-blue-300 mb-2 block"></i><p class="text-sm font-medium text-gray-500">Click to upload cover image</p><p class="text-xs text-gray-400 mt-1">JPG · PNG · WEBP · Max 5 MB</p></div>
                <input type="file" id="coverFile" name="cover_file" accept="image/*" class="hidden" onchange="handleFileUpload(this,'coverPreview','coverZone','jCoverUrl')">
                <div class="relative"><span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-medium">URL</span><input type="text" name="cover_image_url" id="jCoverUrl" placeholder="assets/images/journals/name.jpg" oninput="previewFromUrl(this.value,'coverPreview')" class="w-full border border-gray-200 rounded-lg pl-10 pr-3 py-2 text-xs font-mono focus:ring-2 focus:ring-blue-500"></div>
              </div>
              <div id="coverPreview" class="w-24 h-24 rounded-xl border-2 border-dashed border-gray-200 flex items-center justify-center text-gray-300 flex-shrink-0 overflow-hidden bg-gray-50"><i class="fas fa-image text-2xl"></i></div>
            </div>
          </div>
          <hr class="border-gray-100">
          <div>
            <div class="flex items-center gap-2 mb-2"><div class="w-6 h-6 rounded-md bg-teal-100 flex items-center justify-center"><i class="fas fa-panorama text-teal-500 text-xs"></i></div><label class="text-xs font-semibold text-gray-700">Hero Background Image</label></div>
            <div class="flex gap-4 items-start">
              <div class="flex-1 space-y-2">
                <div class="upload-zone" id="bgZone" onclick="document.getElementById('bgFile').click()"><i class="fas fa-cloud-upload-alt text-3xl text-teal-300 mb-2 block"></i><p class="text-sm font-medium text-gray-500">Click to upload hero background</p><p class="text-xs text-gray-400 mt-1">Recommended 1920×500 px · Max 5 MB</p></div>
                <input type="file" id="bgFile" name="bg_file" accept="image/*" class="hidden" onchange="handleFileUpload(this,'bgPreview','bgZone','jBgUrl')">
                <div class="relative"><span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-medium">URL</span><input type="text" name="bg_image_url" id="jBgUrl" placeholder="assets/images/journals/bg/name.jpg" oninput="previewFromUrl(this.value,'bgPreview')" class="w-full border border-gray-200 rounded-lg pl-10 pr-3 py-2 text-xs font-mono focus:ring-2 focus:ring-blue-500"></div>
              </div>
              <div id="bgPreview" class="w-36 h-20 rounded-xl border-2 border-dashed border-gray-200 flex items-center justify-center text-gray-300 flex-shrink-0 overflow-hidden bg-gray-50"><i class="fas fa-panorama text-2xl"></i></div>
            </div>
          </div>
        </div>

        <!-- STATS -->
        <div id="panel-stats" class="tab-panel space-y-5">
          <div class="bg-teal-50 border border-teal-100 rounded-xl p-3 flex items-start gap-2"><i class="fas fa-info-circle text-teal-500 mt-0.5"></i><p class="text-xs text-teal-700">These numbers appear in the <strong>hero section</strong> alongside the Submit button.</p></div>
          <div id="heroPreview" class="rounded-xl p-5 flex items-center justify-between gap-4 overflow-hidden relative">
            <div class="absolute inset-0 opacity-20 bg-gradient-to-br from-teal-700 to-blue-900 pointer-events-none"></div>
            <div class="relative z-10 text-white min-w-0"><div class="text-[10px] uppercase tracking-widest opacity-60 mb-1">Preview</div><div class="text-base font-bold leading-snug truncate max-w-xs" id="prev_jname">Journal Name</div></div>
            <div class="relative z-10 flex items-center gap-5 flex-shrink-0">
              <div class="text-center text-white"><div class="text-2xl font-bold leading-none" id="prev_cit">—</div><div class="text-[10px] opacity-70 mt-1">Citations</div></div>
              <div class="text-center text-white"><div class="text-2xl font-bold leading-none" id="prev_hi">—</div><div class="text-[10px] opacity-70 mt-1">H-Index</div></div>
              <div class="text-center text-white"><div class="text-2xl font-bold leading-none" id="prev_art">—</div><div class="text-[10px] opacity-70 mt-1">Published Articles</div></div>
              <div class="w-20 h-9 rounded-lg bg-blue-500 flex items-center justify-center text-white text-xs font-semibold">Submit →</div>
            </div>
          </div>
          <div class="grid grid-cols-3 gap-4">
            <div><label class="block text-xs font-semibold text-gray-600 mb-1.5">Citations</label><input type="text" name="stat_citations" id="jStatCitations" placeholder="e.g. 3,901" oninput="document.getElementById('prev_cit').textContent=this.value.trim()||'—'" class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-blue-500"></div>
            <div><label class="block text-xs font-semibold text-gray-600 mb-1.5">H-Index</label><input type="text" name="stat_hindex" id="jStatHindex" placeholder="e.g. 25" oninput="document.getElementById('prev_hi').textContent=this.value.trim()||'—'" class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-blue-500"></div>
            <div><label class="block text-xs font-semibold text-gray-600 mb-1.5">Published Articles</label><input type="text" name="stat_articles" id="jStatArticles" placeholder="e.g. 5,094+" oninput="document.getElementById('prev_art').textContent=this.value.trim()||'—'" class="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-blue-500"></div>
          </div>
        </div>

        <!-- SLIDERS -->
        <div id="panel-sliders" class="tab-panel">
          <div class="flex items-center justify-between mb-4"><div><h3 class="font-semibold text-gray-800 text-sm">Hero Sliders</h3><p class="text-xs text-gray-400 mt-0.5">Each slide: title, description, optional CTA button.</p></div><button type="button" onclick="addRepCard('sliders','blue')" class="btn-primary px-4 py-2 rounded-lg text-xs font-semibold flex items-center gap-1.5"><i class="fas fa-plus text-xs"></i> Add Slide</button></div>
          <div id="list-sliders" class="space-y-3"></div>
          <div id="empty-sliders" class="text-center py-10 border-2 border-dashed border-gray-200 rounded-xl text-gray-400"><i class="fas fa-layer-group text-3xl mb-3 opacity-20 block"></i><p class="text-sm font-medium">No slides yet</p></div>
        </div>

        <!-- INFO CARDS -->
        <div id="panel-infocards" class="tab-panel">
          <div class="flex items-center justify-between mb-4"><div><h3 class="font-semibold text-gray-800 text-sm flex items-center gap-2"><i class="fas fa-th-large text-indigo-500"></i> Info Cards</h3><p class="text-xs text-gray-400 mt-0.5">Cards like "Submit your paper", "Editorial process".</p></div><button type="button" onclick="addRepCard('infocards','blue')" class="btn-primary px-4 py-2 rounded-lg text-xs font-semibold flex items-center gap-1.5"><i class="fas fa-plus text-xs"></i> Add Card</button></div>
          <div id="list-infocards" class="space-y-3"></div>
          <div id="empty-infocards" class="text-center py-10 border-2 border-dashed border-gray-200 rounded-xl text-gray-400"><i class="fas fa-th-large text-3xl mb-3 opacity-20 block"></i><p class="text-sm font-medium">No info cards yet</p></div>
        </div>

        <!-- NOTICES -->
        <div id="panel-notices" class="tab-panel">
          <div class="flex items-center justify-between mb-4"><div><h3 class="font-semibold text-gray-800 text-sm flex items-center gap-2"><i class="fas fa-bell text-amber-500"></i> Journal Notices</h3><p class="text-xs text-gray-400 mt-0.5">Cards like "Call for papers", "Launch your special issue".</p></div><button type="button" onclick="addRepCard('notices','amber')" class="btn-amber px-4 py-2 rounded-lg text-xs font-semibold flex items-center gap-1.5"><i class="fas fa-plus text-xs"></i> Add Notice</button></div>
          <div id="list-notices" class="space-y-3"></div>
          <div id="empty-notices" class="text-center py-10 border-2 border-dashed border-amber-200 rounded-xl text-amber-400"><i class="fas fa-bell text-3xl mb-3 opacity-20 block"></i><p class="text-sm font-medium">No notices yet</p></div>
        </div>

        <!-- SEO -->
        <div id="panel-seo" class="tab-panel">
          <div class="bg-green-50 border border-green-200 rounded-xl p-3 mb-4">
            <div class="flex items-center gap-2 mb-1"><i class="fas fa-key text-green-600 text-xs"></i><label class="text-xs font-semibold text-green-800">Focus Keyword</label></div>
            <div class="flex gap-2"><input type="text" name="focus_keyword" id="jFocusKeyword" placeholder="e.g. social science research journal" class="flex-1 form-field text-xs" oninput="scheduleAnalysis()"><button type="button" onclick="runJournalSeoAnalysis()" class="btn-purple px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 flex-shrink-0"><i class="fas fa-sync-alt text-xs" id="seoAnalyseIcon"></i> Analyse</button></div>
          </div>
          <div class="flex gap-1 border-b border-gray-100 mb-4 overflow-x-auto">
            <button type="button" class="seo-tab active" onclick="switchSeoTab('seo-core')" id="stab-seo-core"><i class="fas fa-tag mr-1 text-xs text-green-500"></i>Core SEO</button>
            <button type="button" class="seo-tab" onclick="switchSeoTab('seo-social')" id="stab-seo-social"><i class="fas fa-share-alt mr-1 text-xs text-blue-500"></i>Social/OG</button>
            <button type="button" class="seo-tab" onclick="switchSeoTab('seo-schema')" id="stab-seo-schema"><i class="fas fa-code mr-1 text-xs text-purple-500"></i>Schema</button>
            <button type="button" class="seo-tab" onclick="switchSeoTab('seo-ai')" id="stab-seo-ai"><i class="fas fa-robot mr-1 text-xs text-indigo-500"></i>AI Seed</button>
            <button type="button" class="seo-tab" onclick="switchSeoTab('seo-faq')" id="stab-seo-faq"><i class="fas fa-question-circle mr-1 text-xs text-orange-500"></i>FAQs</button>
            <button type="button" class="seo-tab" onclick="switchSeoTab('seo-analysis')" id="stab-seo-analysis"><i class="fas fa-microscope mr-1 text-xs text-pink-500"></i>Analysis</button>
          </div>
          <div id="panel-seo-core" class="seo-sub-panel active space-y-4">
            <div><div class="flex justify-between items-center mb-1"><label class="text-xs font-semibold text-gray-600">Meta Title</label><span class="text-xs text-gray-400"><span id="seoMetaTitleCount">0</span>/70 | ideal 50–60</span></div><input type="text" name="meta_title" id="jMetaTitle" maxlength="70" placeholder="Leave blank to use journal name" oninput="bindSeoCounter(this,'seoMetaTitleCount','seoMetaTitleBar',70,50,60);scheduleAnalysis()" class="form-field"><div class="char-bar mt-1"><div id="seoMetaTitleBar" class="char-bar-fill" style="width:0%"></div></div></div>
            <div><div class="flex justify-between items-center mb-1"><label class="text-xs font-semibold text-gray-600">Meta Description</label><span class="text-xs text-gray-400"><span id="seoMetaDescCount">0</span>/320 | ideal 150–160</span></div><textarea name="meta_description" id="jMetaDesc" maxlength="320" rows="2" placeholder="Concise summary for search engines…" oninput="bindSeoCounter(this,'seoMetaDescCount','seoMetaDescBar',320,150,160);scheduleAnalysis()" class="form-field resize-none"></textarea><div class="char-bar mt-1"><div id="seoMetaDescBar" class="char-bar-fill" style="width:0%"></div></div></div>
            <div><div class="flex justify-between items-center mb-1"><label class="text-xs font-semibold text-gray-600">Meta Keywords</label><span class="text-xs text-gray-400"><span id="seoMetaKwCount">0</span>/500</span></div><input type="text" name="meta_keywords" id="jMetaKeywords" maxlength="500" placeholder="social science, open access, peer review" oninput="bindSeoCounter(this,'seoMetaKwCount',null,500,0,255);scheduleAnalysis()" class="form-field"></div>
            <div><label class="text-xs font-semibold text-gray-600 mb-1 block">Canonical URL</label><input type="url" name="canonical_url" id="jCanonicalUrl" placeholder="https://yoursite.com/journals/slug" class="form-field"></div>
            <div class="bg-gray-50 border border-gray-200 rounded-xl p-3"><p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2"><i class="fab fa-google mr-1"></i>SERP Preview</p><div class="bg-white border border-gray-200 rounded-lg p-3"><div class="text-xs text-green-700 mb-1 font-mono">yoursite.com/journals/<span id="serpJSlug">slug</span></div><div id="serpJTitle" class="text-blue-700 text-sm font-medium leading-tight mb-1">Journal Name</div><div id="serpJDesc" class="text-xs text-gray-600">Meta description will appear here…</div></div></div>
          </div>
          <div id="panel-seo-social" class="seo-sub-panel space-y-4">
            <div class="grid grid-cols-2 gap-4"><div><div class="flex justify-between mb-1"><label class="text-xs font-semibold text-gray-600">OG Title</label><span class="text-xs text-gray-400"><span id="seoOgTitleCount">0</span>/200</span></div><input type="text" name="og_title" id="jOgTitle" maxlength="200" placeholder="Leave blank to use Meta Title" oninput="bindSeoCounter(this,'seoOgTitleCount',null,200,0,60)" class="form-field"></div><div><label class="text-xs font-semibold text-gray-600 mb-1 block">OG Type</label><select name="og_type" id="jOgType" class="form-field"><option value="website">Website</option><option value="article">Article</option><option value="blog">Blog</option><option value="profile">Profile</option></select></div></div>
            <div><div class="flex justify-between mb-1"><label class="text-xs font-semibold text-gray-600">OG Description</label><span class="text-xs text-gray-400"><span id="seoOgDescCount">0</span>/300</span></div><textarea name="og_description" id="jOgDesc" maxlength="300" rows="2" placeholder="Leave blank to use Meta Description" oninput="bindSeoCounter(this,'seoOgDescCount',null,300,0,200)" class="form-field resize-none"></textarea></div>
            <div><label class="text-xs font-semibold text-gray-600 mb-1 block">OG Image URL</label><input type="url" name="og_image" id="jOgImage" placeholder="Leave blank to use Cover Image" class="form-field"></div>
            <div class="grid grid-cols-2 gap-4"><div><label class="text-xs font-semibold text-gray-600 mb-1 block">Twitter Card</label><select name="twitter_card" id="jTwitterCard" class="form-field"><option value="summary_large_image">Summary Large Image</option><option value="summary">Summary</option><option value="app">App</option></select></div><div><label class="text-xs font-semibold text-gray-600 mb-1 block">Twitter Handle</label><input type="text" name="twitter_site" id="jTwitterSite" placeholder="@YourHandle" class="form-field"></div></div>
            <div><label class="text-xs font-semibold text-gray-600 mb-1 block">Twitter Title</label><input type="text" name="twitter_title" id="jTwitterTitle" maxlength="200" placeholder="Leave blank to use OG/Meta Title" class="form-field"></div>
            <div><label class="text-xs font-semibold text-gray-600 mb-1 block">Twitter Description</label><textarea name="twitter_description" id="jTwitterDesc" maxlength="300" rows="2" placeholder="Leave blank to use OG/Meta Description" class="form-field resize-none"></textarea></div>
            <div><label class="text-xs font-semibold text-gray-600 mb-1 block">Twitter Image URL</label><input type="url" name="twitter_image" id="jTwitterImage" placeholder="Leave blank to use OG Image" class="form-field"></div>
          </div>
          <div id="panel-seo-schema" class="seo-sub-panel space-y-3">
            <div class="flex items-center justify-between"><div><h4 class="text-xs font-semibold text-gray-700">JSON-LD Structured Data</h4></div><div class="flex gap-1.5"><button type="button" onclick="insertJournalSchema('website')" class="text-xs bg-purple-50 text-purple-700 border border-purple-200 px-2 py-1 rounded-lg font-medium">+WebSite</button><button type="button" onclick="insertJournalSchema('org')" class="text-xs bg-blue-50 text-blue-700 border border-blue-200 px-2 py-1 rounded-lg font-medium">+Org</button><button type="button" onclick="insertJournalSchema('faqpage')" class="text-xs bg-orange-50 text-orange-700 border border-orange-200 px-2 py-1 rounded-lg font-medium">+FAQ</button></div></div>
            <textarea name="schema_markup" id="jSchema" rows="10" placeholder='{"@context":"https://schema.org",...}' class="form-field font-mono text-xs resize-y" style="line-height:1.6"></textarea>
            <div class="flex items-center gap-3"><button type="button" onclick="validateJournalSchema()" class="text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-1.5 rounded-lg font-medium flex items-center gap-1 transition"><i class="fas fa-check-circle text-green-600"></i> Validate JSON</button><span id="schemaValidMsgJ" class="text-xs hidden"></span></div>
          </div>
          <div id="panel-seo-ai" class="seo-sub-panel space-y-4">
            <div><div class="flex justify-between mb-1"><label class="text-xs font-semibold text-gray-600">AI Summary / LLM Seed Text</label><span class="text-xs text-gray-400"><span id="seoAiWordCount">0</span> words | ideal 100–300</span></div><textarea name="ai_summary" id="jAiSummary" rows="5" placeholder="Write a clear, factual summary for AI search engines..." oninput="updateWordCount(this,'seoAiWordCount')" class="form-field resize-y"></textarea></div>
          </div>
          <div id="panel-seo-faq" class="seo-sub-panel">
            <div class="flex items-center justify-between mb-3"><div><h4 class="text-xs font-semibold text-gray-700">FAQs</h4></div><button type="button" onclick="addSeoFaq()" class="btn-amber px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1"><i class="fas fa-plus text-xs"></i> Add FAQ</button></div>
            <div id="seoFaqContainer" class="space-y-2"></div>
            <div id="seoFaqEmpty" class="text-center py-8 border-2 border-dashed border-amber-200 rounded-xl text-amber-400 text-xs"><i class="fas fa-question-circle text-2xl mb-2 block opacity-30"></i>No FAQs yet</div>
            <input type="hidden" name="faqs" id="jFaqsInput" value="[]">
          </div>
          <div id="panel-seo-analysis" class="seo-sub-panel">
            <div class="flex items-center gap-4 mb-4 p-4 bg-gray-50 border border-gray-100 rounded-xl">
              <div class="relative flex-shrink-0"><svg width="68" height="68" viewBox="0 0 68 68"><circle cx="34" cy="34" r="26" fill="none" stroke="#e5e7eb" stroke-width="7"/><circle id="seoDonutJ" cx="34" cy="34" r="26" fill="none" stroke="#8b5cf6" stroke-width="7" stroke-dasharray="163" stroke-dashoffset="163" stroke-linecap="round" transform="rotate(-90 34 34)" style="transition:stroke-dashoffset .6s ease,stroke .3s;"/></svg><div class="absolute inset-0 flex items-center justify-center flex-col"><span class="text-base font-bold text-gray-800 leading-none" id="seoScoreJ">—</span><span class="text-[8px] text-gray-400">/100</span></div></div>
              <div class="flex-1 min-w-0"><div class="text-xs font-semibold text-gray-700 mb-1" id="seoLabelJ">Click Analyse to see results</div><div class="h-1.5 bg-gray-200 rounded-full overflow-hidden mb-2"><div id="seoBarJ" class="h-full rounded-full transition-all" style="width:0%;background:#8b5cf6;"></div></div><div class="flex gap-3 text-xs"><span class="text-green-600 font-medium"><span id="seoPassJ">0</span> passed</span><span class="text-yellow-600 font-medium"><span id="seoImproveJ">0</span> improve</span><span class="text-red-500 font-medium"><span id="seoFailJ">0</span> failed</span></div></div>
              <button type="button" onclick="runJournalSeoAnalysis()" class="btn-purple px-3 py-2 rounded-lg text-xs font-semibold flex items-center gap-1 flex-shrink-0"><i class="fas fa-sync-alt text-xs"></i> Re-run</button>
            </div>
            <div id="seoResultsJ" class="bg-white border border-gray-100 rounded-xl overflow-hidden divide-y divide-gray-50"><div class="p-6 text-center text-gray-400 text-xs"><i class="fas fa-search text-2xl mb-2 block text-gray-300"></i>Enter a focus keyword above and click <strong>Analyse</strong></div></div>
          </div>
        </div><!-- /panel-seo -->

        <!-- SECTIONS TAB -->
        <div id="panel-sections" class="tab-panel">
          <div class="flex items-center justify-between mb-3">
            <div><h3 class="font-semibold text-gray-800 text-sm flex items-center gap-2"><i class="fas fa-layer-group text-orange-500"></i> Journal Page Sections</h3><p class="text-xs text-gray-400 mt-0.5">These sections render on the public journal page below sliders &amp; cards.</p></div>
            <div id="secSaveStatus" class="hidden text-xs text-green-600 flex items-center gap-1"><i class="fas fa-check-circle"></i> Saved!</div>
          </div>

          <div class="flex gap-1 border-b border-gray-100 mb-4 overflow-x-auto">
            <button type="button" class="sec-subtab active" onclick="switchSecTab('ss-jstats')"   id="sst-ss-jstats">  <i class="fas fa-table mr-1 text-xs text-amber-500"></i>Stats</button>
            <button type="button" class="sec-subtab"        onclick="switchSecTab('ss-scope')"    id="sst-ss-scope">   <i class="fas fa-tags mr-1 text-xs text-green-500"></i>Scope</button>
            <button type="button" class="sec-subtab"        onclick="switchSecTab('ss-steps')"    id="sst-ss-steps">   <i class="fas fa-list-ol mr-1 text-xs text-cyan-500"></i>Steps</button>
            <button type="button" class="sec-subtab"        onclick="switchSecTab('ss-board')"    id="sst-ss-board">   <i class="fas fa-users mr-1 text-xs text-teal-500"></i>Board</button>
            <button type="button" class="sec-subtab"        onclick="switchSecTab('ss-indexing')" id="sst-ss-indexing"><i class="fas fa-database mr-1 text-xs text-purple-500"></i>Indexing</button>
            <button type="button" class="sec-subtab"        onclick="switchSecTab('ss-ethics')"   id="sst-ss-ethics">  <i class="fas fa-shield-alt mr-1 text-xs text-pink-500"></i>Ethics</button>
            <button type="button" class="sec-subtab"        onclick="switchSecTab('ss-why')"      id="sst-ss-why">     <i class="fas fa-star mr-1 text-xs text-yellow-500"></i>Why</button>
            <button type="button" class="sec-subtab"        onclick="switchSecTab('ss-contact')"  id="sst-ss-contact"> <i class="fas fa-envelope mr-1 text-xs text-orange-500"></i>Contact</button>
          </div>

          <?php
          $secDefs = [
            'jstats'   => ['amber','Journal Stats (Section 3)','By The Numbers','Journal Stats','4 honest metrics','Stats','fas fa-table'],
            'scope'    => ['green','Aims & Scope (Section 4)','Browse by Discipline','Aims & Scope','12 subject area tags','Tag','fas fa-tags'],
            'steps'    => ['cyan','Submission Process (Section 5)','How It Works','Submission Process','6-step author journey','Step','fas fa-list-ol'],
            'board'    => ['teal','Editorial Board (Section 6)','Our Experts','Editorial Board','Board member cards','Member','fas fa-users'],
            'indexing' => ['purple','Indexing (Section 7)','Visibility','Indexing & Databases','10 database tags','Tag','fas fa-database'],
            'ethics'   => ['pink','Publication Ethics (Section 8)','Our Standards','Publication Ethics','Ethics cards','Card','fas fa-shield-alt'],
            'why'      => ['yellow','Why Publish (Section 9)','Benefits','Why Publish With Us','Value cards for authors','Card','fas fa-star'],
            'contact'  => ['orange','Contact & Quick Links (Section 10)','Get Started','Contact & Quick Links','Action cards','Card','fas fa-envelope'],
          ];
          foreach ($secDefs as $key => [$color,$fullTitle,$defaultEyebrow,$defaultTitle,$defaultDesc,$itemLabel,$icon]): ?>
          <div id="panel-ss-<?=$key?>" class="sec-subpanel <?=$key==='jstats'?'active':''?>">
            <div class="bg-<?=$color?>-50 border border-<?=$color?>-100 rounded-xl p-3 mb-3">
              <p class="text-xs font-semibold text-<?=$color?>-700 mb-2"><i class="<?=$icon?> mr-1"></i><?=$fullTitle?> — Section Header</p>
              <div class="grid grid-cols-3 gap-2">
                <div><label class="block text-xs text-gray-500 mb-1">Eyebrow</label><input type="text" class="sec-hdr-field" data-sec="<?=$key?>" data-field="eyebrow" placeholder="<?=$defaultEyebrow?>"></div>
                <div><label class="block text-xs text-gray-500 mb-1">Title</label><input type="text" class="sec-hdr-field" data-sec="<?=$key?>" data-field="title" placeholder="<?=$defaultTitle?>"></div>
                <div><label class="block text-xs text-gray-500 mb-1">Description</label><input type="text" class="sec-hdr-field" data-sec="<?=$key?>" data-field="description" placeholder="<?=$defaultDesc?>"></div>
              </div>
            </div>
            <div class="flex items-center justify-between mb-2">
              <p class="text-xs font-semibold text-gray-600"><?=$itemLabel?> Items</p>
              <button type="button" onclick="secAddRow('<?=$key?>')" class="text-xs bg-<?=$color?>-500 text-white px-3 py-1.5 rounded-lg font-semibold flex items-center gap-1 hover:bg-<?=$color?>-600 transition"><i class="fas fa-plus text-xs"></i> Add <?=$itemLabel?></button>
            </div>
            <div id="sec-list-<?=$key?>" class="<?=$key==='board'?'grid grid-cols-2 gap-2':($key==='scope'||$key==='indexing'?'flex flex-wrap':'space-y-2')?>"></div>
            <div id="sec-empty-<?=$key?>" class="text-center py-5 border-2 border-dashed border-<?=$color?>-200 rounded-xl text-<?=$color?>-400 text-xs">No <?=strtolower($itemLabel)?> items yet — click Add <?=$itemLabel?></div>
          </div>
          <?php endforeach; ?>

          <div id="ss-scope-form" class="hidden mt-2 bg-gray-50 border border-gray-200 rounded-xl p-3 space-y-2">
            <div class="grid grid-cols-2 gap-2"><div><label class="block text-xs text-gray-500 mb-1">Label *</label><input type="text" id="ss-scope-label" placeholder="Sociology" class="sec-hdr-field"></div><div><label class="block text-xs text-gray-500 mb-1">Link URL</label><input type="text" id="ss-scope-url" placeholder="#" class="sec-hdr-field font-mono"></div></div>
            <div class="flex gap-2"><button type="button" onclick="scopeConfirmAdd()" class="text-xs bg-green-600 text-white px-3 py-1.5 rounded-lg font-semibold">Add Tag</button><button type="button" onclick="document.getElementById('ss-scope-form').classList.add('hidden')" class="text-xs border border-gray-300 text-gray-600 px-3 py-1.5 rounded-lg">Cancel</button></div>
          </div>
          <div id="ss-indexing-form" class="hidden mt-2 bg-gray-50 border border-gray-200 rounded-xl p-3 space-y-2">
            <div class="grid grid-cols-2 gap-2"><div><label class="block text-xs text-gray-500 mb-1">Label *</label><input type="text" id="ss-idx-label" placeholder="Google Scholar" class="sec-hdr-field"></div><div><label class="block text-xs text-gray-500 mb-1">Badge (e.g. applied)</label><input type="text" id="ss-idx-badge" placeholder="applied" class="sec-hdr-field"></div></div>
            <div class="flex gap-2"><button type="button" onclick="idxConfirmAdd()" class="text-xs bg-purple-600 text-white px-3 py-1.5 rounded-lg font-semibold">Add Tag</button><button type="button" onclick="document.getElementById('ss-indexing-form').classList.add('hidden')" class="text-xs border border-gray-300 text-gray-600 px-3 py-1.5 rounded-lg">Cancel</button></div>
          </div>

          <div class="flex justify-end mt-4 pt-3 border-t border-gray-100">
            <button type="button" onclick="saveJournalSections(event)" class="bg-orange-500 hover:bg-orange-600 text-white px-5 py-2 rounded-lg text-sm font-semibold flex items-center gap-2 transition">
              <i class="fas fa-save"></i> Save All Sections
            </button>
          </div>
        </div><!-- /panel-sections -->

      </div><!-- /p-6 -->

      <div class="px-6 py-4 border-t border-gray-100 flex justify-between items-center bg-gray-50 flex-shrink-0">
        <div class="flex gap-2">
          <button type="button" onclick="prevTab()" id="btnPrev" class="border border-gray-300 text-gray-600 px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-100 hidden flex items-center gap-1"><i class="fas fa-chevron-left text-xs"></i> Back</button>
          <button type="button" onclick="nextTab()" id="btnNext" class="border border-blue-300 text-blue-600 px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-50 flex items-center gap-1">Next <i class="fas fa-chevron-right text-xs"></i></button>
        </div>
        <div class="flex gap-2">
          <button type="button" onclick="closeJournalModal()" class="border border-gray-300 text-gray-600 px-5 py-2 rounded-lg text-sm font-medium hover:bg-gray-50">Cancel</button>
          <button type="submit" onclick="serializeJournalFaqs()" class="btn-primary px-6 py-2 rounded-lg text-sm font-semibold flex items-center gap-2"><i class="fas fa-save"></i> <span id="journalSaveBtn">Create Journal</span></button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- CATEGORY MODAL -->
<div id="categoryModal" class="fixed inset-0 modal-backdrop hidden z-50 flex items-center justify-center p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-xl max-h-[90vh] overflow-hidden flex flex-col">
    <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between flex-shrink-0">
      <h2 class="font-bold text-gray-800 text-lg"><i class="fas fa-tags text-purple-500 mr-2"></i>Journal Categories</h2>
      <button onclick="closeCategoryModal()" class="text-gray-400 hover:text-red-500 w-8 h-8 rounded-lg hover:bg-red-50 flex items-center justify-center transition" title="Close"><i class="fas fa-times"></i></button>
    </div>
    <div class="flex-1 overflow-y-auto p-6 space-y-6">
      <form method="POST">
        <input type="hidden" name="save_category" value="1"><input type="hidden" name="category_id" id="catId" value="0">
        <div class="bg-blue-50 border border-blue-100 rounded-xl p-4">
          <h3 class="text-sm font-semibold text-blue-700 mb-3" id="catFormTitle"><i class="fas fa-plus-circle mr-1"></i>Add New Category</h3>
          <div class="grid grid-cols-2 gap-3 mb-3"><div><label class="block text-xs font-semibold text-gray-600 mb-1">Category Name *</label><input type="text" name="cat_name" id="catName" required placeholder="e.g. Engineering" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 bg-white"></div><div><label class="block text-xs font-semibold text-gray-600 mb-1">Display Order</label><input type="number" name="display_order" id="catOrder" value="0" min="0" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 bg-white"></div></div>
          <div class="flex gap-2"><button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-blue-700 flex items-center gap-1"><i class="fas fa-save text-xs"></i> <span id="catSaveBtn">Add Category</span></button><button type="button" onclick="resetCatForm()" class="border border-gray-300 text-gray-600 px-4 py-2 rounded-lg text-sm hover:bg-gray-50">Reset</button></div>
        </div>
      </form>
      <div><h3 class="text-sm font-semibold text-gray-700 mb-3">Existing Categories (<?=$totalCats?>)</h3>
        <?php if(empty($categories)): ?><div class="text-center py-6 text-gray-400 text-sm">No categories yet</div>
        <?php else: ?><div class="space-y-2"><?php foreach($categories as $c): ?>
          <div class="flex items-center justify-between bg-gray-50 rounded-lg px-4 py-3 border border-gray-100">
            <div class="flex items-center gap-3"><div class="w-7 h-7 rounded-lg bg-purple-100 flex items-center justify-center text-purple-600 text-xs font-bold"><?=$c['display_order']?></div><div><div class="font-medium text-gray-800 text-sm"><?=p($c['name'])?></div><div class="text-xs text-gray-400"><?=$c['journal_count']?> journal<?=$c['journal_count']!=1?'s':''?></div></div></div>
            <div class="flex gap-1"><button onclick="editCategory(<?=$c['category_id']?>,'<?=p($c['name'])?>',<?=$c['display_order']?>)" class="w-7 h-7 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"><i class="fas fa-edit text-xs"></i></button><button onclick="deleteCategory(<?=$c['category_id']?>,'<?=p($c['name'])?>')" class="w-7 h-7 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>
          </div><?php endforeach; ?></div><?php endif; ?>
      </div>
    </div>
  </div>
</div>

<form id="deleteJournalForm" method="POST" class="hidden"><input type="hidden" name="delete_journal" value="1"><input type="hidden" name="journal_id" id="deleteJournalId"></form>
<form id="deleteCategoryForm" method="POST" class="hidden"><input type="hidden" name="delete_category" value="1"><input type="hidden" name="category_id" id="deleteCategoryId"></form>

<script>
// ══ TABS ══
const TABS=['basic','images','stats','sliders','infocards','notices','seo','sections'];
let curTab=0;
function switchTab(name){
  curTab=TABS.indexOf(name);
  TABS.forEach(t=>{
    document.getElementById('panel-'+t)?.classList.toggle('active',t===name);
    document.getElementById('tab-'+t)?.classList.toggle('active',t===name);
  });
  document.getElementById('btnPrev').classList.toggle('hidden',curTab===0);
  document.getElementById('btnNext').classList.toggle('hidden',curTab===TABS.length-1);
  syncPreviewName();
}
function nextTab(){if(curTab<TABS.length-1)switchTab(TABS[curTab+1]);}
function prevTab(){if(curTab>0)switchTab(TABS[curTab-1]);}

// ══ SEO sub-tabs ══
const SEO_TABS=['seo-core','seo-social','seo-schema','seo-ai','seo-faq','seo-analysis'];
function switchSeoTab(name){SEO_TABS.forEach(t=>{document.getElementById('panel-'+t)?.classList.toggle('active',t===name);document.getElementById('stab-'+t)?.classList.toggle('active',t===name);});}

// ══ SECTIONS sub-tabs ══
const SEC_TABS=['ss-jstats','ss-scope','ss-steps','ss-board','ss-indexing','ss-ethics','ss-why','ss-contact'];
function switchSecTab(name){
  SEC_TABS.forEach(t=>{
    document.getElementById('panel-'+t)?.classList.toggle('active',t===name);
    document.getElementById('sst-'+t)?.classList.toggle('active',t===name);
  });
}

// ══ SLUG ══
let slugEdited=false;
document.getElementById('jSlug').addEventListener('input',()=>slugEdited=true);
function autoSlug(){if(slugEdited)return;const v=document.getElementById('jName').value.toLowerCase().replace(/[^a-z0-9\s-]/g,'').replace(/\s+/g,'-').replace(/-+/g,'-').trim();document.getElementById('jSlug').value=v;document.getElementById('serpJSlug').textContent=v||'slug';}
function syncPreviewName(){const n=document.getElementById('jName').value.trim();document.getElementById('prev_jname').textContent=n||'Journal Name';document.getElementById('serpJTitle').textContent=document.getElementById('jMetaTitle')?.value?.trim()||n||'Journal Name';document.getElementById('serpJSlug').textContent=document.getElementById('jSlug')?.value?.trim()||'slug';}

// ══ IMAGES ══
function handleFileUpload(input,previewId,zoneId,urlId){if(!input.files||!input.files[0])return;const r=new FileReader();r.onload=e=>{document.getElementById(previewId).innerHTML=`<img src="${e.target.result}" class="w-full h-full object-cover">`;const z=document.getElementById(zoneId);z.classList.add('has-file');z.innerHTML=`<img src="${e.target.result}" class="w-full h-16 object-cover rounded-lg mb-1"><p class="text-xs text-blue-600 font-medium">✓ ${input.files[0].name}</p>`;document.getElementById(urlId).value='';};r.readAsDataURL(input.files[0]);}
function previewFromUrl(url,previewId){const b=document.getElementById(previewId);if(url.trim())b.innerHTML=`<img src="/${url.replace(/^\//,'')}" onerror="this.parentElement.innerHTML='<i class=\\'fas fa-image text-2xl\\'></i>'" class="w-full h-full object-cover">`;else b.innerHTML=`<i class="fas ${previewId==='bgPreview'?'fa-panorama':'fa-image'} text-2xl"></i>`;}

// ══ SEO helpers ══
function bindSeoCounter(el,countId,barId,max,idealMin,idealMax){const len=el.value.length;const c=document.getElementById(countId);if(c)c.textContent=len;if(barId){const b=document.getElementById(barId);if(b){b.style.width=Math.min((len/max)*100,100)+'%';b.style.background=(len>=idealMin&&len<=idealMax)?'#22c55e':(len>idealMax?'#ef4444':'#f59e0b');}}if(el.id==='jMetaTitle')document.getElementById('serpJTitle').textContent=el.value.trim()||(document.getElementById('jName').value.trim()||'Journal Name');if(el.id==='jMetaDesc')document.getElementById('serpJDesc').textContent=el.value.trim()||'Meta description will appear here…';}
function updateWordCount(el,countId){const w=el.value.trim().split(/\s+/).filter(x=>x.length>0).length;const c=document.getElementById(countId);if(c){c.textContent=w;c.className='font-medium '+(w>=100&&w<=300?'text-green-600':w>300?'text-red-500':'text-yellow-600');}}
function insertJournalSchema(type){const el=document.getElementById('jSchema');if(!el)return;if(el.value.trim()&&!confirm('Replace existing schema?'))return;const n=document.getElementById('jName')?.value||'Journal Name';const s=document.getElementById('jSlug')?.value||'slug';const t={website:JSON.stringify({"@context":"https://schema.org","@type":"WebSite","name":n,"url":`https://yoursite.com/journals/${s}`},null,2),org:JSON.stringify({"@context":"https://schema.org","@type":"Organization","name":n,"url":`https://yoursite.com/journals/${s}`},null,2),faqpage:JSON.stringify({"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the scope of "+n+"?","acceptedAnswer":{"@type":"Answer","text":"This journal covers..."}}]},null,2)};el.value=t[type]||'';}
function validateJournalSchema(){const el=document.getElementById('jSchema');const m=document.getElementById('schemaValidMsgJ');try{JSON.parse(el.value);m.textContent='✓ Valid JSON';m.className='text-xs text-green-600';}catch(e){m.textContent='✗ '+e.message;m.className='text-xs text-red-600';}m.classList.remove('hidden');}
function addSeoFaq(q='',a=''){const c=document.getElementById('seoFaqContainer');document.getElementById('seoFaqEmpty').style.display='none';const d=document.createElement('div');d.className='faq-row-seo';d.innerHTML=`<div class="faq-rm" onclick="this.closest('.faq-row-seo').remove();checkFaqEmpty()"><i class="fas fa-times"></i></div><div class="space-y-1.5"><div><label class="text-xs font-semibold text-gray-600 mb-1 block">Question</label><input type="text" class="seo-faq-q form-field text-xs" value="${escH(q)}" placeholder="e.g. What is the scope?"></div><div><label class="text-xs font-semibold text-gray-600 mb-1 block">Answer</label><textarea class="seo-faq-a form-field text-xs resize-none" rows="2" placeholder="Concise answer…">${escH(a)}</textarea></div></div>`;c.appendChild(d);}
function checkFaqEmpty(){if(!document.getElementById('seoFaqContainer').children.length)document.getElementById('seoFaqEmpty').style.display='';}
function serializeJournalFaqs(){const rows=document.querySelectorAll('#seoFaqContainer .faq-row-seo');const data=[];rows.forEach(r=>{const q=r.querySelector('.seo-faq-q')?.value?.trim()||'';const a=r.querySelector('.seo-faq-a')?.value?.trim()||'';if(q||a)data.push({q,a});});document.getElementById('jFaqsInput').value=JSON.stringify(data);}
let _seoTimer=null;function scheduleAnalysis(){clearTimeout(_seoTimer);_seoTimer=setTimeout(runJournalSeoAnalysis,900);}
window.runJournalSeoAnalysis=function(){const keyword=(document.getElementById('jFocusKeyword')?.value||'').trim().toLowerCase();const name=(document.getElementById('jName')?.value||'').trim();const slug=(document.getElementById('jSlug')?.value||'').trim();const desc=(document.getElementById('jDescription')?.value||'').trim();const metaTitle=(document.getElementById('jMetaTitle')?.value||'').trim();const metaDesc=(document.getElementById('jMetaDesc')?.value||'').trim();const metaKw=(document.getElementById('jMetaKeywords')?.value||'').trim();const aiSummary=(document.getElementById('jAiSummary')?.value||'').trim();const schema=(document.getElementById('jSchema')?.value||'').trim();const ogTitle=(document.getElementById('jOgTitle')?.value||'').trim();const coverUrl=(document.getElementById('jCoverUrl')?.value||'').trim();const faqs=document.querySelectorAll('#seoFaqContainer .faq-row-seo');const icon=document.getElementById('seoAnalyseIcon');if(icon){icon.style.transition='transform .5s';icon.style.transform='rotate(360deg)';setTimeout(()=>{icon.style.transform='';},500);}const words=desc.split(/\s+/).filter(w=>w.length>0);const wordCount=words.length;const kwCount=keyword?(desc.toLowerCase().match(new RegExp(keyword.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),'gi'))||[]).length:0;const kwDensity=wordCount>0?(kwCount/wordCount)*100:0;const checks=[];if(!keyword){checks.push({status:'improve',title:'Focus Keyword',detail:'<span class="warn">No focus keyword set.</span>'});}else{const inName=name.toLowerCase().includes(keyword);checks.push({status:inName?'pass':'fail',title:'Keyword in Journal Name',detail:inName?`Keyword <span class="found">"${escH(keyword)}"</span> found.`:`<span class="bad">Not found</span> in: <strong>${escH(name)}</strong>`});}if(keyword){const inSlug=slug.toLowerCase().includes(keyword.replace(/\s+/g,'-'));checks.push({status:inSlug?'pass':'improve',title:'Keyword in URL Slug',detail:inSlug?'Slug contains keyword.':'<span class="warn">Slug missing keyword.</span>'});}if(keyword){const inMeta=metaDesc.toLowerCase().includes(keyword);checks.push({status:inMeta?'pass':'fail',title:'Keyword in Meta Description',detail:inMeta?'Found in meta description.':'<span class="bad">Missing from meta description.</span>'});}if(keyword){const inMetaT=(metaTitle||name).toLowerCase().includes(keyword);checks.push({status:inMetaT?'pass':'fail',title:'Keyword in SEO Title',detail:inMetaT?'Found in SEO title.':'<span class="bad">Missing from SEO title.</span>'});}const mdLen=metaDesc.length;const mdStatus=(mdLen>=150&&mdLen<=165)?'pass':(mdLen>0?'improve':'fail');checks.push({status:mdStatus,title:'Meta Description (150–160 chars)',detail:metaDesc?`<strong>${mdLen} chars</strong>. `+(mdLen>=150&&mdLen<=165?'<span class="found">Perfect.</span>':mdLen<150?'<span class="warn">Too short.</span>':'<span class="warn">Too long.</span>'):'<span class="bad">No meta description.</span>'});checks.push({status:metaKw?'pass':'improve',title:'Meta Keywords',detail:metaKw?`<span class="found">${escH(metaKw.substring(0,60))}</span>`:'<span class="warn">No meta keywords.</span>'});checks.push({status:coverUrl?'pass':'fail',title:'Cover Image',detail:coverUrl?'<span class="found">Cover image set.</span>':'<span class="bad">No cover image.</span>'});checks.push({status:ogTitle?'pass':'improve',title:'OG Title',detail:ogTitle?'<span class="found">OG title set.</span>':'<span class="warn">No OG title.</span>'});checks.push({status:schema?'pass':'improve',title:'JSON-LD Schema',detail:schema?'<span class="found">Schema added.</span>':'<span class="warn">No schema markup.</span>'});const aiWords=aiSummary.split(/\s+/).filter(w=>w.length>0).length;checks.push({status:aiWords>=100?'pass':(aiWords>0?'improve':'fail'),title:'AI Summary',detail:aiSummary?`<strong>${aiWords} words</strong>. `+(aiWords>=100?'<span class="found">Good.</span>':'<span class="warn">Expand to 100+ words.</span>'):'<span class="bad">No AI summary.</span>'});const faqCount=faqs.length;checks.push({status:(faqCount>0&&Array.from(faqs).some(r=>r.querySelector('.seo-faq-q')?.value?.trim()))?'pass':'improve',title:'FAQs',detail:faqCount>0?`<span class="found">${faqCount} FAQ(s)</span> added.`:'<span class="warn">No FAQs set.</span>'});const passed=checks.filter(c=>c.status==='pass').length;const improve=checks.filter(c=>c.status==='improve').length;const total=checks.length;const score=total>0?Math.round(((passed+improve*.5)/total)*100):0;const color=score>=70?'#10b981':score>=40?'#f59e0b':'#ef4444';const offset=163-(score/100)*163;document.getElementById('seoDonutJ').style.strokeDashoffset=offset;document.getElementById('seoDonutJ').style.stroke=color;document.getElementById('seoScoreJ').textContent=score;document.getElementById('seoBarJ').style.width=score+'%';document.getElementById('seoBarJ').style.background=color;document.getElementById('seoPassJ').textContent=passed;document.getElementById('seoImproveJ').textContent=improve;document.getElementById('seoFailJ').textContent=checks.filter(c=>c.status==='fail').length;document.getElementById('seoLabelJ').textContent=score>=70?'✅ Good SEO!':score>=40?'⚠️ Needs improvement':'❌ Significant work needed';const icons={pass:'fa-check',improve:'fa-exclamation',fail:'fa-times'};const labels={pass:'Good',improve:'Improve',fail:'Missing'};document.getElementById('seoResultsJ').innerHTML=checks.map(c=>`<div class="seo-result-row"><div class="seo-icon ${c.status}"><i class="fas ${icons[c.status]}"></i></div><div class="flex-1 min-w-0"><div class="flex items-start gap-2"><div class="seo-result-title flex-1">${escH(c.title)}</div><span class="seo-badge badge-${c.status}">${labels[c.status]}</span></div><div class="seo-result-detail">${c.detail}</div></div></div>`).join('');switchSeoTab('seo-analysis');};
function escH(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}

// ══ REPEATABLE CARDS ══
const repState={sliders:{count:0},infocards:{count:0},notices:{count:0}};
function addRepCard(section,color,data=null){repState[section].count++;const n=repState[section].count;const isNotice=section==='notices';const isSlider=section==='sliders';const isInfoCard=section==='infocards';const tp=isSlider?'slider':isInfoCard?'journal_info_cards':'journal_notices';const pk=isSlider?'slider_id':isInfoCard?'card_id':'notice_id';const sid=data?(parseInt(data[pk])||0):0;const label=isSlider?'Slide':isNotice?'Notice':'Card';const numCls=color==='amber'?'card-num amber':'card-num blue';const cardCls=isNotice?'rep-card notice-card':'rep-card';document.getElementById('empty-'+section).style.display='none';let hiddenId='';if(isSlider)hiddenId=`<input type="hidden" name="slider_id[]" value="${sid}">`;if(isInfoCard)hiddenId=`<input type="hidden" name="journal_info_cards_id[]" value="${sid}">`;if(isNotice)hiddenId=`<input type="hidden" name="journal_notices_id[]" value="${sid}">`;const btnFields=isSlider?`<div class="grid grid-cols-2 gap-3"><div><label class="block text-xs font-semibold text-gray-600 mb-1">Button Name</label><input type="text" name="slider_btn_name[]" value="${escH(data?.btn_name||'')}" placeholder="Submit your research" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 bg-white"></div><div><label class="block text-xs font-semibold text-gray-600 mb-1">Button Link</label><input type="text" name="slider_btn_link[]" value="${escH(data?.btn_link||'')}" placeholder="/submit" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm font-mono focus:ring-2 focus:ring-blue-500 bg-white"></div></div>`:'';const linkField=!isSlider?`<div><label class="block text-xs font-semibold text-gray-600 mb-1">Link URL</label><input type="text" name="${tp}_link[]" value="${escH(data?.link||'')}" placeholder="/submit-paper or https://..." class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm font-mono focus:ring-2 focus:ring-${color==='amber'?'amber':'blue'}-500 bg-white"></div>`:'';const imgField=!isSlider?`<div><label class="block text-xs font-semibold text-gray-600 mb-1">Card Image</label><div class="flex gap-3 items-start"><div class="flex-1"><div class="mini-upload" id="minizone-${section}-${n}" onclick="document.getElementById('mini-file-${section}-${n}').click()"><i class="fas fa-cloud-upload-alt mr-1"></i> Click to upload</div><input type="file" id="mini-file-${section}-${n}" name="${tp}_image[]" accept="image/*" class="hidden" onchange="miniPreview(this,'minizone-${section}-${n}','mini-prev-${section}-${n}','mini-url-${section}-${n}')"><input type="text" id="mini-url-${section}-${n}" name="${tp}_url[]" value="${escH(data?.image_url||'')}" placeholder="or paste image URL..." oninput="miniUrlPreview(this.value,'mini-prev-${section}-${n}')" class="mt-1 w-full border border-gray-200 rounded-lg px-3 py-1.5 text-xs font-mono focus:ring-2 focus:ring-blue-500 bg-white"></div><div id="mini-prev-${section}-${n}" class="img-thumb">${data?.image_url?`<img src="/${(data.image_url).replace(/^\//,'')}" onerror="this.parentElement.innerHTML='<i class=\\'fas fa-image\\'></i>'">`:'<i class="fas fa-image"></i>'}</div></div></div>`:'';const div=document.createElement('div');div.className=cardCls;div.innerHTML=`<button type="button" class="rm-btn" onclick="removeRepCard(this,'${section}')"><i class="fas fa-times"></i></button>${hiddenId}<div class="flex items-center gap-2 mb-3"><span class="${numCls}">${n}</span><span class="text-xs font-semibold text-gray-600">${label} ${n}</span></div><div class="space-y-3"><div><label class="block text-xs font-semibold text-gray-600 mb-1">Title <span class="text-red-500">*</span></label><input type="text" name="${isSlider?'slider_title[]':`${tp}_title[]`}" value="${escH(data?.title||'')}" placeholder="${isSlider?'e.g. Promoting research...':isNotice?'e.g. Call for papers':'e.g. Submit your paper'}" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-${color==='amber'?'amber':'blue'}-500 bg-white"></div><div><label class="block text-xs font-semibold text-gray-600 mb-1">Description</label><textarea name="${isSlider?'slider_desc[]':`${tp}_desc[]`}" rows="2" class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm resize-none focus:ring-2 focus:ring-${color==='amber'?'amber':'blue'}-500 bg-white">${escH(data?.description||'')}</textarea></div>${imgField}${linkField}${btnFields}</div>`;document.getElementById('list-'+section).appendChild(div);}
function removeRepCard(btn,section){btn.closest('.rep-card').remove();if(!document.getElementById('list-'+section).children.length)document.getElementById('empty-'+section).style.display='';}
function miniPreview(input,zoneId,previewId,urlId){if(!input.files||!input.files[0])return;const r=new FileReader();r.onload=e=>{document.getElementById(zoneId).classList.add('has-file');document.getElementById(zoneId).innerHTML=`<i class="fas fa-check-circle text-green-500 mr-1"></i>${input.files[0].name}`;const p=document.getElementById(previewId);if(p)p.innerHTML=`<img src="${e.target.result}" class="w-full h-full object-cover">`;const u=document.getElementById(urlId);if(u)u.value='';};r.readAsDataURL(input.files[0]);}
function miniUrlPreview(url,previewId){const p=document.getElementById(previewId);if(!p)return;if(url.trim())p.innerHTML=`<img src="/${url.replace(/^\//,'')}" onerror="this.parentElement.innerHTML='<i class=\\'fas fa-image\\'></i>'" class="w-full h-full object-cover">`;else p.innerHTML='<i class="fas fa-image"></i>';}
function clearAll(){['sliders','infocards','notices'].forEach(s=>{repState[s].count=0;document.getElementById('list-'+s).innerHTML='';document.getElementById('empty-'+s).style.display='';});document.getElementById('seoFaqContainer').innerHTML='';document.getElementById('seoFaqEmpty').style.display='';document.getElementById('jFaqsInput').value='[]';}

// ══ SECTIONS STATE ══
const SEC={jstats:[],scope:[],steps:[],board:[],indexing:[],ethics:[],why:[],contact:[],headers:{}};
function clearSections(){Object.keys(SEC).forEach(k=>{SEC[k]=k==='headers'?{}:[];});SEC_TABS.forEach(s=>{const k=s.replace('ss-','');const list=document.getElementById('sec-list-'+k);if(list)list.innerHTML='';const emp=document.getElementById('sec-empty-'+k);if(emp)emp.style.display='';});document.querySelectorAll('.sec-hdr-field').forEach(el=>el.value='');['ss-scope-form','ss-indexing-form'].forEach(id=>document.getElementById(id)?.classList.add('hidden'));}

function secRender(key){
  const list=document.getElementById('sec-list-'+key);
  const emp=document.getElementById('sec-empty-'+key);
  if(!list)return;
  list.innerHTML='';
  if(SEC[key].length===0){if(emp)emp.style.display='';return;}
  if(emp)emp.style.display='none';
  SEC[key].forEach((r,i)=>{
    let html='';const ev=v=>String(v||'').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    if(key==='jstats'){html=`<div class="sec-row flex gap-2 items-center"><button type="button" class="rm-sec" onclick="secRemove('jstats',${i})"><i class="fas fa-times"></i></button><input class="sec-hdr-field flex-1" placeholder="Number (e.g. 4×)" value="${ev(r.number)}" oninput="SEC.jstats[${i}].number=this.value"><input class="sec-hdr-field flex-1" placeholder="Label (e.g. Issues per year)" value="${ev(r.label)}" oninput="SEC.jstats[${i}].label=this.value"></div>`;}
    else if(key==='scope'){html=`<span class="sec-chip">${ev(r.label)}<span class="rm-chip" onclick="secRemove('scope',${i})">✕</span></span>`;}
    else if(key==='steps'){html=`<div class="sec-row"><button type="button" class="rm-sec" onclick="secRemove('steps',${i})"><i class="fas fa-times"></i></button><div class="grid grid-cols-3 gap-2"><input class="sec-hdr-field" placeholder="Step #" value="${ev(r.step_number)}" oninput="SEC.steps[${i}].step_number=this.value"><input class="sec-hdr-field" placeholder="Title" value="${ev(r.title)}" oninput="SEC.steps[${i}].title=this.value"><input class="sec-hdr-field" placeholder="Description" value="${ev(r.description)}" oninput="SEC.steps[${i}].description=this.value"></div></div>`;}
    else if(key==='board'){const init=r.initials||(r.name?r.name.split(' ').map(w=>w[0]).join('').toUpperCase().slice(0,2):'??');html=`<div class="sec-row"><button type="button" class="rm-sec" onclick="secRemove('board',${i})"><i class="fas fa-times"></i></button><div class="flex gap-2 items-center mb-2"><div class="sec-board-avatar">${ev(init)}</div><input class="sec-hdr-field flex-1" placeholder="Name" value="${ev(r.name)}" oninput="SEC.board[${i}].name=this.value"></div><div class="grid grid-cols-3 gap-1.5"><input class="sec-hdr-field" placeholder="Initials" value="${ev(init)}" oninput="SEC.board[${i}].initials=this.value"><input class="sec-hdr-field" placeholder="Role" value="${ev(r.role)}" oninput="SEC.board[${i}].role=this.value"><input class="sec-hdr-field" placeholder="Institution" value="${ev(r.institution)}" oninput="SEC.board[${i}].institution=this.value"></div></div>`;}
    else if(key==='indexing'){html=`<span class="sec-chip">${ev(r.label)}${r.badge?` <small style="color:#8b5cf6;font-size:9px;font-weight:700">${ev(r.badge)}</small>`:''}<span class="rm-chip" onclick="secRemove('indexing',${i})">✕</span></span>`;}
    else if(key==='ethics'){html=`<div class="sec-row"><button type="button" class="rm-sec" onclick="secRemove('ethics',${i})"><i class="fas fa-times"></i></button><div class="grid grid-cols-2 gap-2"><input class="sec-hdr-field" placeholder="Title" value="${ev(r.title)}" oninput="SEC.ethics[${i}].title=this.value"><input class="sec-hdr-field" placeholder="Description" value="${ev(r.description)}" oninput="SEC.ethics[${i}].description=this.value"></div></div>`;}
    else if(key==='why'){html=`<div class="sec-row"><button type="button" class="rm-sec" onclick="secRemove('why',${i})"><i class="fas fa-times"></i></button><div class="grid grid-cols-2 gap-2"><input class="sec-hdr-field" placeholder="Title" value="${ev(r.title)}" oninput="SEC.why[${i}].title=this.value"><textarea class="sec-hdr-field" rows="2" placeholder="Description" oninput="SEC.why[${i}].description=this.value">${ev(r.description)}</textarea></div></div>`;}
    else if(key==='contact'){html=`<div class="sec-row"><button type="button" class="rm-sec" onclick="secRemove('contact',${i})"><i class="fas fa-times"></i></button><div class="grid grid-cols-2 gap-2 mb-1"><input class="sec-hdr-field" placeholder="Title" value="${ev(r.title)}" oninput="SEC.contact[${i}].title=this.value"><textarea class="sec-hdr-field" rows="2" placeholder="Description" oninput="SEC.contact[${i}].description=this.value">${ev(r.description)}</textarea></div><div class="grid grid-cols-2 gap-2"><input class="sec-hdr-field" placeholder="Link Text" value="${ev(r.link_text)}" oninput="SEC.contact[${i}].link_text=this.value"><input class="sec-hdr-field font-mono" placeholder="Link URL" value="${ev(r.link_url)}" oninput="SEC.contact[${i}].link_url=this.value"></div></div>`;}
    const d=document.createElement('div'); d.innerHTML=html; list.appendChild(d.firstElementChild||d);
  });
}

function secRemove(key,idx){SEC[key].splice(idx,1);secRender(key);}

function secAddRow(key){
  if(key==='scope'){document.getElementById('ss-scope-form').classList.remove('hidden');document.getElementById('ss-scope-label').focus();return;}
  if(key==='indexing'){document.getElementById('ss-indexing-form').classList.remove('hidden');document.getElementById('ss-idx-label').focus();return;}
  const defaults={jstats:{number:'',label:''},steps:{step_number:String(SEC.steps.length+1),title:'',description:''},board:{name:'',initials:'',role:'',institution:''},ethics:{title:'',description:''},why:{title:'',description:''},contact:{title:'',description:'',link_text:'',link_url:''}};
  SEC[key].push(defaults[key]||{});secRender(key);
}
function scopeConfirmAdd(){const label=document.getElementById('ss-scope-label').value.trim();if(!label)return;SEC.scope.push({label,link_url:document.getElementById('ss-scope-url').value.trim()||'#'});secRender('scope');document.getElementById('ss-scope-label').value='';document.getElementById('ss-scope-url').value='';document.getElementById('ss-scope-form').classList.add('hidden');}
function idxConfirmAdd(){const label=document.getElementById('ss-idx-label').value.trim();if(!label)return;SEC.indexing.push({label,badge:document.getElementById('ss-idx-badge').value.trim()||null});secRender('indexing');document.getElementById('ss-idx-label').value='';document.getElementById('ss-idx-badge').value='';document.getElementById('ss-indexing-form').classList.add('hidden');}

function collectSectionHeaders(){const h={};document.querySelectorAll('.sec-hdr-field').forEach(el=>{const s=el.dataset.sec;const f=el.dataset.field;if(!s||!f)return;if(!h[s])h[s]={};h[s][f]=el.value.trim();});return h;}

async function loadJournalSections(jid){
  clearSections();
  if(!jid)return;
  try{
    const res=await fetch(`?ajax=get_journal_sections&id=${jid}`);
    const data=await res.json();
    if(data.headers)Object.entries(data.headers).forEach(([k,hdr])=>{SEC.headers[k]=hdr;document.querySelectorAll(`.sec-hdr-field[data-sec="${k}"]`).forEach(el=>{el.value=hdr[el.dataset.field]||'';});});
    const map={jl_stats:'jstats',jl_scope_tags:'scope',jl_steps:'steps',jl_board:'board',jl_indexing:'indexing',jl_ethics:'ethics',jl_why:'why',jl_contact:'contact'};
    Object.entries(map).forEach(([dbKey,secKey])=>{SEC[secKey]=(data[dbKey]||[]);secRender(secKey);});
  }catch(e){console.error('loadJournalSections:',e);}
}

async function saveJournalSections(e){
  const jid=parseInt(document.getElementById('journalId').value||'0');
  if(!jid){alert('Please save the journal first, then save sections.');return;}
  const btn=e.currentTarget; btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin mr-1"></i> Saving…';
  try{
    const res=await fetch('?ajax=save_journal_sections',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({journal_id:jid,jl_stats:SEC.jstats,jl_scope_tags:SEC.scope,jl_steps:SEC.steps,jl_board:SEC.board,jl_indexing:SEC.indexing,jl_ethics:SEC.ethics,jl_why:SEC.why,jl_contact:SEC.contact,headers:collectSectionHeaders()})});
    const data=await res.json();
    if(data.success){const s=document.getElementById('secSaveStatus');s.classList.remove('hidden');setTimeout(()=>s.classList.add('hidden'),3000);}
    else alert('Error: '+(data.error||'Unknown'));
  }catch(ex){alert('Network error: '+ex.message);}
  finally{btn.disabled=false;btn.innerHTML='<i class="fas fa-save"></i> Save All Sections';}
}

// ══ MODAL OPEN/CLOSE ══
function openJournalModal(data=null){
  slugEdited=false;clearAll();clearSections();switchTab('basic');switchSeoTab('seo-core');switchSecTab('ss-jstats');
  if(data&&data.journal_id){
    document.getElementById('journalModalTitle').innerHTML='<i class="fas fa-edit text-blue-500"></i> Edit Journal';
    document.getElementById('journalSaveBtn').textContent='Update Journal';
    document.getElementById('journalId').value=data.journal_id;
    document.getElementById('jName').value=data.name||'';document.getElementById('jSlug').value=data.slug||'';document.getElementById('jCategory').value=data.category_id||'';document.getElementById('jDescription').value=data.description||'';
    document.getElementById('jCoverUrl').value=data.cover_image_url||'';document.getElementById('jBgUrl').value=data.bg_image_url||'';
    document.getElementById('jStatCitations').value=data.stat_citations||'';document.getElementById('jStatHindex').value=data.stat_hindex||'';document.getElementById('jStatArticles').value=data.stat_articles||'';
    document.getElementById('jActive').checked=data.is_active==1;slugEdited=true;
    document.getElementById('jFocusKeyword').value=data.focus_keyword||'';document.getElementById('jMetaTitle').value=data.meta_title||'';document.getElementById('jMetaDesc').value=data.meta_description||'';document.getElementById('jMetaKeywords').value=data.meta_keywords||'';document.getElementById('jCanonicalUrl').value=data.canonical_url||'';document.getElementById('jOgTitle').value=data.og_title||'';document.getElementById('jOgDesc').value=data.og_description||'';document.getElementById('jOgImage').value=data.og_image||'';document.getElementById('jOgType').value=data.og_type||'website';document.getElementById('jTwitterCard').value=data.twitter_card||'summary_large_image';document.getElementById('jTwitterTitle').value=data.twitter_title||'';document.getElementById('jTwitterDesc').value=data.twitter_description||'';document.getElementById('jTwitterImage').value=data.twitter_image||'';document.getElementById('jTwitterSite').value=data.twitter_site||'';document.getElementById('jSchema').value=data.schema_markup||'';document.getElementById('jAiSummary').value=data.ai_summary||'';
    try{const faqData=JSON.parse(data.faqs||'[]');if(Array.isArray(faqData))faqData.forEach(f=>addSeoFaq(f.q||'',f.a||''));}catch(e){}
    document.getElementById('serpJSlug').textContent=data.slug||'slug';document.getElementById('serpJTitle').textContent=data.meta_title||data.name||'Journal Name';document.getElementById('serpJDesc').textContent=data.meta_description||'Meta description will appear here…';
    previewFromUrl(data.cover_image_url||'','coverPreview');previewFromUrl(data.bg_image_url||'','bgPreview');
    document.getElementById('prev_cit').textContent=data.stat_citations||'—';document.getElementById('prev_hi').textContent=data.stat_hindex||'—';document.getElementById('prev_art').textContent=data.stat_articles||'—';document.getElementById('prev_jname').textContent=data.name||'Journal Name';
    (data.sliders||[]).forEach(s=>addRepCard('sliders','blue',s));(data.info_cards||[]).forEach(c=>addRepCard('infocards','blue',c));(data.notices||[]).forEach(n=>addRepCard('notices','amber',n));
    if(data.focus_keyword)setTimeout(runJournalSeoAnalysis,400);
    loadJournalSections(data.journal_id);
  }else{
    document.getElementById('journalModalTitle').innerHTML='<i class="fas fa-book-open text-blue-500"></i> Create New Journal';
    document.getElementById('journalSaveBtn').textContent='Create Journal';
    document.getElementById('journalForm').reset();document.getElementById('journalId').value=0;document.getElementById('jActive').checked=true;
    ['coverPreview','bgPreview'].forEach(id=>{document.getElementById(id).innerHTML=`<i class="fas ${id==='bgPreview'?'fa-panorama':'fa-image'} text-2xl"></i>`;});
    document.getElementById('coverZone').classList.remove('has-file');document.getElementById('bgZone').classList.remove('has-file');
    document.getElementById('coverZone').innerHTML='<i class="fas fa-cloud-upload-alt text-3xl text-blue-300 mb-2 block"></i><p class="text-sm font-medium text-gray-500">Click to upload cover image</p><p class="text-xs text-gray-400 mt-1">JPG · PNG · WEBP · Max 5 MB</p>';
    document.getElementById('bgZone').innerHTML='<i class="fas fa-cloud-upload-alt text-3xl text-teal-300 mb-2 block"></i><p class="text-sm font-medium text-gray-500">Click to upload hero background</p><p class="text-xs text-gray-400 mt-1">Recommended 1920×500 px · Max 5 MB</p>';
    ['prev_cit','prev_hi','prev_art'].forEach(id=>document.getElementById(id).textContent='—');document.getElementById('prev_jname').textContent='Journal Name';
    document.getElementById('serpJTitle').textContent='Journal Name';document.getElementById('serpJDesc').textContent='Meta description will appear here…';document.getElementById('serpJSlug').textContent='slug';slugEdited=false;
  }
  document.getElementById('journalModal').classList.remove('hidden');
  setTimeout(()=>document.getElementById('jName').focus(),100);
}

async function editJournal(id){const res=await fetch(`?ajax=get_journal&id=${id}`);const data=await res.json();openJournalModal(data);}

function closeJournalModal(){document.getElementById('journalModal').classList.add('hidden');}

async function toggleActive(id,btn){await fetch(`?ajax=toggle_journal&id=${id}`);const a=btn.textContent.trim()==='Active';btn.className=a?'badge bg-gray-100 text-gray-500 cursor-pointer hover:opacity-80 transition':'badge bg-green-100 text-green-700 cursor-pointer hover:opacity-80 transition';btn.innerHTML=a?'<span class="w-1.5 h-1.5 rounded-full bg-gray-400"></span> Inactive':'<span class="w-1.5 h-1.5 rounded-full bg-green-500"></span> Active';}
function deleteJournal(id,name){if(!confirm(`Delete journal "${name}"?\nAll sliders, info cards, notices and sections will also be removed.`))return;document.getElementById('deleteJournalId').value=id;document.getElementById('deleteJournalForm').submit();}
function openCategoryModal(){document.getElementById('categoryModal').classList.remove('hidden');}
function closeCategoryModal(){document.getElementById('categoryModal').classList.add('hidden');resetCatForm();}
function editCategory(id,name,order){document.getElementById('catFormTitle').innerHTML='<i class="fas fa-edit mr-1"></i> Edit Category';document.getElementById('catSaveBtn').textContent='Update Category';document.getElementById('catId').value=id;document.getElementById('catName').value=name;document.getElementById('catOrder').value=order;document.getElementById('catName').focus();}
function resetCatForm(){document.getElementById('catFormTitle').innerHTML='<i class="fas fa-plus-circle mr-1"></i> Add New Category';document.getElementById('catSaveBtn').textContent='Add Category';document.getElementById('catId').value=0;document.getElementById('catName').value='';document.getElementById('catOrder').value=0;}
function deleteCategory(id,name){if(!confirm(`Delete category "${name}"?`))return;document.getElementById('deleteCategoryId').value=id;document.getElementById('deleteCategoryForm').submit();}

<?php if($msg&&(isset($_POST['save_category'])||isset($_POST['delete_category']))): ?>openCategoryModal();<?php endif; ?>
</script>
</body>
</html>