<?php
/* ============================================================================
   WBMCZ — Admin · Hero Slider manager

   Everything the landing page hero shows is stored here and nowhere else:
   badge, title, subtitle, background photo, two buttons, order, on/off, and
   a Bengali / Hindi version of every piece of text.

   The public page reads these rows only — no translation file is involved —
   so whatever you type here is exactly what a visitor sees.
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/admin_list.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
if (!hasPermission('manage_settings')) { die("Access Denied: You do not have permission to manage website settings."); }

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

/* sidebar permission flags */
$can_users        = hasPermission('manage_users');
$can_sellers      = hasPermission('manage_sellers');
$can_staff        = hasPermission('manage_staff_roles');
$can_services     = hasPermission('manage_services');
$can_orders       = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets      = hasPermission('manage_tickets');
$can_settings     = hasPermission('manage_settings');

if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }
if (isset($_SESSION['flash_error']))   { $error_msg   = $_SESSION['flash_error'];   unset($_SESSION['flash_error']); }

/* ---------------------------------------------------------------------------
   Self healing schema — the page works even before tmomigration.php is run
   --------------------------------------------------------------------------- */
$__conn = $db->getConnection();
try {
    $__conn->query("CREATE TABLE IF NOT EXISTS hero_slides (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(200) NULL, subtitle TEXT NULL, image_path VARCHAR(255) NULL,
        button_text VARCHAR(60) NULL, button_link VARCHAR(255) NULL,
        slide_order INT NOT NULL DEFAULT 0, status TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (\Throwable $e) {}
$__hero_cols = [
    'panel' => "VARCHAR(20) NOT NULL DEFAULT 'landing'",
    'badge_text' => 'VARCHAR(160) NULL', 'badge_bn' => 'VARCHAR(160) NULL', 'badge_hi' => 'VARCHAR(160) NULL',
    'title_bn' => 'VARCHAR(200) NULL', 'title_hi' => 'VARCHAR(200) NULL',
    'subtitle_bn' => 'TEXT NULL', 'subtitle_hi' => 'TEXT NULL',
    'button_bn' => 'VARCHAR(60) NULL', 'button_hi' => 'VARCHAR(60) NULL',
    'button2_text' => 'VARCHAR(60) NULL', 'button2_link' => 'VARCHAR(255) NULL',
    'button2_bn' => 'VARCHAR(60) NULL', 'button2_hi' => 'VARCHAR(60) NULL',
    'text_align' => "VARCHAR(10) NOT NULL DEFAULT 'left'",
    'overlay' => 'TINYINT NOT NULL DEFAULT 70',
    'show_trust' => 'TINYINT(1) NOT NULL DEFAULT 1',
];
foreach ($__hero_cols as $__c => $__t) {
    try {
        $__r = $__conn->query("SHOW COLUMNS FROM hero_slides LIKE '$__c'");
        if ($__r && $__r->num_rows === 0) { $__conn->query("ALTER TABLE hero_slides ADD COLUMN `$__c` $__t"); }
    } catch (\Throwable $e) {}
}

/* ---------------------------------------------------------------------------
   Image upload — returns the stored path, or '' when nothing was uploaded
   --------------------------------------------------------------------------- */
function hero_upload_image($field = 'image_file') {
    if (empty($_FILES[$field]['name']) || !is_uploaded_file($_FILES[$field]['tmp_name'])) return '';
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true)) return '';
    $dir = __DIR__ . '/../uploads/hero/';
    if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
    $name = 'hero_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
    if (move_uploaded_file($_FILES[$field]['tmp_name'], $dir . $name)) { return 'uploads/hero/' . $name; }
    return '';
}

/* ---------------------------------------------------------------------------
   Which banner is being edited? The two sets never mix.
     landing    the big hero on the public home page  (index.php)
     dashboard  the banner a member sees after login  (dashboard.php)
   --------------------------------------------------------------------------- */
$HERO_PANELS = [
    'landing'   => ['Home Page Banner',  'fa-house',        'The big slider a visitor sees on the public home page.'],
    'dashboard' => ['After-Login Banner','fa-gauge-high',   'The banner a member sees on their dashboard once they log in.'],
];
$PANEL = $_GET['panel'] ?? ($_POST['panel'] ?? 'landing');
if (!isset($HERO_PANELS[$PANEL])) { $PANEL = 'landing'; }

/* every text field the form posts, in one place */
$HERO_TEXT = ['badge_text', 'badge_bn', 'badge_hi', 'title', 'title_bn', 'title_hi',
              'subtitle', 'subtitle_bn', 'subtitle_hi',
              'button_text', 'button_bn', 'button_hi', 'button_link',
              'button2_text', 'button2_bn', 'button2_hi', 'button2_link'];

/* ---------------------------------------------------------------------------
   ADD
   --------------------------------------------------------------------------- */
if (isset($_POST['add_slide'])) {
    $vals = [];
    foreach ($HERO_TEXT as $f) { $vals[$f] = sanitize($_POST[$f] ?? ''); }

    $img = hero_upload_image();
    if ($img === '') { $img = sanitize($_POST['image_url'] ?? ''); }

    if ($vals['title'] === '' && $vals['title_bn'] === '') {
        $_SESSION['flash_error'] = 'A slide needs at least an English or a Bengali title.';
        redirect('hero_slides.php');
    }

    $order   = (int)($_POST['slide_order'] ?? 0);
    $status  = ((int)($_POST['status'] ?? 1) === 1) ? 1 : 0;
    $align   = ($_POST['text_align'] ?? 'left') === 'center' ? 'center' : 'left';
    $overlay = max(0, min(100, (int)($_POST['overlay'] ?? 70)));
    $trust   = ((int)($_POST['show_trust'] ?? 1) === 1) ? 1 : 0;

    $db->insert(
        "INSERT INTO hero_slides
         (panel, badge_text, badge_bn, badge_hi, title, title_bn, title_hi, subtitle, subtitle_bn, subtitle_hi,
          button_text, button_bn, button_hi, button_link, button2_text, button2_bn, button2_hi, button2_link,
          image_path, slide_order, status, text_align, overlay, show_trust)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        [
            $PANEL,
            $vals['badge_text'], $vals['badge_bn'], $vals['badge_hi'],
            $vals['title'], $vals['title_bn'], $vals['title_hi'],
            $vals['subtitle'], $vals['subtitle_bn'], $vals['subtitle_hi'],
            $vals['button_text'], $vals['button_bn'], $vals['button_hi'], $vals['button_link'],
            $vals['button2_text'], $vals['button2_bn'], $vals['button2_hi'], $vals['button2_link'],
            $img, $order, $status, $align, $overlay, $trust,
        ]
    );
    $_SESSION['flash_success'] = 'Slide added to the ' . strtolower($HERO_PANELS[$PANEL][0]) . '.';
    redirect('hero_slides.php?panel=' . $PANEL);
}

/* ---------------------------------------------------------------------------
   EDIT
   --------------------------------------------------------------------------- */
if (isset($_POST['edit_slide'])) {
    $sid  = (int)($_POST['slide_id'] ?? 0);
    $old  = $db->select("SELECT * FROM hero_slides WHERE id = ?", [$sid]);
    if (empty($old)) { $_SESSION['flash_error'] = 'That slide no longer exists.'; redirect('hero_slides.php'); }
    $old = $old[0];

    $vals = [];
    foreach ($HERO_TEXT as $f) { $vals[$f] = sanitize($_POST[$f] ?? ''); }

    $img = hero_upload_image();
    if ($img === '') {
        $url = sanitize($_POST['image_url'] ?? '');
        $img = ($url !== '') ? $url : (string)$old['image_path'];
    }

    $order   = (int)($_POST['slide_order'] ?? 0);
    $status  = ((int)($_POST['status'] ?? 1) === 1) ? 1 : 0;
    $align   = ($_POST['text_align'] ?? 'left') === 'center' ? 'center' : 'left';
    $overlay = max(0, min(100, (int)($_POST['overlay'] ?? 70)));
    $trust   = ((int)($_POST['show_trust'] ?? 1) === 1) ? 1 : 0;

    $db->insert(
        "UPDATE hero_slides SET
            badge_text = ?, badge_bn = ?, badge_hi = ?,
            title = ?, title_bn = ?, title_hi = ?,
            subtitle = ?, subtitle_bn = ?, subtitle_hi = ?,
            button_text = ?, button_bn = ?, button_hi = ?, button_link = ?,
            button2_text = ?, button2_bn = ?, button2_hi = ?, button2_link = ?,
            image_path = ?, slide_order = ?, status = ?, text_align = ?, overlay = ?, show_trust = ?, panel = ?
         WHERE id = ?",
        [
            $vals['badge_text'], $vals['badge_bn'], $vals['badge_hi'],
            $vals['title'], $vals['title_bn'], $vals['title_hi'],
            $vals['subtitle'], $vals['subtitle_bn'], $vals['subtitle_hi'],
            $vals['button_text'], $vals['button_bn'], $vals['button_hi'], $vals['button_link'],
            $vals['button2_text'], $vals['button2_bn'], $vals['button2_hi'], $vals['button2_link'],
            $img, $order, $status, $align, $overlay, $trust, $PANEL, $sid,
        ]
    );
    $_SESSION['flash_success'] = 'Slide updated.';
    redirect('hero_slides.php?panel=' . $PANEL);
}

/* ---------------------------------------------------------------------------
   DELETE / TOGGLE / REORDER
   --------------------------------------------------------------------------- */
if (isset($_POST['delete_slide'])) {
    $sid = (int)$_POST['slide_id'];
    $db->insert("DELETE FROM hero_slides WHERE id = ?", [$sid]);
    $_SESSION['flash_success'] = 'Slide deleted.';
    redirect('hero_slides.php?panel=' . $PANEL);
}
if (isset($_POST['toggle_slide'])) {
    $sid = (int)$_POST['slide_id'];
    $db->insert("UPDATE hero_slides SET status = IF(status = 1, 0, 1) WHERE id = ?", [$sid]);
    $_SESSION['flash_success'] = 'Slide visibility changed.';
    redirect('hero_slides.php?panel=' . $PANEL);
}
if (isset($_POST['move_slide'])) {
    $sid = (int)$_POST['slide_id'];
    $dir = ($_POST['move_slide'] === 'up') ? -1 : 1;
    $cur = $db->select("SELECT slide_order FROM hero_slides WHERE id = ?", [$sid]);
    if (!empty($cur)) {
        $db->insert("UPDATE hero_slides SET slide_order = ? WHERE id = ?", [((int)$cur[0]['slide_order'] + $dir), $sid]);
    }
    redirect('hero_slides.php?panel=' . $PANEL);
}

/* ---------------------------------------------------------------------------
   Data for the page
   --------------------------------------------------------------------------- */
$slides = [];
try {
    $slides = $db->select("SELECT * FROM hero_slides
                           WHERE COALESCE(NULLIF(panel, ''), 'landing') = ?
                           ORDER BY slide_order ASC, id ASC", [$PANEL]);
} catch (\Throwable $e) {
    try { $slides = $db->select("SELECT * FROM hero_slides ORDER BY slide_order ASC, id ASC"); } catch (\Throwable $e2) {}
}

/* how many slides each tab holds, for the little counters */
$PANEL_COUNT = ['landing' => 0, 'dashboard' => 0];
try {
    foreach ($db->select("SELECT COALESCE(NULLIF(panel, ''), 'landing') p, COUNT(*) c FROM hero_slides GROUP BY p") as $__pc) {
        if (isset($PANEL_COUNT[$__pc['p']])) { $PANEL_COUNT[$__pc['p']] = (int)$__pc['c']; }
    }
} catch (\Throwable $e) {}

$live  = 0;
foreach ($slides as $s) { if ((int)$s['status'] === 1) $live++; }

$company_logo = getSetting('company_logo', '../assets/images/logo.png');
$next_order   = 0;
foreach ($slides as $s) { $next_order = max($next_order, (int)$s['slide_order']); }
$next_order  += 1;
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hero Slider - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Hind+Siliguri:wght@400;500;600;700&family=Noto+Sans+Devanagari:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter','Hind Siliguri','Noto Sans Devanagari',sans-serif; }
        .lbl { display:block; font-size:10px; font-weight:800; color:#64748b; margin-bottom:.25rem;
               text-transform:uppercase; letter-spacing:.05em; }
        .fld { width:100%; padding:.6rem .75rem; background:#fff; border:1.5px solid #cbd5e1;
               border-radius:.75rem; font-size:.82rem; outline:none; color:#0f172a; }
        .fld:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }
        .hs-card { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; overflow:hidden; }
        .hs-thumb { width:100%; height:132px; object-fit:cover; background:#0f172a; }
        .hs-pill { display:inline-flex; align-items:center; gap:.3rem; padding:.15rem .55rem; border-radius:999px;
                   font-size:9.5px; font-weight:900; text-transform:uppercase; letter-spacing:.05em; }
        .hs-live { background:#dcfce7; color:#15803d; }
        .hs-off  { background:#f1f5f9; color:#64748b; }
        .hs-btn  { display:inline-flex; align-items:center; justify-content:center; gap:.35rem; padding:.45rem .7rem;
                   border-radius:.6rem; font-size:11px; font-weight:800; border:0; cursor:pointer; color:#fff; }
        .hs-tab  { padding:.5rem .9rem; border-radius:.65rem; font-size:11.5px; font-weight:800; cursor:pointer;
                   color:#64748b; background:#f1f5f9; }
        .hs-tab.on { background:#4f46e5; color:#fff; }
        .hs-panel { display:inline-flex; align-items:center; gap:.55rem; padding:.7rem 1.1rem; border-radius:.9rem;
                    font-size:12.5px; font-weight:800; text-decoration:none; color:#64748b;
                    background:#fff; border:1px solid #e2e8f0; }
        .hs-panel:hover { border-color:#c7d2fe; color:#4338ca; }
        .hs-panel.on { background:#0f172a; color:#fff; border-color:#0f172a; }
        .hs-panel b { font-size:10px; padding:.1rem .45rem; border-radius:999px; background:rgba(100,116,139,.16); }
        .hs-panel.on b { background:rgba(255,255,255,.22); }
    </style>
</head>
<body class="bg-gray-50" x-data="heroApp()">
<div class="flex h-screen overflow-hidden">

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

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 shadow-sm border-b border-gray-200 z-40 relative">
            <div class="flex items-center">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg"><i class="fas fa-bars text-xl"></i></button>
                <h2 class="text-xl font-bold hidden md:block text-slate-800">Hero Slider</h2>
            </div>
            <div class="flex items-center gap-2">
                <a href="../index.php?home=1" target="_blank" class="hidden sm:inline-flex items-center gap-2 text-sm font-semibold text-slate-500 hover:text-emerald-600">
                    <i class="fas fa-external-link-alt"></i> View site
                </a>
                <button type="button" @click="openAdd()" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-blue-600 text-white text-sm font-bold shadow">
                    <i class="fas fa-plus"></i> Add Slide
                </button>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6">
            <?php echo alist_styles(); ?>

            <?php if (isset($success_msg)): ?>
            <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($success_msg); ?></span>
            </div>
            <?php endif; ?>
            <?php if (isset($error_msg)): ?>
            <div class="mb-5 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-triangle-exclamation mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($error_msg); ?></span>
            </div>
            <?php endif; ?>

            <div class="mb-4">
                <h2 class="text-2xl font-bold text-slate-800 mb-1">Banners</h2>
                <p class="text-gray-500 text-sm">
                    Two completely separate sliders. What you put on one tab never shows up on the other,
                    so you can change the home page banner without touching what your members see after they log in.
                </p>
            </div>

            <!-- which banner -->
            <div class="flex flex-wrap gap-2 mb-5">
                <?php foreach ($HERO_PANELS as $__pk => $__pv): ?>
                    <a href="hero_slides.php?panel=<?php echo $__pk; ?>"
                       class="hs-panel <?php echo $PANEL === $__pk ? 'on' : ''; ?>">
                        <i class="fas <?php echo $__pv[1]; ?>"></i>
                        <span><?php echo esc($__pv[0]); ?></span>
                        <b><?php echo (int)($PANEL_COUNT[$__pk] ?? 0); ?></b>
                    </a>
                <?php endforeach; ?>
            </div>

            <div class="mb-5 flex items-start gap-3 bg-indigo-50 border border-indigo-100 text-indigo-800 rounded-xl px-4 py-3 text-[12px]">
                <i class="fas <?php echo $HERO_PANELS[$PANEL][1]; ?> mt-0.5"></i>
                <span>
                    <b><?php echo esc($HERO_PANELS[$PANEL][0]); ?></b> &mdash; <?php echo esc($HERO_PANELS[$PANEL][2]); ?>
                    Slides play in the order below; switch one off to hide it without deleting.
                </span>
            </div>

            <?php echo alist_stats([
                ['label' => 'Total slides', 'value' => count($slides),           'icon' => 'fa-images',        'colour' => 'indigo'],
                ['label' => 'Live now',     'value' => $live,                    'icon' => 'fa-circle-check',  'colour' => 'emerald'],
                ['label' => 'Hidden',       'value' => count($slides) - $live,   'icon' => 'fa-eye-slash',     'colour' => 'slate'],
            ]); ?>

            <?php if (empty($slides)): ?>
                <div class="bg-white border border-dashed border-slate-300 rounded-2xl p-10 text-center">
                    <i class="fas fa-images text-4xl text-slate-300 mb-3"></i>
                    <p class="font-bold text-slate-700">No slides on this tab yet</p>
                    <p class="text-sm text-slate-500 mb-4">
                        Add the first one and it appears on the <?php echo esc(strtolower($HERO_PANELS[$PANEL][0])); ?> straight away.
                    </p>
                    <button type="button" @click="openAdd()" class="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-bold"><i class="fas fa-plus mr-1"></i>Add Slide</button>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                    <?php foreach ($slides as $i => $s):
                        $img = (string)$s['image_path'];
                        $src = ($img === '') ? '' : ((strpos($img, 'http') === 0) ? $img : '../' . ltrim($img, '/'));
                        $js  = json_encode($s, JSON_HEX_APOS | JSON_HEX_QUOT);
                    ?>
                    <div class="hs-card flex flex-col">
                        <div class="relative">
                            <?php if ($src !== ''): ?>
                                <img src="<?php echo htmlspecialchars($src); ?>" class="hs-thumb" alt="">
                            <?php else: ?>
                                <div class="hs-thumb flex items-center justify-center text-slate-500"><i class="fas fa-image text-2xl"></i></div>
                            <?php endif; ?>
                            <span class="absolute top-2 left-2 hs-pill <?php echo (int)$s['status'] === 1 ? 'hs-live' : 'hs-off'; ?>">
                                <?php echo (int)$s['status'] === 1 ? 'Live' : 'Hidden'; ?>
                            </span>
                            <span class="absolute top-2 right-2 hs-pill bg-slate-900/70 text-white">#<?php echo (int)$s['slide_order']; ?></span>
                        </div>

                        <div class="p-4 flex-1">
                            <?php if (!empty($s['badge_text'])): ?>
                                <p class="text-[10px] font-black uppercase tracking-widest text-amber-600 mb-1"><?php echo esc($s['badge_text']); ?></p>
                            <?php endif; ?>
                            <p class="font-extrabold text-slate-800 leading-snug"><?php echo esc($s['title'] ?: $s['title_bn']); ?></p>
                            <?php if (!empty($s['title_bn'])): ?>
                                <p class="text-[12px] text-slate-500 mt-0.5"><?php echo esc($s['title_bn']); ?></p>
                            <?php endif; ?>
                            <p class="text-[11.5px] text-slate-500 mt-2 line-clamp-2"><?php echo esc($s['subtitle']); ?></p>

                            <div class="flex flex-wrap gap-1.5 mt-3">
                                <?php if (!empty($s['button_text'])): ?>
                                    <span class="hs-pill bg-amber-100 text-amber-700"><i class="fas fa-hand-pointer"></i> <?php echo esc($s['button_text']); ?></span>
                                <?php endif; ?>
                                <?php if (!empty($s['button2_text'])): ?>
                                    <span class="hs-pill bg-slate-100 text-slate-600"><i class="fas fa-hand-pointer"></i> <?php echo esc($s['button2_text']); ?></span>
                                <?php endif; ?>
                                <?php if (!empty($s['show_trust'])): ?>
                                    <span class="hs-pill bg-emerald-50 text-emerald-600"><i class="fas fa-shield-halved"></i> Trust row</span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="px-4 pb-4 flex flex-wrap items-center gap-1.5">
                            <button type="button" @click='openEdit(<?php echo $js; ?>)' class="hs-btn bg-indigo-600 hover:bg-indigo-700"><i class="fas fa-pen"></i> Edit</button>

                            <form method="POST" class="inline">
                                <input type="hidden" name="slide_id" value="<?php echo (int)$s['id']; ?>"><input type="hidden" name="panel" value="<?php echo $PANEL; ?>">
                                <button type="submit" name="toggle_slide" value="1" class="hs-btn <?php echo (int)$s['status'] === 1 ? 'bg-slate-500 hover:bg-slate-600' : 'bg-emerald-600 hover:bg-emerald-700'; ?>">
                                    <i class="fas <?php echo (int)$s['status'] === 1 ? 'fa-eye-slash' : 'fa-eye'; ?>"></i>
                                    <?php echo (int)$s['status'] === 1 ? 'Hide' : 'Show'; ?>
                                </button>
                            </form>

                            <form method="POST" class="inline">
                                <input type="hidden" name="slide_id" value="<?php echo (int)$s['id']; ?>"><input type="hidden" name="panel" value="<?php echo $PANEL; ?>">
                                <button type="submit" name="move_slide" value="up" class="hs-btn bg-slate-400 hover:bg-slate-500" title="Move earlier"><i class="fas fa-arrow-up"></i></button>
                            </form>
                            <form method="POST" class="inline">
                                <input type="hidden" name="slide_id" value="<?php echo (int)$s['id']; ?>"><input type="hidden" name="panel" value="<?php echo $PANEL; ?>">
                                <button type="submit" name="move_slide" value="down" class="hs-btn bg-slate-400 hover:bg-slate-500" title="Move later"><i class="fas fa-arrow-down"></i></button>
                            </form>

                            <form method="POST" class="inline ml-auto" onsubmit="return confirm('Delete this slide permanently?')">
                                <input type="hidden" name="slide_id" value="<?php echo (int)$s['id']; ?>"><input type="hidden" name="panel" value="<?php echo $PANEL; ?>">
                                <button type="submit" name="delete_slide" value="1" class="hs-btn bg-rose-600 hover:bg-rose-700"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <div class="mt-6 text-[11.5px] text-slate-500 bg-white border border-slate-200 rounded-2xl p-4 leading-relaxed">
                <p class="font-bold text-slate-700 mb-1"><i class="fas fa-circle-info text-indigo-500 mr-1"></i>How the banner reads these fields</p>
                A visitor sees the text of the language they picked in the header. If the Bengali or Hindi box is left
                empty the English text is shown instead, so you can fill in only what you need.
                The recommended photo size is <b>1920 &times; 900</b> for the home page and <b>1400 &times; 420</b>
                for the after-login banner, and the darkness slider decides how much of the photo shows through
                behind the writing.
                <br><br>
                <b>The two tabs are completely independent.</b> Editing or deleting a slide on one tab never
                touches the other. To move a slide across, open it and change <b>Shows on</b>.
            </div>
        </main>
    </div>
</div>

<!-- ===================== ADD / EDIT MODAL ===================== -->
<template x-teleport="body">
<div x-show="modal" x-transition.opacity class="fixed inset-0 z-[100] flex items-center justify-center p-4" style="display:none;">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="modal = false"></div>

    <div class="relative w-full max-w-3xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[93vh] flex flex-col">
        <div class="bg-gradient-to-r from-indigo-600 to-blue-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <h3 class="text-white font-bold text-lg">
                <i class="fas fa-images mr-2"></i><span x-text="mode === 'add' ? 'Add Slide' : 'Edit Slide'"></span>
            </h3>
            <button @click="modal = false" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>

        <form method="POST" enctype="multipart/form-data" class="flex flex-col overflow-hidden">
            <input type="hidden" name="slide_id" :value="s.id">

            <div class="p-5 overflow-y-auto space-y-5">

                <!-- language tabs -->
                <div class="flex flex-wrap gap-2">
                    <span class="hs-tab" :class="tab==='en' && 'on'" @click="tab='en'">English</span>
                    <span class="hs-tab" :class="tab==='bn' && 'on'" @click="tab='bn'">বাংলা</span>
                    <span class="hs-tab" :class="tab==='hi' && 'on'" @click="tab='hi'">हिन्दी</span>
                    <span class="text-[11px] text-slate-400 self-center ml-1">Empty Bengali / Hindi boxes fall back to English.</span>
                </div>

                <!-- ENGLISH -->
                <div x-show="tab==='en'" class="space-y-3">
                    <div><label class="lbl">Badge (small gold pill)</label>
                        <input name="badge_text" x-model="s.badge_text" class="fld" placeholder="Trusted Digital Service Network"></div>
                    <div><label class="lbl">Title</label>
                        <input name="title" x-model="s.title" class="fld" placeholder="The trusted address for digital services"></div>
                    <div><label class="lbl">Subtitle</label>
                        <textarea name="subtitle" x-model="s.subtitle" rows="2" class="fld" placeholder="All your digital services on one platform"></textarea></div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div><label class="lbl">Button 1 label</label><input name="button_text" x-model="s.button_text" class="fld" placeholder="Get Started Free"></div>
                        <div><label class="lbl">Button 1 link</label><input name="button_link" x-model="s.button_link" class="fld" placeholder="register.php"></div>
                        <div><label class="lbl">Button 2 label <span class="text-slate-400 normal-case font-medium">(optional)</span></label><input name="button2_text" x-model="s.button2_text" class="fld" placeholder="Learn More"></div>
                        <div><label class="lbl">Button 2 link</label><input name="button2_link" x-model="s.button2_link" class="fld" placeholder="#about"></div>
                    </div>
                </div>

                <!-- BENGALI -->
                <div x-show="tab==='bn'" style="display:none" class="space-y-3">
                    <div><label class="lbl">ব্যাজ</label><input name="badge_bn" x-model="s.badge_bn" class="fld" placeholder="বিশ্বস্ত ডিজিটাল সার্ভিস নেটওয়ার্ক"></div>
                    <div><label class="lbl">শিরোনাম</label><input name="title_bn" x-model="s.title_bn" class="fld" placeholder="ডিজিটাল সার্ভিসের বিশ্বস্ত ঠিকানা"></div>
                    <div><label class="lbl">উপ-শিরোনাম</label><textarea name="subtitle_bn" x-model="s.subtitle_bn" rows="2" class="fld"></textarea></div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div><label class="lbl">বোতাম ১</label><input name="button_bn" x-model="s.button_bn" class="fld" placeholder="বিনামূল্যে শুরু করুন"></div>
                        <div><label class="lbl">বোতাম ২</label><input name="button2_bn" x-model="s.button2_bn" class="fld" placeholder="আরও জানুন"></div>
                    </div>
                    <p class="text-[11px] text-slate-400">লিংক দুটো সব ভাষার জন্য একই — English ট্যাব থেকে সেট করুন।</p>
                </div>

                <!-- HINDI -->
                <div x-show="tab==='hi'" style="display:none" class="space-y-3">
                    <div><label class="lbl">बैज</label><input name="badge_hi" x-model="s.badge_hi" class="fld"></div>
                    <div><label class="lbl">शीर्षक</label><input name="title_hi" x-model="s.title_hi" class="fld"></div>
                    <div><label class="lbl">उपशीर्षक</label><textarea name="subtitle_hi" x-model="s.subtitle_hi" rows="2" class="fld"></textarea></div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div><label class="lbl">बटन 1</label><input name="button_hi" x-model="s.button_hi" class="fld"></div>
                        <div><label class="lbl">बटन 2</label><input name="button2_hi" x-model="s.button2_hi" class="fld"></div>
                    </div>
                </div>

                <!-- PHOTO -->
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-amber-600 mb-2 border-b pb-1"><i class="fas fa-image mr-1"></i>Background photo</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label class="lbl">Upload (jpg / png / webp)</label>
                            <input type="file" name="image_file" accept="image/*" class="fld !py-2">
                        </div>
                        <div>
                            <label class="lbl">…or paste an image URL / path</label>
                            <input name="image_url" x-model="s.image_path" class="fld" placeholder="uploads/hero/banner.jpg">
                        </div>
                    </div>
                    <template x-if="s.image_path">
                        <img :src="(s.image_path || '').startsWith('http') ? s.image_path : '../' + (s.image_path || '')"
                             class="mt-3 w-full h-32 object-cover rounded-xl border border-slate-200" alt="">
                    </template>
                </div>

                <!-- LAYOUT -->
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-emerald-600 mb-2 border-b pb-1"><i class="fas fa-sliders mr-1"></i>Layout</p>
                    <div class="mb-3">
                        <label class="lbl">Shows on</label>
                        <select name="panel" x-model="s.panel" class="fld">
                            <?php foreach ($HERO_PANELS as $__pk => $__pv): ?>
                                <option value="<?php echo $__pk; ?>"><?php echo esc($__pv[0]); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <p class="text-[10px] text-slate-400 mt-1">Change this to move the slide to the other banner.</p>
                    </div>

                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div><label class="lbl">Text position</label>
                            <select name="text_align" x-model="s.text_align" class="fld">
                                <option value="left">Left</option><option value="center">Centre</option>
                            </select>
                        </div>
                        <div><label class="lbl">Order</label><input type="number" name="slide_order" x-model="s.slide_order" class="fld"></div>
                        <div><label class="lbl">Status</label>
                            <select name="status" x-model="s.status" class="fld">
                                <option value="1">Live</option><option value="0">Hidden</option>
                            </select>
                        </div>
                        <div><label class="lbl">Trust row</label>
                            <select name="show_trust" x-model="s.show_trust" class="fld">
                                <option value="1">Show</option><option value="0">Hide</option>
                            </select>
                        </div>
                        <div class="col-span-2 md:col-span-4">
                            <label class="lbl">Photo darkness — <span x-text="s.overlay"></span>%</label>
                            <input type="range" name="overlay" min="0" max="100" step="5" x-model="s.overlay" class="w-full">
                            <p class="text-[10px] text-slate-400">Higher = darker photo, easier to read the writing.</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="flex justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                <button type="button" @click="modal = false" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" :name="mode === 'add' ? 'add_slide' : 'edit_slide'" value="1"
                        class="px-5 py-2 text-sm font-bold text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg shadow">
                    <i class="fas fa-save mr-1"></i><span x-text="mode === 'add' ? 'Add Slide' : 'Save Changes'"></span>
                </button>
            </div>
        </form>
    </div>
</div>
</template>

<script>
function heroApp() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        modal: false, mode: 'add', tab: 'en',
        s: {},
        blank() {
            return { id: '', badge_text: '', badge_bn: '', badge_hi: '', title: '', title_bn: '', title_hi: '',
                     subtitle: '', subtitle_bn: '', subtitle_hi: '',
                     button_text: 'Get Started Free', button_bn: '', button_hi: '', button_link: 'register.php',
                     button2_text: '', button2_bn: '', button2_hi: '', button2_link: '',
                     image_path: '', slide_order: <?php echo (int)$next_order; ?>, status: '1',
                     text_align: 'left', overlay: 70, show_trust: '1',
                     panel: '<?php echo $PANEL; ?>' };
        },
        openAdd()  { this.s = this.blank(); this.mode = 'add';  this.tab = 'en'; this.modal = true; },
        openEdit(row) {
            const b = this.blank();
            Object.keys(b).forEach(k => { b[k] = (row[k] === null || row[k] === undefined) ? '' : String(row[k]); });
            b.overlay = Number(row.overlay ?? 70);
            this.s = b; this.mode = 'edit'; this.tab = 'en'; this.modal = true;
        }
    }
}
</script>
</body>
</html>
