<?php
// admin/homepage.php — Homepage Sections Management (Full)
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set('display_errors', 1);
session_start();
include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

// ══════════════════════════════════════════════════════
// AUTO-CREATE ALL TABLES
// ══════════════════════════════════════════════════════
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_hero` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`badge_text` VARCHAR(200) DEFAULT 'Independent since 2012 · Open Access',`title_line1` VARCHAR(200) DEFAULT 'Shaping the Future',`title_em1` VARCHAR(200) DEFAULT 'Research',`title_em2` VARCHAR(200) DEFAULT 'Excellence',`subtitle` TEXT,`btn1_text` VARCHAR(100) DEFAULT 'Explore Journals',`btn1_url` VARCHAR(500) DEFAULT '#',`btn2_text` VARCHAR(100) DEFAULT 'Call For Paper',`btn2_url` VARCHAR(500) DEFAULT '#',`trust_pill1` VARCHAR(200) DEFAULT 'Independent Publisher',`trust_pill2` VARCHAR(200) DEFAULT '100% Open Access',`bg_image_url` VARCHAR(500) NULL,`is_active` TINYINT(1) DEFAULT 1,`updated_at` DATETIME DEFAULT NOW() ON UPDATE NOW()) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_hero_stats` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`number` VARCHAR(50) NOT NULL,`superscript` VARCHAR(20) NULL,`label` VARCHAR(200) NOT NULL,`description` VARCHAR(300) NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_affordability` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`eyebrow` VARCHAR(200) DEFAULT 'Our Commitment',`title` VARCHAR(300) DEFAULT 'Affordability & Open Access',`description` TEXT,`btn_text` VARCHAR(100) DEFAULT 'See how it can work for you →',`btn_url` VARCHAR(500) DEFAULT '#',`is_active` TINYINT(1) DEFAULT 1,`updated_at` DATETIME DEFAULT NOW() ON UPDATE NOW()) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_gallery_header` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`eyebrow` VARCHAR(200) DEFAULT 'Our Services',`title` VARCHAR(300) DEFAULT 'What we offer for you',`description` TEXT,`is_active` TINYINT(1) DEFAULT 1,`updated_at` DATETIME DEFAULT NOW() ON UPDATE NOW()) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_tabs` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`tab_key` VARCHAR(100) NOT NULL UNIQUE,`tab_label` VARCHAR(100) NOT NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_gallery_cards` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`tab_id` INT UNSIGNED NOT NULL,`sort_order` INT UNSIGNED DEFAULT 0,`title` VARCHAR(300) NOT NULL,`description` TEXT NULL,`image_url` VARCHAR(500) NULL,`link_url` VARCHAR(500) NULL,`link_text` VARCHAR(100) DEFAULT 'Learn more →',`is_active` TINYINT(1) DEFAULT 1,KEY `idx_gc_tab` (`tab_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // NEW TABLES
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_journal_stats` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`number` VARCHAR(100) NOT NULL,`label` VARCHAR(200) NOT NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_section_headers` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`section_key` VARCHAR(100) NOT NULL UNIQUE,`eyebrow` VARCHAR(200) NULL,`title` VARCHAR(300) NULL,`description` TEXT NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_scope_tags` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`label` VARCHAR(200) NOT NULL,`link_url` VARCHAR(500) NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_submission_steps` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`step_number` VARCHAR(10) NOT NULL,`title` VARCHAR(200) NOT NULL,`description` TEXT NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_board_members` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`name` VARCHAR(200) NOT NULL,`initials` VARCHAR(10) NULL,`role` VARCHAR(200) NULL,`institution` VARCHAR(300) NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_indexing_tags` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`label` VARCHAR(200) NOT NULL,`badge` VARCHAR(100) NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_ethics_cards` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`title` VARCHAR(200) NOT NULL,`description` TEXT NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_why_cards` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`title` VARCHAR(200) NOT NULL,`description` TEXT NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hp_contact_cards` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,`sort_order` INT UNSIGNED DEFAULT 0,`title` VARCHAR(200) NOT NULL,`description` TEXT NULL,`link_text` VARCHAR(100) NULL,`link_url` VARCHAR(500) NULL,`is_active` TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // Seed defaults
    $heroCount = $pdo->query("SELECT COUNT(*) FROM hp_hero")->fetchColumn();
    if (!$heroCount) {
        $pdo->exec("INSERT INTO hp_hero (badge_text,title_line1,title_em1,title_em2,subtitle,btn1_text,btn1_url,btn2_text,btn2_url,trust_pill1,trust_pill2,bg_image_url) VALUES ('Independent since 2012 · Open Access','Shaping the Future','Research','Excellence','Pioneering excellence for global well-being through affordable, open-access scholarly publishing.','Explore Journals','https://communeglobal.com/journals.php','Call For Paper','https://rsisinternational.org/call-for-paper/','Independent Publisher','100% Open Access','https://rsisinternational.org/wp-content/uploads/2024/08/scene-with-business-person-working-futuristic-office-job-scaled.jpg')");
        $pdo->exec("INSERT INTO hp_hero_stats (sort_order,number,superscript,label,description) VALUES (0,'100','%','Open Access','Empowering knowledge sharing for all'),(1,'12','+','Years of Excellence','Over a decade of trusted publishing'),(2,'6K','+','Expert Reviewers','From 71+ countries worldwide'),(3,'40','+','Countries','Global authorship network')");
        $pdo->exec("INSERT INTO hp_affordability (eyebrow,title,description,btn_text,btn_url) VALUES ('Our Commitment','Affordability & Open Access','Supporting affordable research and open access for all since 2012. We believe knowledge should be free, accessible, and impactful.','See how it can work for you →','https://rsisinternational.org/affordable-scholarly-publishing/')");
        $pdo->exec("INSERT INTO hp_gallery_header (eyebrow,title,description) VALUES ('Our Services','What we offer for you','Comprehensive resources for authors, editors, reviewers and institutional partners.')");
        $pdo->exec("INSERT INTO hp_tabs (sort_order,tab_key,tab_label) VALUES (0,'authors','Authors'),(1,'editors','Editors & Reviewers'),(2,'partnerships','Partnerships')");
        $pdo->exec("INSERT INTO hp_journal_stats (sort_order,number,label) VALUES (0,'4×','Issues per year'),(1,'4-6 wk','Avg. review time'),(2,'Open','Access policy'),(3,'Double','Blind peer review')");
        $pdo->exec("INSERT INTO hp_section_headers (section_key,eyebrow,title,description) VALUES ('scope','Browse by Discipline','Aims & Scope','Discover research across a wide spectrum of academic disciplines.'),('submission','How It Works','Submission Process','A simple 6-step journey from manuscript to publication.'),('board','Our Experts','Editorial Board','Internationally recognised scholars guiding our publication standards.'),('indexing','Visibility','Indexing & Databases','Our journals are indexed across major international databases.'),('ethics','Our Standards','Publication Ethics','We uphold the highest standards of academic integrity and publishing ethics.'),('why','Benefits','Why Publish With Us','Join thousands of researchers who trust our platform.'),('contact','Get Started','Contact & Quick Links','We are here to help at every step of your publishing journey.')");
        $pdo->exec("INSERT INTO hp_scope_tags (sort_order,label,link_url) VALUES (0,'Social Science','#'),(1,'International Relations & Political Studies','#'),(2,'Regional Studies','#'),(3,'Humanities & Cultural Studies','#'),(4,'Education','#'),(5,'Business, Economics & Financial Studies','#'),(6,'Global Development & Policy','#'),(7,'Mental Health','#'),(8,'Language & Literature','#'),(9,'Public Health','#'),(10,'Fine Arts','#'),(11,'Legal Studies','#')");
        $pdo->exec("INSERT INTO hp_submission_steps (sort_order,step_number,title,description) VALUES (0,'1','Prepare manuscript','Follow author guidelines for format & citations'),(1,'2','Submit online','Upload via Communeglobal portal'),(2,'3','Editorial screening','Scope & quality check, 5-7 days'),(3,'4','Peer review','Double-blind by 2+ expert reviewers'),(4,'5','Decision','Accept / revise / reject with feedback'),(5,'6','Published + DOI','Live online with CrossRef DOI')");
        $pdo->exec("INSERT INTO hp_board_members (sort_order,name,initials,role,institution) VALUES (0,'Prof. Emmanuel Okafor','EO','Editor-in-Chief','Univ. of Lagos'),(1,'Dr. Ritu Sharma','RS','Associate Editor','JNU, India'),(2,'Prof. Li Chen','LC','Section Editor','Fudan Univ.'),(3,'Dr. Mariam Al-Hassan','MA','Review Board','AUC Egypt'),(4,'Prof. James Patterson','JP','Review Board','Univ. Manchester'),(5,'Dr. Fatima Santos','FS','Review Board','Univ. São Paulo')");
        $pdo->exec("INSERT INTO hp_indexing_tags (sort_order,label,badge) VALUES (0,'Google Scholar',NULL),(1,'CrossRef (DOI)',NULL),(2,'DOAJ','applied'),(3,'Index Copernicus',NULL),(4,'ROAD (ISSN Portal)',NULL),(5,'ResearchGate',NULL),(6,'Semantic Scholar',NULL),(7,'BASE Bielefeld',NULL),(8,'OpenAIRE',NULL),(9,'Academia.edu',NULL)");
        $pdo->exec("INSERT INTO hp_ethics_cards (sort_order,title,description) VALUES (0,'COPE guidelines','Follows all Committee on Publication Ethics guidelines for editors, authors, and reviewers.'),(1,'Plagiarism screening','All manuscripts screened using iThenticate before peer review begins.'),(2,'CC BY 4.0 license','Authors retain copyright. Articles distributed under Creative Commons Attribution 4.0.'),(3,'Conflict of interest','All authors, editors, and reviewers must declare conflicts before review participation.')");
        $pdo->exec("INSERT INTO hp_why_cards (sort_order,title,description) VALUES (0,'Global reach','Open access means your research is readable in every country — no paywalls, maximum citation potential.'),(1,'Fast, fair review','Double-blind peer review completed in 4–6 weeks with detailed, constructive reviewer feedback.'),(2,'Permanent DOI','Every accepted article gets a CrossRef DOI — permanently citable and traceable in academic databases.')");
        $pdo->exec("INSERT INTO hp_contact_cards (sort_order,title,description,link_text,link_url) VALUES (0,'Submit a manuscript','Ready to publish? Start your submission through our online portal. Open year-round.','Submit now','https://communeglobal.com/journals/social-science/submit'),(1,'Join as reviewer','Apply to become a peer reviewer and contribute to advancing social science scholarship.','Apply here','https://communeglobal.com/journals/social-science/board-members'),(2,'Contact editorial office','Queries on submissions, review status, or editorial policy — reach our team directly.','Get in touch','mailto:editor@communeglobal.com')");
    }
} catch(PDOException $e) {}

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

function handleUpload(string $field, string $subfolder='homepage'): ?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 for '$field'.");
    $dir=__DIR__."/../assets/images/$subfolder/"; if(!is_dir($dir)) mkdir($dir,0755,true);
    $name=uniqid('hp_',true).".$ext";
    if (!move_uploaded_file($f['tmp_name'],$dir.$name)) throw new Exception("Upload failed for '$field'.");
    return "assets/images/$subfolder/$name";
}
function p($v): string { return htmlspecialchars($v??'',ENT_QUOTES,'UTF-8'); }

// ══════════════════════════════════════════════════════
// AJAX
// ══════════════════════════════════════════════════════
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $id = (int)($_GET['id']??0);
    $ajax = $_GET['ajax'];
    $tableMap = ['get_card'=>'hp_gallery_cards','get_stat'=>'hp_hero_stats','get_tab'=>'hp_tabs','get_jstat'=>'hp_journal_stats','get_step'=>'hp_submission_steps','get_member'=>'hp_board_members','get_index'=>'hp_indexing_tags','get_ethics'=>'hp_ethics_cards','get_why'=>'hp_why_cards','get_contact'=>'hp_contact_cards','get_scope'=>'hp_scope_tags'];
    foreach ($tableMap as $key => $table) {
        if ($ajax === $key && $id) { $q=$pdo->prepare("SELECT * FROM $table WHERE id=?"); $q->execute([$id]); echo json_encode($q->fetch(PDO::FETCH_ASSOC)?:[]); exit; }
    }
    $toggleMap = ['toggle_card'=>'hp_gallery_cards','toggle_stat'=>'hp_hero_stats','toggle_tab'=>'hp_tabs','toggle_jstat'=>'hp_journal_stats','toggle_step'=>'hp_submission_steps','toggle_member'=>'hp_board_members','toggle_index'=>'hp_indexing_tags','toggle_ethics'=>'hp_ethics_cards','toggle_why'=>'hp_why_cards','toggle_contact'=>'hp_contact_cards','toggle_scope'=>'hp_scope_tags'];
    foreach ($toggleMap as $key => $table) {
        if ($ajax === $key && $id) { $pdo->prepare("UPDATE $table SET is_active=1-is_active WHERE id=?")->execute([$id]); echo json_encode(['success'=>true]); exit; }
    }
    $deleteMap = ['delete_card'=>'hp_gallery_cards','delete_stat'=>'hp_hero_stats','delete_jstat'=>'hp_journal_stats','delete_step'=>'hp_submission_steps','delete_member'=>'hp_board_members','delete_index'=>'hp_indexing_tags','delete_ethics'=>'hp_ethics_cards','delete_why'=>'hp_why_cards','delete_contact'=>'hp_contact_cards','delete_scope'=>'hp_scope_tags'];
    foreach ($deleteMap as $key => $table) {
        if ($ajax === $key && $id) { $pdo->prepare("DELETE FROM $table WHERE id=?")->execute([$id]); echo json_encode(['success'=>true]); exit; }
    }
    if ($ajax==='get_section_header' && isset($_GET['key'])) { $q=$pdo->prepare("SELECT * FROM hp_section_headers WHERE section_key=?"); $q->execute([$_GET['key']]); echo json_encode($q->fetch(PDO::FETCH_ASSOC)?:[]); exit; }
    if ($ajax==='get_tab'  && $id)  { $q=$pdo->prepare("SELECT * FROM hp_tabs WHERE id=?"); $q->execute([$id]); echo json_encode($q->fetch(PDO::FETCH_ASSOC)?:[]); exit; }
    exit;
}

// ══════════════════════════════════════════════════════
// GENERIC SIMPLE-ROW UPSERT (for simple tables)
// ══════════════════════════════════════════════════════
function simpleUpsert(PDO $pdo, string $table, string $pkField, array $fields, array $values, int $id, string &$msg, string &$msgType, string $name): void {
    try {
        $fieldList = implode(',', $fields);
        $ph = implode(',', array_fill(0, count($fields), '?'));
        $updateList = implode(',', array_map(fn($f)=>"$f=?", $fields));
        if ($id > 0) {
            $pdo->prepare("UPDATE $table SET $updateList WHERE $pkField=?")->execute([...$values, $id]);
        } else {
            $pdo->prepare("INSERT INTO $table ($fieldList) VALUES ($ph)")->execute($values);
        }
        $msg = "$name saved."; $msgType = 'success';
    } catch(Exception $e) { $msg = $e->getMessage(); $msgType = 'error'; }
}

// ══════════════════════════════════════════════════════
// POST HANDLERS
// ══════════════════════════════════════════════════════

// HERO
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_hero'])) {
    try {
        $bgUrl=trim($_POST['bg_image_url']??'');
        if (!empty($_FILES['hero_bg_file']['tmp_name'])) $bgUrl=handleUpload('hero_bg_file');
        $pdo->prepare("UPDATE hp_hero SET badge_text=?,title_line1=?,title_em1=?,title_em2=?,subtitle=?,btn1_text=?,btn1_url=?,btn2_text=?,btn2_url=?,trust_pill1=?,trust_pill2=?,bg_image_url=?,is_active=? WHERE id=1")
            ->execute([trim($_POST['badge_text']??''),trim($_POST['title_line1']??''),trim($_POST['title_em1']??''),trim($_POST['title_em2']??''),trim($_POST['subtitle']??''),trim($_POST['btn1_text']??''),trim($_POST['btn1_url']??''),trim($_POST['btn2_text']??''),trim($_POST['btn2_url']??''),trim($_POST['trust_pill1']??''),trim($_POST['trust_pill2']??''),$bgUrl?:null,isset($_POST['hero_active'])?1:0]);
        $msg='Hero section updated.'; $msgType='success';
    } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}
// STAT CARD (hero)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_stat'])) {
    $id=(int)($_POST['stat_id']??0);
    simpleUpsert($pdo,'hp_hero_stats','id',['sort_order','number','superscript','label','description'],[(int)$_POST['stat_sort'],trim($_POST['stat_number']??''),trim($_POST['stat_superscript']??''),trim($_POST['stat_label']??''),trim($_POST['stat_description']??'')],$id,$msg,$msgType,'Hero stat');
}
// AFFORDABILITY
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_affordability'])) {
    try { $pdo->prepare("UPDATE hp_affordability SET eyebrow=?,title=?,description=?,btn_text=?,btn_url=?,is_active=? WHERE id=1")->execute([trim($_POST['aff_eyebrow']??''),trim($_POST['aff_title']??''),trim($_POST['aff_description']??''),trim($_POST['aff_btn_text']??''),trim($_POST['aff_btn_url']??''),isset($_POST['aff_active'])?1:0]); $msg='Affordability updated.'; $msgType='success'; } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}
// GALLERY HEADER
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_gallery_header'])) {
    try { $pdo->prepare("UPDATE hp_gallery_header SET eyebrow=?,title=?,description=?,is_active=? WHERE id=1")->execute([trim($_POST['gh_eyebrow']??''),trim($_POST['gh_title']??''),trim($_POST['gh_description']??''),isset($_POST['gh_active'])?1:0]); $msg='Gallery header updated.'; $msgType='success'; } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}
// TAB
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_tab'])) {
    try {
        $id=(int)($_POST['tab_id']??0); $key=strtolower(preg_replace('/[^a-z0-9_]/i','_',trim($_POST['tab_key']??''))); $label=trim($_POST['tab_label']??'');
        if(empty($key)||empty($label)) throw new Exception("Key and label required.");
        if($id>0) $pdo->prepare("UPDATE hp_tabs SET sort_order=?,tab_key=?,tab_label=? WHERE id=?")->execute([(int)$_POST['tab_sort'],$key,$label,$id]);
        else $pdo->prepare("INSERT INTO hp_tabs (sort_order,tab_key,tab_label) VALUES (?,?,?)")->execute([(int)$_POST['tab_sort'],$key,$label]);
        $msg='Tab saved.'; $msgType='success';
    } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_tab'])) {
    $id=(int)$_POST['tab_id']; $cnt=$pdo->prepare("SELECT COUNT(*) FROM hp_gallery_cards WHERE tab_id=?"); $cnt->execute([$id]);
    if($cnt->fetchColumn()>0){ $msg="Cannot delete — tab has cards."; $msgType='error'; }
    else{ $pdo->prepare("DELETE FROM hp_tabs WHERE id=?")->execute([$id]); $msg="Tab deleted."; $msgType='success'; }
}
// GALLERY CARD
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_card'])) {
    try {
        $id=(int)($_POST['card_id']??0); $imgUrl=trim($_POST['card_image_url']??'');
        if(!empty($_FILES['card_image_file']['tmp_name'])) $imgUrl=handleUpload('card_image_file','homepage/cards');
        if(empty(trim($_POST['card_title']??''))) throw new Exception("Card title required.");
        if($id>0) $pdo->prepare("UPDATE hp_gallery_cards SET tab_id=?,sort_order=?,title=?,description=?,image_url=?,link_url=?,link_text=?,is_active=? WHERE id=?")->execute([(int)$_POST['card_tab_id'],(int)$_POST['card_sort'],trim($_POST['card_title']??''),trim($_POST['card_description']??''),$imgUrl?:null,trim($_POST['card_link_url']??'')?:null,trim($_POST['card_link_text']??'Learn more →'),isset($_POST['card_active'])?1:0,$id]);
        else $pdo->prepare("INSERT INTO hp_gallery_cards (tab_id,sort_order,title,description,image_url,link_url,link_text,is_active) VALUES (?,?,?,?,?,?,?,?)")->execute([(int)$_POST['card_tab_id'],(int)$_POST['card_sort'],trim($_POST['card_title']??''),trim($_POST['card_description']??''),$imgUrl?:null,trim($_POST['card_link_url']??'')?:null,trim($_POST['card_link_text']??'Learn more →'),isset($_POST['card_active'])?1:0]);
        $msg='Card saved.'; $msgType='success';
    } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}
// JOURNAL STATS
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_jstat'])) {
    $id=(int)($_POST['jstat_id']??0);
    simpleUpsert($pdo,'hp_journal_stats','id',['sort_order','number','label'],[(int)$_POST['jstat_sort'],trim($_POST['jstat_number']??''),trim($_POST['jstat_label']??'')],$id,$msg,$msgType,'Journal stat');
}
// SECTION HEADER (generic)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_section_header'])) {
    try {
        $key=trim($_POST['sh_key']??'');
        $pdo->prepare("INSERT INTO hp_section_headers (section_key,eyebrow,title,description,is_active) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE eyebrow=VALUES(eyebrow),title=VALUES(title),description=VALUES(description),is_active=VALUES(is_active)")
            ->execute([$key,trim($_POST['sh_eyebrow']??''),trim($_POST['sh_title']??''),trim($_POST['sh_description']??''),isset($_POST['sh_active'])?1:0]);
        $msg='Section header saved.'; $msgType='success';
    } catch(Exception $e){ $msg=$e->getMessage(); $msgType='error'; }
}
// SCOPE TAG
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_scope'])) {
    $id=(int)($_POST['scope_id']??0);
    simpleUpsert($pdo,'hp_scope_tags','id',['sort_order','label','link_url'],[(int)$_POST['scope_sort'],trim($_POST['scope_label']??''),trim($_POST['scope_url']??'')],$id,$msg,$msgType,'Scope tag');
}
// SUBMISSION STEP
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_step'])) {
    $id=(int)($_POST['step_id']??0);
    simpleUpsert($pdo,'hp_submission_steps','id',['sort_order','step_number','title','description'],[(int)$_POST['step_sort'],trim($_POST['step_number']??''),trim($_POST['step_title']??''),trim($_POST['step_description']??'')],$id,$msg,$msgType,'Step');
}
// BOARD MEMBER
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_member'])) {
    $id=(int)($_POST['member_id']??0); $name=trim($_POST['member_name']??'');
    $initials=trim($_POST['member_initials']??'') ?: strtoupper(implode('',array_map(fn($w)=>$w[0],explode(' ',$name))));
    simpleUpsert($pdo,'hp_board_members','id',['sort_order','name','initials','role','institution'],[(int)$_POST['member_sort'],$name,$initials,trim($_POST['member_role']??''),trim($_POST['member_institution']??'')],$id,$msg,$msgType,'Board member');
}
// INDEXING TAG
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_index'])) {
    $id=(int)($_POST['index_id']??0);
    simpleUpsert($pdo,'hp_indexing_tags','id',['sort_order','label','badge'],[(int)$_POST['index_sort'],trim($_POST['index_label']??''),trim($_POST['index_badge']??'')?:null],$id,$msg,$msgType,'Indexing tag');
}
// ETHICS CARD
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_ethics'])) {
    $id=(int)($_POST['ethics_id']??0);
    simpleUpsert($pdo,'hp_ethics_cards','id',['sort_order','title','description'],[(int)$_POST['ethics_sort'],trim($_POST['ethics_title']??''),trim($_POST['ethics_description']??'')],$id,$msg,$msgType,'Ethics card');
}
// WHY CARD
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_why'])) {
    $id=(int)($_POST['why_id']??0);
    simpleUpsert($pdo,'hp_why_cards','id',['sort_order','title','description'],[(int)$_POST['why_sort'],trim($_POST['why_title']??''),trim($_POST['why_description']??'')],$id,$msg,$msgType,'Why card');
}
// CONTACT CARD
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_contact'])) {
    $id=(int)($_POST['contact_id']??0);
    simpleUpsert($pdo,'hp_contact_cards','id',['sort_order','title','description','link_text','link_url'],[(int)$_POST['contact_sort'],trim($_POST['contact_title']??''),trim($_POST['contact_description']??''),trim($_POST['contact_link_text']??''),trim($_POST['contact_link_url']??'')],$id,$msg,$msgType,'Contact card');
}

// ══════════════════════════════════════════════════════
// FETCH DATA
// ══════════════════════════════════════════════════════
$hero          = $pdo->query("SELECT * FROM hp_hero WHERE id=1")->fetch(PDO::FETCH_ASSOC) ?: [];
$heroStats     = $pdo->query("SELECT * FROM hp_hero_stats ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$affordability = $pdo->query("SELECT * FROM hp_affordability WHERE id=1")->fetch(PDO::FETCH_ASSOC) ?: [];
$galleryHeader = $pdo->query("SELECT * FROM hp_gallery_header WHERE id=1")->fetch(PDO::FETCH_ASSOC) ?: [];
$tabs          = $pdo->query("SELECT * FROM hp_tabs ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$filterTab     = (int)($_GET['tab_filter']??0);
$cardQuery     = "SELECT c.*,t.tab_label FROM hp_gallery_cards c LEFT JOIN hp_tabs t ON t.id=c.tab_id".($filterTab>0?" WHERE c.tab_id=$filterTab":"")." ORDER BY c.tab_id ASC,c.sort_order ASC";
$cards         = $pdo->query($cardQuery)->fetchAll(PDO::FETCH_ASSOC);
$journalStats  = $pdo->query("SELECT * FROM hp_journal_stats ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$scopeTags     = $pdo->query("SELECT * FROM hp_scope_tags ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$steps         = $pdo->query("SELECT * FROM hp_submission_steps ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$boardMembers  = $pdo->query("SELECT * FROM hp_board_members ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$indexingTags  = $pdo->query("SELECT * FROM hp_indexing_tags ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$ethicsCards   = $pdo->query("SELECT * FROM hp_ethics_cards ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$whyCards      = $pdo->query("SELECT * FROM hp_why_cards ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$contactCards  = $pdo->query("SELECT * FROM hp_contact_cards ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);

// Section headers
$shdrs = [];
foreach ($pdo->query("SELECT * FROM hp_section_headers")->fetchAll(PDO::FETCH_ASSOC) as $sh) $shdrs[$sh['section_key']] = $sh;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Homepage 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);}
  .badge{padding:2px 10px;border-radius:20px;font-size:11px;font-weight:600;display:inline-flex;align-items:center;gap:4px;}
  .section-card{background:#fff;border-radius:16px;border:1px solid #e5e7eb;overflow:hidden;}
  .sec-head{background:linear-gradient(135deg,#f8faff,#eff6ff);padding:14px 20px;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;justify-content:space-between;}
  .sec-title{font-weight:700;font-size:14px;color:#1e293b;display:flex;align-items:center;gap:8px;}
  .stat-card{transition:box-shadow .2s,transform .2s;}
  .stat-card:hover{box-shadow:0 4px 20px rgba(0,0,0,.08);transform:translateY(-2px);}
  .trow{transition:background .15s;}.trow:hover{background:#f8faff;}
  .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);}
  .form-field{width:100%;border:1px solid #e2e8f0;border-radius:.5rem;padding:.5rem .75rem;font-size:.8rem;color:#374151;transition:border-color .15s;background:#fff;}
  .form-field:focus{border-color:#3b82f6;box-shadow:0 0 0 2px rgba(59,130,246,.12);outline:none;}
  .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;}
  .nav-tab{padding:8px 16px;border-radius:8px;font-size:12.5px;font-weight:500;cursor:pointer;color:#64748b;border:none;background:transparent;transition:all .15s;white-space:nowrap;}
  .nav-tab.active{background:#eff6ff;color:#1d4ed8;font-weight:600;}
  .main-panel{display:none;}.main-panel.active{display:block;}
  .mini-badge{font-size:10px;background:#e0f2fe;color:#0369a1;padding:1px 6px;border-radius:4px;font-weight:600;}
</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-home text-blue-600"></i> Homepage Management</h1><p class="text-xs text-gray-400 mt-0.5">Manage all homepage sections — Hero, Stats, Tabs, Board, Indexing, Ethics & more</p></div>
    <a href="../index.php" target="_blank" class="border border-gray-300 text-gray-600 px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-50 flex items-center gap-2 transition"><i class="fas fa-external-link-alt text-blue-500"></i> Preview Homepage</a>
  </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">
<!-- STAT PILLS -->
<div class="grid grid-cols-5 gap-3 mb-5">
  <?php foreach([['fa-image','bg-blue-100','text-blue-600','Hero','1 section'],['fa-th-large','bg-indigo-100','text-indigo-600','Gallery',count($cards).' cards'],['fa-users','bg-teal-100','text-teal-600','Board',count($boardMembers).' members'],['fa-tag','bg-purple-100','text-purple-600','Indexing',count($indexingTags).' tags'],['fa-shield-alt','bg-pink-100','text-pink-600','Ethics',count($ethicsCards).' cards']] as [$ic,$bg,$tc,$lbl,$sub]): ?>
  <div class="stat-card bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-3"><div class="w-10 h-10 rounded-xl <?=$bg?> flex items-center justify-center"><i class="fas <?=$ic?> <?=$tc?>"></i></div><div><div class="font-bold text-gray-800"><?=$lbl?></div><div class="text-xs text-gray-400"><?=$sub?></div></div></div>
  <?php endforeach; ?>
</div>

<!-- MAIN NAV -->
<div class="bg-white rounded-xl border border-gray-200 mb-5 p-2.5 flex gap-1 overflow-x-auto flex-wrap">
  <button class="nav-tab active" onclick="switchMain('hero')"       id="mnav-hero">      <i class="fas fa-image mr-1 text-blue-400 text-xs"></i>Hero</button>
  <button class="nav-tab"        onclick="switchMain('stats')"      id="mnav-stats">     <i class="fas fa-chart-bar mr-1 text-teal-400 text-xs"></i>Hero Stats</button>
  <button class="nav-tab"        onclick="switchMain('aff')"        id="mnav-aff">       <i class="fas fa-heart mr-1 text-pink-400 text-xs"></i>Affordability</button>
  <button class="nav-tab"        onclick="switchMain('gallery')"    id="mnav-gallery">   <i class="fas fa-th-large mr-1 text-indigo-400 text-xs"></i>Gallery &amp; Tabs</button>
  <button class="nav-tab"        onclick="switchMain('jstats')"     id="mnav-jstats">    <i class="fas fa-table mr-1 text-amber-400 text-xs"></i>Journal Stats</button>
  <button class="nav-tab"        onclick="switchMain('scope')"      id="mnav-scope">     <i class="fas fa-tags mr-1 text-green-400 text-xs"></i>Aims &amp; Scope</button>
  <button class="nav-tab"        onclick="switchMain('submission')" id="mnav-submission"><i class="fas fa-list-ol mr-1 text-cyan-400 text-xs"></i>Submission</button>
  <button class="nav-tab"        onclick="switchMain('board')"      id="mnav-board">     <i class="fas fa-users mr-1 text-teal-400 text-xs"></i>Board</button>
  <button class="nav-tab"        onclick="switchMain('indexing')"   id="mnav-indexing">  <i class="fas fa-database mr-1 text-purple-400 text-xs"></i>Indexing</button>
  <button class="nav-tab"        onclick="switchMain('ethics')"     id="mnav-ethics">    <i class="fas fa-shield-alt mr-1 text-pink-400 text-xs"></i>Ethics</button>
  <button class="nav-tab"        onclick="switchMain('why')"        id="mnav-why">       <i class="fas fa-star mr-1 text-yellow-400 text-xs"></i>Why Publish</button>
  <button class="nav-tab"        onclick="switchMain('contact')"    id="mnav-contact">   <i class="fas fa-envelope mr-1 text-orange-400 text-xs"></i>Contact</button>
</div>

<!-- ══ HERO ══ -->
<div id="panel-hero" class="main-panel active">
  <div class="section-card">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-image text-blue-500"></i> Hero Section</span></div>
    <form method="POST" enctype="multipart/form-data" class="p-6 space-y-5">
      <input type="hidden" name="save_hero" value="1">
      <div class="rounded-xl overflow-hidden relative" style="background:linear-gradient(135deg,#0f172a,#1e3a5f);min-height:70px;">
        <div id="heroBgStrip" class="absolute inset-0 bg-cover bg-center opacity-30" <?=!empty($hero['bg_image_url'])?'style="background-image:url(/'.ltrim($hero['bg_image_url']??'/','/').'/)"':''?>></div>
        <div class="relative z-10 p-4 flex items-center justify-between gap-4">
          <div class="text-white"><div class="text-[10px] bg-white/20 rounded-full px-3 py-0.5 inline-block mb-1" id="phBadge"><?=p($hero['badge_text']??'')?></div><div class="font-bold text-sm" id="phTitle"><?=p($hero['title_line1']??'')?> / <?=p($hero['title_em1']??'')?></div><div class="text-xs opacity-60 mt-1" id="phSub"><?=p(substr($hero['subtitle']??'',0,80))?></div></div>
          <div class="flex gap-2 flex-shrink-0"><span class="bg-orange-500 text-white text-xs px-3 py-1.5 rounded-lg" id="phBtn1"><?=p($hero['btn1_text']??'')?></span><span class="border border-white/40 text-white text-xs px-3 py-1.5 rounded-lg" id="phBtn2"><?=p($hero['btn2_text']??'')?></span></div>
        </div>
      </div>
      <div class="grid grid-cols-2 gap-5">
        <div class="space-y-3">
          <div><label class="block text-xs font-semibold text-gray-500 mb-1">Badge Text</label><input type="text" name="badge_text" value="<?=p($hero['badge_text']??'')?>" oninput="document.getElementById('phBadge').textContent=this.value" class="form-field"></div>
          <div class="grid grid-cols-3 gap-2">
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Title Line</label><input type="text" name="title_line1" value="<?=p($hero['title_line1']??'')?>" oninput="updateHPTitle()" class="form-field"></div>
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Italic 1</label><input type="text" name="title_em1" value="<?=p($hero['title_em1']??'')?>" oninput="updateHPTitle()" class="form-field"></div>
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Italic 2</label><input type="text" name="title_em2" value="<?=p($hero['title_em2']??'')?>" oninput="updateHPTitle()" class="form-field"></div>
          </div>
          <div><label class="block text-xs font-semibold text-gray-500 mb-1">Subtitle</label><textarea name="subtitle" rows="2" oninput="document.getElementById('phSub').textContent=this.value.substring(0,80)" class="form-field resize-none"><?=p($hero['subtitle']??'')?></textarea></div>
          <div class="grid grid-cols-2 gap-2">
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Trust Pill 1</label><input type="text" name="trust_pill1" value="<?=p($hero['trust_pill1']??'')?>" class="form-field"></div>
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Trust Pill 2</label><input type="text" name="trust_pill2" value="<?=p($hero['trust_pill2']??'')?>" class="form-field"></div>
          </div>
        </div>
        <div class="space-y-3">
          <div class="grid grid-cols-2 gap-2">
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Btn 1 Text</label><input type="text" name="btn1_text" value="<?=p($hero['btn1_text']??'')?>" oninput="document.getElementById('phBtn1').textContent=this.value" class="form-field"></div>
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Btn 1 URL</label><input type="url" name="btn1_url" value="<?=p($hero['btn1_url']??'')?>" class="form-field font-mono text-xs"></div>
          </div>
          <div class="grid grid-cols-2 gap-2">
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Btn 2 Text</label><input type="text" name="btn2_text" value="<?=p($hero['btn2_text']??'')?>" oninput="document.getElementById('phBtn2').textContent=this.value" class="form-field"></div>
            <div><label class="block text-xs font-semibold text-gray-500 mb-1">Btn 2 URL</label><input type="url" name="btn2_url" value="<?=p($hero['btn2_url']??'')?>" class="form-field font-mono text-xs"></div>
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-500 mb-1">Background Image</label>
            <div class="upload-zone text-xs" id="heroBgZone" onclick="document.getElementById('heroBgFile').click()"><i class="fas fa-cloud-upload-alt text-2xl text-teal-300 mb-1 block"></i><p class="text-gray-500">Click to upload</p></div>
            <input type="file" id="heroBgFile" name="hero_bg_file" accept="image/*" class="hidden" onchange="handleBgUp(this)">
            <input type="text" name="bg_image_url" id="heroBgUrl" value="<?=p($hero['bg_image_url']??'')?>" placeholder="or paste URL" oninput="if(this.value)document.getElementById('heroBgStrip').style.backgroundImage='url(/'+this.value.replace(/^\//,'')+')'" class="form-field font-mono text-xs mt-1">
          </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="hero_active" value="1" <?=($hero['is_active']??1)?'checked':''?> class="sr-only peer"><div class="w-10 h-5 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-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div></label>
            <span class="text-xs font-medium text-gray-700">Active</span>
          </div>
        </div>
      </div>
      <div class="flex justify-end pt-2 border-t border-gray-100"><button type="submit" class="btn-primary px-6 py-2.5 rounded-lg text-sm font-semibold flex items-center gap-2"><i class="fas fa-save"></i> Save Hero</button></div>
    </form>
  </div>
</div>

<!-- ══ HERO STATS ══ -->
<div id="panel-stats" class="main-panel">
  <?php echo buildSimplePanel('Hero Stats','hp_hero_stats','stat','fa-chart-bar','text-teal-500',
    [['Number','stat_number','text','number'],['Superscript','stat_superscript','text','% or +'],['Label','stat_label','text','Open Access'],['Description','stat_description','text','Empowering...'],['Sort','stat_sort','number','0']],
    [['number','','w-20'],['label','font-semibold text-gray-800',''],['description','text-xs text-gray-500',''],['sort_order','font-mono text-xs text-gray-400','w-12']],$heroStats,'number+superscript','stat_id'); ?>
</div>

<!-- ══ AFFORDABILITY ══ -->
<div id="panel-aff" class="main-panel">
  <div class="section-card">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-heart text-pink-500"></i> Affordability Strip</span></div>
    <form method="POST" class="p-6 space-y-4">
      <input type="hidden" name="save_affordability" value="1">
      <div class="grid grid-cols-2 gap-5">
        <div class="space-y-3">
          <div><label class="block text-xs font-semibold text-gray-500 mb-1">Eyebrow</label><input type="text" name="aff_eyebrow" value="<?=p($affordability['eyebrow']??'')?>" class="form-field"></div>
          <div><label class="block text-xs font-semibold text-gray-500 mb-1">Title</label><input type="text" name="aff_title" value="<?=p($affordability['title']??'')?>" class="form-field"></div>
          <div><label class="block text-xs font-semibold text-gray-500 mb-1">Description</label><textarea name="aff_description" rows="3" class="form-field resize-none"><?=p($affordability['description']??'')?></textarea></div>
        </div>
        <div class="space-y-3">
          <div><label class="block text-xs font-semibold text-gray-500 mb-1">Button Text</label><input type="text" name="aff_btn_text" value="<?=p($affordability['btn_text']??'')?>" class="form-field"></div>
          <div><label class="block text-xs font-semibold text-gray-500 mb-1">Button URL</label><input type="url" name="aff_btn_url" value="<?=p($affordability['btn_url']??'')?>" class="form-field font-mono text-xs"></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="aff_active" value="1" <?=($affordability['is_active']??1)?'checked':''?> class="sr-only peer"><div class="w-10 h-5 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-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div></label><span class="text-xs font-medium text-gray-700">Active</span></div>
        </div>
      </div>
      <div class="flex justify-end border-t border-gray-100 pt-3"><button type="submit" class="btn-primary px-5 py-2 rounded-lg text-sm font-semibold flex items-center gap-2"><i class="fas fa-save"></i> Save</button></div>
    </form>
  </div>
</div>

<!-- ══ GALLERY & TABS ══ -->
<div id="panel-gallery" class="main-panel">
  <!-- Gallery Header -->
  <div class="section-card mb-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-align-center text-indigo-500"></i> Gallery Section Header</span></div>
    <form method="POST" class="p-4">
      <input type="hidden" name="save_gallery_header" value="1">
      <div class="grid grid-cols-4 gap-3 items-end">
        <div><label class="block text-xs font-semibold text-gray-500 mb-1">Eyebrow</label><input type="text" name="gh_eyebrow" value="<?=p($galleryHeader['eyebrow']??'')?>" class="form-field"></div>
        <div><label class="block text-xs font-semibold text-gray-500 mb-1">Title</label><input type="text" name="gh_title" value="<?=p($galleryHeader['title']??'')?>" class="form-field"></div>
        <div><label class="block text-xs font-semibold text-gray-500 mb-1">Description</label><input type="text" name="gh_description" value="<?=p($galleryHeader['description']??'')?>" class="form-field"></div>
        <div class="flex items-center gap-2">
          <label class="relative inline-flex items-center cursor-pointer"><input type="checkbox" name="gh_active" value="1" <?=($galleryHeader['is_active']??1)?'checked':''?> class="sr-only peer"><div class="w-9 h-5 bg-gray-200 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-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div></label>
          <button type="submit" class="btn-primary px-4 py-2 rounded-lg text-xs font-semibold flex items-center gap-1"><i class="fas fa-save text-xs"></i> Save</button>
        </div>
      </div>
    </form>
  </div>
  <!-- Tabs -->
  <div class="section-card mb-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-folder text-purple-500"></i> Gallery Tabs</span><button onclick="openModal('tabModal')" class="btn-primary 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 Tab</button></div>
    <div class="p-3">
      <?php if(empty($tabs)): ?><div class="text-center py-6 text-gray-400 text-sm">No tabs yet</div><?php else: ?>
      <div class="flex gap-2 mb-3 bg-gray-50 rounded-lg p-2"><?php foreach($tabs as $t): if(!$t['is_active']) continue; ?><span class="px-3 py-1.5 rounded-lg text-sm font-medium bg-white shadow text-gray-700"><?=p($t['tab_label'])?></span><?php endforeach; ?></div>
      <table class="w-full text-xs"><thead class="bg-gray-50 text-gray-400 uppercase tracking-wide"><tr><th class="px-3 py-2 text-left">Order</th><th class="px-3 py-2 text-left">Key</th><th class="px-3 py-2 text-left">Label</th><th class="px-3 py-2 text-center">Status</th><th class="px-3 py-2 text-right">Actions</th></tr></thead><tbody class="divide-y divide-gray-50">
      <?php foreach($tabs as $t): ?><tr class="trow"><td class="px-3 py-2 text-gray-400"><?=$t['sort_order']?></td><td class="px-3 py-2"><code class="bg-gray-100 px-1.5 py-0.5 rounded text-purple-700"><?=p($t['tab_key'])?></code></td><td class="px-3 py-2 font-semibold text-gray-800"><?=p($t['tab_label'])?></td><td class="px-3 py-2 text-center"><button onclick="toggleAjax('toggle_tab',<?=$t['id']?>,this)" class="badge <?=$t['is_active']?'bg-green-100 text-green-700':'bg-gray-100 text-gray-500'?> cursor-pointer"><span class="w-1.5 h-1.5 rounded-full <?=$t['is_active']?'bg-green-500':'bg-gray-400'?>"></span><?=$t['is_active']?'Active':'Inactive'?></button></td><td class="px-3 py-2 text-right"><div class="flex gap-1 justify-end"><button onclick="editTab(<?=$t['id']?>)" 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 transition"><i class="fas fa-edit"></i></button><button onclick="deleteTabConfirm(<?=$t['id']?>,'<?=p($t['tab_label'])?>')" 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 transition"><i class="fas fa-trash"></i></button></div></td></tr><?php endforeach; ?>
      </tbody></table><?php endif; ?>
    </div>
  </div>
  <!-- Cards -->
  <div class="section-card">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-th-large text-indigo-500"></i> Gallery Cards <span class="ml-1 text-xs font-normal text-gray-400"><?=count($cards)?> total</span></span>
      <div class="flex gap-2"><form method="GET" class="flex gap-1"><input type="hidden" name="panel" value="gallery"><select name="tab_filter" onchange="this.form.submit()" class="border border-gray-200 rounded-lg px-2 py-1.5 text-xs"><option value="">All Tabs</option><?php foreach($tabs as $t): ?><option value="<?=$t['id']?>" <?=$filterTab==$t['id']?'selected':''?>><?=p($t['tab_label'])?></option><?php endforeach; ?></select></form><button onclick="openModal('cardModal')" class="btn-primary 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 Card</button></div>
    </div>
    <div class="p-4">
      <?php if(empty($cards)): ?><div class="text-center py-8 text-gray-400 text-sm">No cards yet</div><?php else: ?>
      <div class="grid grid-cols-3 gap-3">
        <?php foreach($cards as $card): ?>
        <div class="flex gap-3 bg-gray-50 border border-gray-100 rounded-xl p-3 <?=!$card['is_active']?'opacity-50':''?> hover:border-blue-200 transition group">
          <div class="w-12 h-12 rounded-lg overflow-hidden border border-gray-200 flex-shrink-0 bg-gray-100"><?php if($card['image_url']): ?><img src="<?=p($card['image_url'])?>" class="w-full h-full object-cover" onerror="this.style.display='none'"><?php else: ?><div class="w-full h-full flex items-center justify-center"><i class="fas fa-image text-gray-300 text-xs"></i></div><?php endif; ?></div>
          <div class="flex-1 min-w-0"><div class="font-semibold text-gray-800 text-xs truncate"><?=p($card['title'])?></div><div class="text-[10px] text-gray-400 mt-0.5 truncate"><?=p($card['description']??'')?></div><span class="badge bg-purple-50 text-purple-700 text-[9px] mt-1"><?=p($card['tab_label']??'—')?></span></div>
          <div class="flex flex-col gap-1 opacity-0 group-hover:opacity-100 transition">
            <button onclick="editCard(<?=$card['id']?>)" class="w-6 h-6 rounded border border-gray-200 flex items-center justify-center text-gray-400 hover:text-blue-600 hover:bg-blue-50 transition text-[10px]"><i class="fas fa-edit"></i></button>
            <button onclick="toggleAjax('toggle_card',<?=$card['id']?>,this)" class="w-6 h-6 rounded border border-gray-200 flex items-center justify-center text-gray-400 hover:text-amber-600 hover:bg-amber-50 transition text-[10px]"><i class="fas fa-toggle-on"></i></button>
            <button onclick="deleteAjax('delete_card',<?=$card['id']?>,this,'.group')" class="w-6 h-6 rounded border border-gray-200 flex items-center justify-center text-gray-400 hover:text-red-600 hover:bg-red-50 transition text-[10px]"><i class="fas fa-trash"></i></button>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══ JOURNAL STATS ══ -->
<div id="panel-jstats" class="main-panel">
  <?php echo buildSectionHeaderForm('jstats','Journal Stats Section Header',$shdrs,'fa-table','text-amber-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-table text-amber-500"></i> Journal Stats Cards <span class="mini-badge ml-1"><?=count($journalStats)?></span></span><button onclick="openSimpleModal('jstatModal')" class="btn-primary 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 Stat</button></div>
    <?php echo buildSimpleTable([['Number','jstat_number','font-bold text-gray-800 text-lg'],['Label','jstat_label','text-gray-600'],['sort_order','Sort','font-mono text-xs text-gray-400 w-12']],$journalStats,'jstat','jstat'); ?>
  </div>
</div>

<!-- ══ SCOPE TAGS ══ -->
<div id="panel-scope" class="main-panel">
  <?php echo buildSectionHeaderForm('scope','Aims & Scope Section Header',$shdrs,'fa-tags','text-green-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-tags text-green-500"></i> Scope Tags <span class="mini-badge ml-1"><?=count($scopeTags)?></span></span><button onclick="openSimpleModal('scopeModal')" class="btn-primary 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 Tag</button></div>
    <div class="p-4">
      <?php if(empty($scopeTags)): ?><div class="text-center py-6 text-gray-400 text-sm">No tags yet</div><?php else: ?>
      <div class="flex flex-wrap gap-2 mb-4">
        <?php foreach($scopeTags as $t): ?><span class="<?=!$t['is_active']?'opacity-40 line-through':''?> bg-white border border-gray-200 text-gray-700 text-xs font-medium px-3 py-1.5 rounded-lg cursor-pointer hover:border-blue-300 transition flex items-center gap-1.5 group" onclick="editScope(<?=$t['id']?>)"><?=p($t['label'])?><button onclick="event.stopPropagation();deleteAjax('delete_scope',<?=$t['id']?>,this,'.group')" class="text-[10px] text-gray-300 hover:text-red-500 ml-1">✕</button></span><?php endforeach; ?>
      </div>
      <div class="text-xs text-gray-400">Click a tag to edit · ✕ to delete</div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══ SUBMISSION STEPS ══ -->
<div id="panel-submission" class="main-panel">
  <?php echo buildSectionHeaderForm('submission','Submission Process Section Header',$shdrs,'fa-list-ol','text-cyan-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-list-ol text-cyan-500"></i> Submission Steps <span class="mini-badge ml-1"><?=count($steps)?></span></span><button onclick="openSimpleModal('stepModal')" class="btn-primary 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 Step</button></div>
    <?php echo buildSimpleTable([['step_number','#','font-bold text-blue-600 w-10'],['title','Title','font-semibold text-gray-800'],['description','Desc','text-xs text-gray-500'],['sort_order','Sort','font-mono text-xs text-gray-400 w-12']],$steps,'step','step'); ?>
  </div>
</div>

<!-- ══ BOARD MEMBERS ══ -->
<div id="panel-board" class="main-panel">
  <?php echo buildSectionHeaderForm('board','Editorial Board Section Header',$shdrs,'fa-users','text-teal-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-users text-teal-500"></i> Board Members <span class="mini-badge ml-1"><?=count($boardMembers)?></span></span><button onclick="openSimpleModal('memberModal')" class="btn-primary 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 Member</button></div>
    <div class="p-4">
      <?php if(empty($boardMembers)): ?><div class="text-center py-6 text-gray-400 text-sm">No members yet</div><?php else: ?>
      <div class="grid grid-cols-3 gap-3">
        <?php foreach($boardMembers as $m): ?>
        <div class="flex gap-3 bg-gray-50 border border-gray-100 rounded-xl p-3 hover:border-teal-200 transition group <?=!$m['is_active']?'opacity-50':''?>">
          <div class="w-10 h-10 rounded-full bg-gradient-to-br from-slate-700 to-slate-500 flex items-center justify-center text-white font-bold text-sm flex-shrink-0"><?=p($m['initials']??'??')?></div>
          <div class="flex-1 min-w-0"><div class="font-semibold text-gray-800 text-xs truncate"><?=p($m['name'])?></div><div class="text-[10px] text-gray-400"><?=p($m['role'])?></div><div class="text-[10px] text-gray-400 truncate"><?=p($m['institution']??'')?></div></div>
          <div class="flex flex-col gap-1 opacity-0 group-hover:opacity-100 transition">
            <button onclick="editMember(<?=$m['id']?>)" class="w-6 h-6 rounded border border-gray-200 flex items-center justify-center text-gray-400 hover:text-blue-600 hover:bg-blue-50 transition text-[10px]"><i class="fas fa-edit"></i></button>
            <button onclick="deleteAjax('delete_member',<?=$m['id']?>,this,'.group')" class="w-6 h-6 rounded border border-gray-200 flex items-center justify-center text-gray-400 hover:text-red-600 hover:bg-red-50 transition text-[10px]"><i class="fas fa-trash"></i></button>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══ INDEXING ══ -->
<div id="panel-indexing" class="main-panel">
  <?php echo buildSectionHeaderForm('indexing','Indexing Section Header',$shdrs,'fa-database','text-purple-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-database text-purple-500"></i> Indexing Tags <span class="mini-badge ml-1"><?=count($indexingTags)?></span></span><button onclick="openSimpleModal('indexModal')" class="btn-primary 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 Tag</button></div>
    <div class="p-4">
      <?php if(empty($indexingTags)): ?><div class="text-center py-6 text-gray-400 text-sm">No tags yet</div><?php else: ?>
      <div class="flex flex-wrap gap-2 mb-3">
        <?php foreach($indexingTags as $t): ?><span class="<?=!$t['is_active']?'opacity-40 line-through':''?> bg-white border border-gray-200 text-gray-700 text-xs font-medium px-3 py-1.5 rounded-lg flex items-center gap-1.5 cursor-pointer hover:border-purple-300 transition group" onclick="editIndex(<?=$t['id']?>)"><?=p($t['label'])?><?php if(!empty($t['badge'])): ?><span class="mini-badge"><?=p($t['badge'])?></span><?php endif; ?><button onclick="event.stopPropagation();deleteAjax('delete_index',<?=$t['id']?>,this,'.group')" class="text-[10px] text-gray-300 hover:text-red-500 ml-0.5">✕</button></span><?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══ ETHICS CARDS ══ -->
<div id="panel-ethics" class="main-panel">
  <?php echo buildSectionHeaderForm('ethics','Publication Ethics Section Header',$shdrs,'fa-shield-alt','text-pink-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-shield-alt text-pink-500"></i> Ethics Cards <span class="mini-badge ml-1"><?=count($ethicsCards)?></span></span><button onclick="openSimpleModal('ethicsModal')" class="btn-primary 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 Card</button></div>
    <?php echo buildSimpleTable([['title','Title','font-semibold text-gray-800'],['description','Description','text-xs text-gray-500 max-w-xs'],['sort_order','Sort','font-mono text-xs text-gray-400 w-12']],$ethicsCards,'ethics','ethics'); ?>
  </div>
</div>

<!-- ══ WHY PUBLISH ══ -->
<div id="panel-why" class="main-panel">
  <?php echo buildSectionHeaderForm('why','Why Publish Section Header',$shdrs,'fa-star','text-yellow-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-star text-yellow-500"></i> Why Publish Cards <span class="mini-badge ml-1"><?=count($whyCards)?></span></span><button onclick="openSimpleModal('whyModal')" 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 Card</button></div>
    <?php echo buildSimpleTable([['title','Title','font-semibold text-gray-800'],['description','Description','text-xs text-gray-500 max-w-xs'],['sort_order','Sort','font-mono text-xs text-gray-400 w-12']],$whyCards,'why','why'); ?>
  </div>
</div>

<!-- ══ CONTACT CARDS ══ -->
<div id="panel-contact" class="main-panel">
  <?php echo buildSectionHeaderForm('contact','Contact & Quick Links Header',$shdrs,'fa-envelope','text-orange-500'); ?>
  <div class="section-card mt-4">
    <div class="sec-head"><span class="sec-title"><i class="fas fa-envelope text-orange-500"></i> Contact Cards <span class="mini-badge ml-1"><?=count($contactCards)?></span></span><button onclick="openSimpleModal('contactModal')" class="btn-primary 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 Card</button></div>
    <?php echo buildSimpleTable([['title','Title','font-semibold text-gray-800'],['description','Description','text-xs text-gray-500'],['link_text','Link Text','text-xs text-blue-600'],['sort_order','Sort','font-mono text-xs text-gray-400 w-12']],$contactCards,'contact','contact'); ?>
  </div>
</div>

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

<?php
// ══════════════════════════════════════════════════════
// PHP HELPERS: Build repeated UI blocks
// ══════════════════════════════════════════════════════
function buildSectionHeaderForm(string $key, string $title, array $shdrs, string $icon, string $iconColor): string {
    $h = $shdrs[$key] ?? [];
    $p = fn($v) => htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
    return "<div class='section-card mb-4'><div class='sec-head'><span class='sec-title'><i class='fas $icon $iconColor'></i> $title</span></div>
    <form method='POST' class='p-4'><input type='hidden' name='save_section_header' value='1'><input type='hidden' name='sh_key' value='$key'>
    <div class='grid grid-cols-4 gap-3 items-end'>
      <div><label class='block text-xs font-semibold text-gray-500 mb-1'>Eyebrow</label><input type='text' name='sh_eyebrow' value='{$p($h['eyebrow']??'')}' class='form-field'></div>
      <div><label class='block text-xs font-semibold text-gray-500 mb-1'>Title</label><input type='text' name='sh_title' value='{$p($h['title']??'')}' class='form-field'></div>
      <div><label class='block text-xs font-semibold text-gray-500 mb-1'>Description</label><input type='text' name='sh_description' value='{$p($h['description']??'')}' class='form-field'></div>
      <div class='flex gap-2'><label class='relative inline-flex items-center cursor-pointer'><input type='checkbox' name='sh_active' value='1' ".($h['is_active']??1?'checked':'')." class='sr-only peer'><div class='w-9 h-5 bg-gray-200 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-4 after:w-4 after:transition-all peer-checked:bg-blue-600'></div></label>
      <button type='submit' class='btn-primary px-3 py-2 rounded-lg text-xs font-semibold flex items-center gap-1'><i class='fas fa-save text-xs'></i> Save</button></div>
    </div></form></div>";
}

function buildSimpleTable(array $cols, array $rows, string $editFn, string $deleteAction): string {
    if (empty($rows)) return "<div class='p-4 text-center text-gray-400 text-sm py-8'>No items yet</div>";
    $html = "<div class='overflow-x-auto'><table class='w-full text-xs'><thead class='bg-gray-50 text-gray-400 uppercase tracking-wide'><tr>";
    foreach ($cols as $c) {
        $label = is_array($c) ? $c[1] : ucfirst($c);
        $html .= "<th class='px-4 py-2.5 text-left'>$label</th>";
    }
    $html .= "<th class='px-4 py-2.5 text-center'>Status</th><th class='px-4 py-2.5 text-right'>Actions</th></tr></thead><tbody class='divide-y divide-gray-50'>";
    foreach ($rows as $row) {
        $html .= "<tr class='trow'>";
        foreach ($cols as $c) {
            $field = is_array($c) ? $c[0] : $c;
            $class = is_array($c) ? ($c[2]??'') : 'text-gray-700';
            $html .= "<td class='px-4 py-2.5 $class'>" . htmlspecialchars($row[$field]??'',ENT_QUOTES,'UTF-8') . "</td>";
        }
        $id = $row['id'];
        $active = $row['is_active'];
        $activeCls = $active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500';
        $dotCls = $active ? 'bg-green-500' : 'bg-gray-400';
        $label = $active ? 'Active' : 'Inactive';
        $html .= "<td class='px-4 py-2.5 text-center'><button onclick=\"toggleAjax('toggle_{$deleteAction}',$id,this)\" class='badge $activeCls cursor-pointer hover:opacity-80'><span class='w-1.5 h-1.5 rounded-full $dotCls'></span>$label</button></td>";
        $html .= "<td class='px-4 py-2.5 text-right'><div class='flex gap-1 justify-end'><button onclick=\"{$editFn}Edit($id)\" 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 transition'><i class='fas fa-edit'></i></button><button onclick=\"deleteAjax('delete_{$deleteAction}',$id,this,'tr')\" 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 transition'><i class='fas fa-trash'></i></button></div></td>";
        $html .= "</tr>";
    }
    $html .= "</tbody></table></div>";
    return $html;
}

function buildSimplePanel(...$args): string { return ''; } // placeholder - not used directly
?>

<!-- ════════════════ MODALS ════════════════ -->

<!-- TAB MODAL -->
<div id="tabModal" 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-sm">
    <div class="px-5 py-4 border-b flex items-center justify-between"><h3 class="font-bold text-gray-800" id="tabModalTitle"><i class="fas fa-folder text-purple-500 mr-2"></i>Add Tab</h3><button onclick="closeModal('tabModal')" class="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center"><i class="fas fa-times"></i></button></div>
    <form method="POST" class="p-5 space-y-3"><input type="hidden" name="save_tab" value="1"><input type="hidden" name="tab_id" id="tabId" value="0">
      <div><label class="block text-xs font-semibold text-gray-500 mb-1">Label *</label><input type="text" name="tab_label" id="tabLabel" oninput="autoKey()" class="form-field"></div>
      <div><label class="block text-xs font-semibold text-gray-500 mb-1">Key (auto)</label><input type="text" name="tab_key" id="tabKey" class="form-field font-mono"></div>
      <div><label class="block text-xs font-semibold text-gray-500 mb-1">Sort Order</label><input type="number" name="tab_sort" id="tabSort" value="0" min="0" class="form-field"></div>
      <div class="flex gap-2 justify-end border-t border-gray-100 pt-3"><button type="button" onclick="closeModal('tabModal')" class="border border-gray-300 text-gray-600 px-4 py-2 rounded-lg text-sm">Cancel</button><button type="submit" class="btn-primary px-5 py-2 rounded-lg text-sm font-semibold flex items-center gap-2"><i class="fas fa-save"></i> Save</button></div>
    </form>
    <form id="deleteTabForm" method="POST" class="hidden"><input type="hidden" name="delete_tab" value="1"><input type="hidden" name="tab_id" id="deleteTabId"></form>
  </div>
</div>

<!-- GALLERY CARD MODAL -->
<div id="cardModal" 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-lg max-h-[90vh] overflow-y-auto">
    <div class="px-5 py-4 border-b flex items-center justify-between sticky top-0 bg-white z-10"><h3 class="font-bold text-gray-800" id="cardModalTitle"><i class="fas fa-th-large text-indigo-500 mr-2"></i>Add Card</h3><button onclick="closeModal('cardModal')" class="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center"><i class="fas fa-times"></i></button></div>
    <form method="POST" enctype="multipart/form-data" class="p-5 space-y-3"><input type="hidden" name="save_card" value="1"><input type="hidden" name="card_id" id="cardId" value="0">
      <div class="grid grid-cols-2 gap-3"><div><label class="block text-xs font-semibold text-gray-500 mb-1">Tab *</label><select name="card_tab_id" id="cardTabId" class="form-field"><?php foreach($tabs as $t): ?><option value="<?=$t['id']?>"><?=p($t['tab_label'])?></option><?php endforeach; ?></select></div><div><label class="block text-xs font-semibold text-gray-500 mb-1">Sort</label><input type="number" name="card_sort" id="cardSort" value="0" class="form-field"></div></div>
      <div><label class="block text-xs font-semibold text-gray-500 mb-1">Title *</label><input type="text" name="card_title" id="cardTitle" class="form-field"></div>
      <div><label class="block text-xs font-semibold text-gray-500 mb-1">Description</label><textarea name="card_description" id="cardDescription" rows="2" class="form-field resize-none"></textarea></div>
      <div><label class="block text-xs font-semibold text-gray-500 mb-1">Image</label>
        <div class="flex gap-3 items-start">
          <div class="flex-1"><div class="upload-zone text-xs" id="cardImgZone" onclick="document.getElementById('cardImgFile').click()"><i class="fas fa-cloud-upload-alt text-xl text-blue-300 mb-1 block"></i><p class="text-gray-500">Upload image</p></div><input type="file" id="cardImgFile" name="card_image_file" accept="image/*" class="hidden" onchange="cardImgPreview(this)"><input type="text" name="card_image_url" id="cardImgUrl" placeholder="or paste URL" oninput="cardImgUrlPreview(this.value)" class="form-field font-mono text-xs mt-1"></div>
          <div id="cardImgPrev" class="w-16 h-16 rounded-lg 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-lg"></i></div>
        </div>
      </div>
      <div class="grid grid-cols-2 gap-3"><div><label class="block text-xs font-semibold text-gray-500 mb-1">Link URL</label><input type="text" name="card_link_url" id="cardLinkUrl" class="form-field font-mono text-xs"></div><div><label class="block text-xs font-semibold text-gray-500 mb-1">Link Text</label><input type="text" name="card_link_text" id="cardLinkText" placeholder="Get started →" class="form-field"></div></div>
      <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-2.5"><label class="relative inline-flex items-center cursor-pointer"><input type="checkbox" name="card_active" id="cardActive" value="1" checked class="sr-only peer"><div class="w-9 h-5 bg-gray-200 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-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div></label><span class="text-xs text-gray-600">Active</span></div>
      <div class="flex gap-2 justify-end border-t border-gray-100 pt-3"><button type="button" onclick="closeModal('cardModal')" class="border border-gray-300 text-gray-600 px-4 py-2 rounded-lg text-sm">Cancel</button><button type="submit" class="btn-primary px-5 py-2 rounded-lg text-sm font-semibold flex items-center gap-2"><i class="fas fa-save"></i> Save Card</button></div>
    </form>
  </div>
</div>

<!-- JOURNAL STAT MODAL -->
<?php echo buildSimpleModal('jstatModal','Journal Stat','fa-table text-amber-500','save_jstat','jstat_id',[['jstat_number','Number *','text','4×','required'],['jstat_label','Label *','text','Issues per year','required'],['jstat_sort','Sort','number','0','']]); ?>

<!-- SCOPE TAG MODAL -->
<?php echo buildSimpleModal('scopeModal','Scope Tag','fa-tags text-green-500','save_scope','scope_id',[['scope_label','Label *','text','Social Science','required'],['scope_url','Link URL','url','#',''],['scope_sort','Sort','number','0','']]); ?>

<!-- STEP MODAL -->
<?php echo buildSimpleModal('stepModal','Submission Step','fa-list-ol text-cyan-500','save_step','step_id',[['step_number','Step # *','text','1','required'],['step_title','Title *','text','Prepare manuscript','required'],['step_description','Description','textarea','Follow author guidelines...',''],['step_sort','Sort','number','0','']]); ?>

<!-- BOARD MEMBER MODAL -->
<?php echo buildSimpleModal('memberModal','Board Member','fa-user text-teal-500','save_member','member_id',[['member_name','Name *','text','Prof. John Smith','required'],['member_initials','Initials (auto)','text','JS',''],['member_role','Role *','text','Editor-in-Chief','required'],['member_institution','Institution','text','Univ. of Lagos',''],['member_sort','Sort','number','0','']]); ?>

<!-- INDEXING TAG MODAL -->
<?php echo buildSimpleModal('indexModal','Indexing Tag','fa-database text-purple-500','save_index','index_id',[['index_label','Label *','text','Google Scholar','required'],['index_badge','Badge (e.g. applied)','text','applied',''],['index_sort','Sort','number','0','']]); ?>

<!-- ETHICS CARD MODAL -->
<?php echo buildSimpleModal('ethicsModal','Ethics Card','fa-shield-alt text-pink-500','save_ethics','ethics_id',[['ethics_title','Title *','text','COPE guidelines','required'],['ethics_description','Description','textarea','Follows all COPE guidelines...',''],['ethics_sort','Sort','number','0','']]); ?>

<!-- WHY CARD MODAL -->
<?php echo buildSimpleModal('whyModal','Why Publish Card','fa-star text-yellow-500','save_why','why_id',[['why_title','Title *','text','Global reach','required'],['why_description','Description','textarea','Open access means...',''],['why_sort','Sort','number','0','']]); ?>

<!-- CONTACT CARD MODAL -->
<?php echo buildSimpleModal('contactModal','Contact Card','fa-envelope text-orange-500','save_contact','contact_id',[['contact_title','Title *','text','Submit a manuscript','required'],['contact_description','Description','textarea','Ready to publish?...',''],['contact_link_text','Link Text','text','Submit now',''],['contact_link_url','Link URL','url','https://...',''],['contact_sort','Sort','number','0','']]); ?>

<?php
function buildSimpleModal(string $id, string $title, string $icon, string $saveField, string $idField, array $fields): string {
    $html = "<div id='$id' 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-md max-h-[90vh] overflow-y-auto'>";
    $html .= "<div class='px-5 py-4 border-b flex items-center justify-between sticky top-0 bg-white z-10'><h3 class='font-bold text-gray-800'><i class='fas $icon mr-2'></i>$title</h3><button onclick=\"closeModal('$id')\" class='text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center'><i class='fas fa-times'></i></button></div>";
    $html .= "<form method='POST' class='p-5 space-y-3'><input type='hidden' name='$saveField' value='1'><input type='hidden' name='$idField' id='{$id}RecordId' value='0'>";
    foreach ($fields as [$name, $label, $type, $placeholder, $req]) {
        $html .= "<div><label class='block text-xs font-semibold text-gray-500 mb-1'>$label</label>";
        if ($type === 'textarea') $html .= "<textarea name='$name' id='{$id}_$name' rows='3' placeholder='$placeholder' class='form-field resize-none'></textarea>";
        else $html .= "<input type='$type' name='$name' id='{$id}_$name' placeholder='$placeholder' $req class='form-field" . ($type==='number'?'':(strpos($name,'url')!==false?' font-mono text-xs':'')) . "'>";
        $html .= "</div>";
    }
    $html .= "<div class='flex gap-2 justify-end border-t border-gray-100 pt-3'><button type='button' onclick=\"closeModal('$id')\" class='border border-gray-300 text-gray-600 px-4 py-2 rounded-lg text-sm'>Cancel</button><button type='submit' class='btn-primary px-5 py-2 rounded-lg text-sm font-semibold flex items-center gap-2'><i class='fas fa-save'></i> Save</button></div></form></div></div>";
    return $html;
}
?>

<script>
// ── Nav ────────────────────────────────────────────────
const PANELS=['hero','stats','aff','gallery','jstats','scope','submission','board','indexing','ethics','why','contact'];
function switchMain(name){
  PANELS.forEach(p=>{
    document.getElementById('panel-'+p)?.classList.toggle('active',p===name);
    document.getElementById('mnav-'+p)?.classList.toggle('active',p===name);
  });
}

// ── Modals ─────────────────────────────────────────────
function openModal(id){ document.getElementById(id).classList.remove('hidden'); }
function closeModal(id){ document.getElementById(id).classList.add('hidden'); }
function openSimpleModal(id){ openModal(id); }
document.querySelectorAll('[id$="Modal"]').forEach(m=>{
  m.addEventListener('click',e=>{ if(e.target===m) m.classList.add('hidden'); });
});

// ── Hero ───────────────────────────────────────────────
function handleBgUp(input){
  if(!input.files[0]) return;
  const r=new FileReader(); r.onload=e=>{
    document.getElementById('heroBgStrip').style.backgroundImage=`url(${e.target.result})`;
    const z=document.getElementById('heroBgZone'); z.classList.add('has-file');
    z.innerHTML=`<i class='fas fa-check-circle text-teal-500'></i> <span class='text-xs'>${input.files[0].name}</span>`;
    document.getElementById('heroBgUrl').value='';
  }; r.readAsDataURL(input.files[0]);
}
function updateHPTitle(){
  const l=document.querySelector('[name=title_line1]')?.value||'';
  const e1=document.querySelector('[name=title_em1]')?.value||'';
  document.getElementById('phTitle').textContent=l+' / '+e1;
}

// ── Tab ────────────────────────────────────────────────
let tabKeyEdited=false;
document.getElementById('tabKey').addEventListener('input',()=>tabKeyEdited=true);
function autoKey(){
  if(tabKeyEdited) return;
  document.getElementById('tabKey').value=document.getElementById('tabLabel').value.toLowerCase().replace(/[^a-z0-9]+/g,'_').replace(/_+/g,'_').replace(/^_|_$/g,'');
}
async function editTab(id){
  const d=await(await fetch(`?ajax=get_tab&id=${id}`)).json();
  tabKeyEdited=true;
  document.getElementById('tabModalTitle').innerHTML='<i class="fas fa-edit text-purple-500 mr-2"></i>Edit Tab';
  document.getElementById('tabId').value=d.id; document.getElementById('tabLabel').value=d.tab_label||''; document.getElementById('tabKey').value=d.tab_key||''; document.getElementById('tabSort').value=d.sort_order||0;
  openModal('tabModal');
}
function deleteTabConfirm(id,name){ if(!confirm(`Delete tab "${name}"?`)) return; document.getElementById('deleteTabId').value=id; document.getElementById('deleteTabForm').submit(); }

// ── Card ───────────────────────────────────────────────
async function editCard(id){
  const d=await(await fetch(`?ajax=get_card&id=${id}`)).json();
  document.getElementById('cardModalTitle').innerHTML='<i class="fas fa-edit text-indigo-500 mr-2"></i>Edit Card';
  document.getElementById('cardId').value=d.id; document.getElementById('cardTabId').value=d.tab_id||'';
  document.getElementById('cardTitle').value=d.title||''; document.getElementById('cardDescription').value=d.description||'';
  document.getElementById('cardImgUrl').value=d.image_url||''; document.getElementById('cardLinkUrl').value=d.link_url||'';
  document.getElementById('cardLinkText').value=d.link_text||''; document.getElementById('cardSort').value=d.sort_order||0;
  document.getElementById('cardActive').checked=d.is_active==1;
  if(d.image_url) cardImgUrlPreview(d.image_url);
  openModal('cardModal');
}
function cardImgPreview(input){ if(!input.files[0]) return; const r=new FileReader(); r.onload=e=>{ document.getElementById('cardImgPrev').innerHTML=`<img src="${e.target.result}" class="w-full h-full object-cover">`; }; r.readAsDataURL(input.files[0]); }
function cardImgUrlPreview(url){ const p=document.getElementById('cardImgPrev'); if(url.trim()) p.innerHTML=`<img src="${url.startsWith('http')?url:'/'+url.replace(/^\//,'')}" class="w-full h-full object-cover" onerror="this.parentElement.innerHTML='<i class=\\'fas fa-image text-lg\\'></i>'">`; else p.innerHTML='<i class="fas fa-image text-lg"></i>'; }

// ── Generic AJAX helpers ───────────────────────────────
async function toggleAjax(action,id,btn){
  await fetch(`?ajax=${action}&id=${id}`);
  const active=btn.textContent.trim()==='Active';
  btn.className=active?'badge bg-gray-100 text-gray-500 cursor-pointer hover:opacity-80':'badge bg-green-100 text-green-700 cursor-pointer hover:opacity-80';
  btn.innerHTML=active?'<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';
}
async function deleteAjax(action,id,btn,rowSelector){
  if(!confirm('Delete this item?')) return;
  await fetch(`?ajax=${action}&id=${id}`);
  const row=btn.closest(rowSelector); if(row) row.remove();
}

// ── Generic edit for simple modals ────────────────────
<?php
$simpleEditMap = [
    'jstat'   => ['jstatModal',   ['jstat_number'=>'number','jstat_label'=>'label','jstat_sort'=>'sort_order']],
    'scope'   => ['scopeModal',   ['scope_label'=>'label','scope_url'=>'link_url','scope_sort'=>'sort_order']],
    'step'    => ['stepModal',    ['step_number'=>'step_number','step_title'=>'title','step_description'=>'description','step_sort'=>'sort_order']],
    'member'  => ['memberModal',  ['member_name'=>'name','member_initials'=>'initials','member_role'=>'role','member_institution'=>'institution','member_sort'=>'sort_order']],
    'index'   => ['indexModal',   ['index_label'=>'label','index_badge'=>'badge','index_sort'=>'sort_order']],
    'ethics'  => ['ethicsModal',  ['ethics_title'=>'title','ethics_description'=>'description','ethics_sort'=>'sort_order']],
    'why'     => ['whyModal',     ['why_title'=>'title','why_description'=>'description','why_sort'=>'sort_order']],
    'contact' => ['contactModal', ['contact_title'=>'title','contact_description'=>'description','contact_link_text'=>'link_text','contact_link_url'=>'link_url','contact_sort'=>'sort_order']],
];
foreach ($simpleEditMap as $fn => [$modal, $fieldMap]): ?>
async function <?=$fn?>Edit(id){
  const d=await(await fetch(`?ajax=get_<?=$fn?>&id=${id}`)).json();
  document.getElementById('<?=$modal?>RecordId').value=d.id;
  <?php foreach ($fieldMap as $inputId => $dataKey): ?>document.getElementById('<?=$modal?>_<?=$inputId?>').value=d['<?=$dataKey?>']||'';
  <?php endforeach; ?>
  openModal('<?=$modal?>');
}
<?php endforeach; ?>

// ── Init from URL ──────────────────────────────────────
const urlP=new URLSearchParams(location.search);
if(urlP.get('panel')) switchMain(urlP.get('panel'));
</script>
</body>
</html>