<?php
ob_start();
include 'config.php';
checkLogin();
if (!has_access($conn, 'perm_manage_inventory')) {
    header("Location: index.php?status=restricted");
    exit;
}

// ==========================================
// 1. LOGIKA PROSES
// ==========================================

// --- PROSES PAKET ---
if(isset($_POST['add_package'])) {
    $nama = mysqli_real_escape_string($conn, $_POST['nama_paket']);
    $durasi = (int)$_POST['durasi_menit'];
    $harga = (int)$_POST['harga'];
    mysqli_query($conn, "INSERT INTO packages (nama_paket, durasi_menit, harga) VALUES ('$nama', '$durasi', '$harga')");
    header("Location: inventory.php");
    exit;
}

if(isset($_POST['update_paket'])) {
    $id = $_POST['id'];
    $durasi = (int)$_POST['durasi_menit'];
    $harga = (int)$_POST['harga'];
    $nama = mysqli_real_escape_string($conn, $_POST['nama_paket'] ?? '');
    if (!empty($nama)) {
        mysqli_query($conn, "UPDATE packages SET nama_paket='$nama', durasi_menit='$durasi', harga='$harga' WHERE id='$id'");
    } else {
        mysqli_query($conn, "UPDATE packages SET durasi_menit='$durasi', harga='$harga' WHERE id='$id'");
    }
    header("Location: inventory.php");
    exit;
}

if(isset($_GET['delete_package'])) {
    $id = (int)$_GET['delete_package'];
    mysqli_query($conn, "DELETE FROM packages WHERE id='$id'");
    header("Location: inventory.php");
    exit;
}

// --- PROSES SNACK ---
if(isset($_POST['add_snack'])) {
    $nama = mysqli_real_escape_string($conn, $_POST['nama']);
    $beli = (int)$_POST['beli'];
    $jual = (int)$_POST['jual'];
    $stok = (int)$_POST['stok'];
    mysqli_query($conn, "INSERT INTO snacks (nama_barang, harga_beli, harga_jual, stok) VALUES ('$nama', '$beli', '$jual', '$stok')");
    header("Location: inventory.php");
    exit;
}

if(isset($_POST['update_snack'])) {
    $id = $_POST['id'];
    $nama = mysqli_real_escape_string($conn, $_POST['nama']);
    $beli = (int)$_POST['beli'];
    $jual = (int)$_POST['jual'];
    $stok = (int)$_POST['stok'];
    mysqli_query($conn, "UPDATE snacks SET nama_barang='$nama', harga_beli='$beli', harga_jual='$jual', stok='$stok' WHERE id='$id'");
    header("Location: inventory.php");
    exit;
}

if(isset($_GET['delete_snack'])) {
    $id = (int)$_GET['delete_snack'];
    mysqli_query($conn, "DELETE FROM snacks WHERE id='$id'");
    header("Location: inventory.php");
    exit;
}

// ==========================================
// 2. DATA
// ==========================================
$pkgs = mysqli_query($conn, "SELECT * FROM packages ORDER BY durasi_menit ASC");
$snacks = mysqli_query($conn, "SELECT * FROM snacks ORDER BY nama_barang ASC");
$total_snacks = 0; $low_stock = 0; $total_stok_val = 0;
$snack_list = [];
while($s = mysqli_fetch_assoc($snacks)) {
    $snack_list[] = $s;
    $total_snacks++;
    if ((int)$s['stok'] < 5) $low_stock++;
    $total_stok_val += (int)$s['stok'] * (int)$s['harga_beli'];
}
$pkg_list = [];
while($p = mysqli_fetch_assoc($pkgs)) { $pkg_list[] = $p; }

$page_title = "Inventory & Pricing";
$active_page = "inventory";
include 'layout.php';
?>

<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>

<style>
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Chakra+Petch:wght@600;700&family=JetBrains+Mono:wght@500;600;700&display=swap');

:root {
    --bg-dark: #0a0f1e;
    --bg-card: rgba(22, 33, 62, 0.6);
    --bg-card-solid: #16213e;
    --bg-input: rgba(10, 15, 30, 0.8);
    --primary: #06b6d4;
    --primary-glow: rgba(6, 182, 212, 0.25);
    --primary-soft: rgba(6, 182, 212, 0.08);
    --accent-green: #10b981;
    --accent-yellow: #f59e0b;
    --accent-red: #ef4444;
    --accent-purple: #a78bfa;
    --text-primary: #f1f5f9;
    --text-secondary: #94a3b8;
    --text-muted: #64748b;
    --border: rgba(255, 255, 255, 0.06);
    --border-hover: rgba(6, 182, 212, 0.3);
    --radius: 18px;
    --radius-sm: 12px;
    --shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

* { box-sizing: border-box; }
input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
input[type=number] { -moz-appearance: textfield; }

/* ─── PAGE HEADER ─── */
.page-hero {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 28px;
    flex-wrap: wrap;
    gap: 16px;
}
.page-hero-left { display: flex; align-items: center; gap: 16px; }
.page-hero-icon {
    width: 52px; height: 52px;
    background: linear-gradient(135deg, var(--primary), #0891b2);
    border-radius: 16px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.5rem; color: #fff;
    box-shadow: 0 4px 20px var(--primary-glow);
}
.page-hero h2 {
    font-family: 'Chakra Petch', sans-serif;
    font-size: 1.6rem; color: #fff; margin: 0;
    letter-spacing: 0.5px;
}
.page-hero p { margin: 2px 0 0; font-size: 0.82rem; color: var(--text-secondary); }

/* ─── STAT PILLS ─── */
.stat-row { display: flex; gap: 12px; flex-wrap: wrap; }
.stat-pill {
    display: flex; align-items: center; gap: 8px;
    background: var(--bg-card);
    backdrop-filter: blur(12px);
    border: 1px solid var(--border);
    padding: 8px 16px;
    border-radius: 30px;
    font-size: 0.78rem;
    color: var(--text-secondary);
    white-space: nowrap;
}
.stat-pill .val { color: var(--text-primary); font-weight: 700; font-family: 'JetBrains Mono', monospace; }
.stat-pill i { font-size: 1rem; }
.stat-pill.warn { border-color: rgba(239, 68, 68, 0.2); }
.stat-pill.warn i { color: var(--accent-red); }

/* ─── TAB SWITCH ─── */
.tab-bar {
    display: flex; gap: 6px;
    background: rgba(15, 23, 42, 0.5);
    border: 1px solid var(--border);
    padding: 5px;
    border-radius: 14px;
    margin-bottom: 24px;
    width: fit-content;
}
.tab-btn {
    padding: 10px 22px;
    border-radius: 10px;
    border: none;
    background: transparent;
    color: var(--text-muted);
    font-size: 0.85rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.25s ease;
    display: flex; align-items: center; gap: 8px;
    font-family: 'Plus Jakarta Sans', sans-serif;
}
.tab-btn:hover { color: var(--text-primary); background: rgba(255,255,255,0.03); }
.tab-btn.active {
    background: var(--primary);
    color: #000;
    box-shadow: 0 4px 15px var(--primary-glow);
}
.tab-btn .count {
    font-size: 0.7rem;
    background: rgba(255,255,255,0.15);
    padding: 2px 7px;
    border-radius: 10px;
    font-weight: 700;
}
.tab-btn.active .count { background: rgba(0,0,0,0.2); color: #000; }

.tab-panel { display: none; animation: fadeUp 0.35s ease; }
.tab-panel.active { display: block; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }

/* ─── SECTION CARD ─── */
.section-card {
    background: var(--bg-card);
    backdrop-filter: blur(16px);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    overflow: hidden;
    box-shadow: var(--shadow);
    transition: border-color 0.3s;
}
.section-card:hover { border-color: var(--border-hover); }

.section-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 20px 24px;
    border-bottom: 1px solid var(--border);
    flex-wrap: wrap;
    gap: 12px;
}
.section-header-left { display: flex; align-items: center; gap: 10px; }
.section-header-left i { font-size: 1.2rem; color: var(--primary); }
.section-header-left h3 { margin: 0; font-size: 1rem; color: #fff; font-weight: 700; }

/* ─── ADD FORM ─── */
.add-form-bar {
    display: flex; gap: 10px; align-items: center;
    padding: 16px 24px;
    background: rgba(0,0,0,0.15);
    border-bottom: 1px solid var(--border);
    flex-wrap: wrap;
}
.fi {
    background: var(--bg-input);
    border: 1px solid var(--border);
    color: #fff;
    padding: 10px 14px;
    border-radius: var(--radius-sm);
    font-size: 0.85rem;
    outline: none;
    transition: all 0.25s;
    font-family: 'Plus Jakarta Sans', sans-serif;
    min-width: 0;
}
.fi:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-soft); }
.fi::placeholder { color: var(--text-muted); }
.fi-grow { flex: 1; min-width: 120px; }
.fi-sm { width: 90px; }
.fi-xs { width: 70px; }

.btn-add {
    display: flex; align-items: center; justify-content: center; gap: 6px;
    background: linear-gradient(135deg, var(--primary), #0891b2);
    color: #000; border: none;
    padding: 10px 18px;
    border-radius: var(--radius-sm);
    font-size: 0.85rem; font-weight: 700;
    cursor: pointer;
    transition: all 0.25s;
    white-space: nowrap;
    font-family: 'Plus Jakarta Sans', sans-serif;
}
.btn-add:hover { transform: translateY(-1px); box-shadow: 0 6px 20px var(--primary-glow); filter: brightness(1.1); }

/* ─── SEARCH ─── */
.search-box {
    position: relative;
    width: 220px;
}
.search-box i {
    position: absolute; left: 12px; top: 50%; transform: translateY(-50%);
    color: var(--text-muted); font-size: 1rem;
}
.search-box input {
    width: 100%;
    background: var(--bg-input);
    border: 1px solid var(--border);
    color: #fff;
    padding: 9px 14px 9px 36px;
    border-radius: var(--radius-sm);
    font-size: 0.82rem;
    outline: none;
    transition: all 0.25s;
    font-family: 'Plus Jakarta Sans', sans-serif;
}
.search-box input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-soft); }

/* ─── PAKET CARDS GRID ─── */
.pkg-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 14px;
    padding: 20px 24px;
}
.pkg-card {
    background: rgba(10, 15, 30, 0.5);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 20px;
    position: relative;
    transition: all 0.3s ease;
    display: flex; flex-direction: column; gap: 12px;
}
.pkg-card:hover { border-color: var(--border-hover); transform: translateY(-3px); box-shadow: 0 12px 30px rgba(0,0,0,0.3); }
.pkg-duration {
    font-family: 'JetBrains Mono', monospace;
    font-size: 2rem; font-weight: 700; color: var(--primary);
    line-height: 1;
}
.pkg-duration small { font-size: 0.65rem; color: var(--text-muted); font-weight: 500; letter-spacing: 1px; }
.pkg-name { font-size: 0.9rem; font-weight: 700; color: var(--text-primary); }
.pkg-price {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.95rem; font-weight: 600; color: var(--accent-green);
    display: flex; align-items: center; gap: 4px;
}
.pkg-price span { font-size: 0.7rem; color: var(--text-muted); font-weight: 500; }
.pkg-actions {
    display: flex; gap: 6px;
    position: absolute; top: 12px; right: 12px;
    opacity: 0; transition: opacity 0.25s;
}
.pkg-card:hover .pkg-actions { opacity: 1; }
.pkg-act-btn {
    width: 30px; height: 30px;
    border-radius: 8px; border: 1px solid var(--border);
    background: var(--bg-card-solid);
    color: var(--text-muted);
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 0.9rem;
    transition: all 0.2s;
}
.pkg-act-btn:hover { border-color: var(--primary); color: var(--primary); }
.pkg-act-btn.del:hover { border-color: var(--accent-red); color: var(--accent-red); }

/* ─── SNACK TABLE ─── */
.inv-table { width: 100%; border-collapse: collapse; }
.inv-table thead th {
    text-align: left; padding: 14px 24px;
    color: var(--text-muted); font-size: 0.7rem;
    text-transform: uppercase; letter-spacing: 1.5px; font-weight: 700;
    border-bottom: 1px solid var(--border);
    background: rgba(0,0,0,0.1);
}
.inv-table tbody tr {
    transition: background 0.2s;
    border-bottom: 1px solid rgba(255,255,255,0.02);
}
.inv-table tbody tr:hover { background: rgba(6, 182, 212, 0.03); }
.inv-table tbody td { padding: 14px 24px; color: var(--text-primary); font-size: 0.88rem; vertical-align: middle; }

.item-info { display: flex; align-items: center; gap: 12px; }
.item-avatar {
    width: 40px; height: 40px;
    border-radius: 12px;
    background: linear-gradient(135deg, rgba(6,182,212,0.1), rgba(167,139,250,0.1));
    display: flex; align-items: center; justify-content: center;
    font-size: 1.1rem; flex-shrink: 0;
}
.item-name { font-weight: 700; color: #fff; font-size: 0.88rem; }
.item-modal { font-size: 0.75rem; color: var(--text-muted); margin-top: 2px; }

.stock-badge {
    display: inline-flex; align-items: center; gap: 5px;
    padding: 5px 12px; border-radius: 20px;
    font-size: 0.78rem; font-weight: 700;
    font-family: 'JetBrains Mono', monospace;
}
.stock-ok { background: rgba(16, 185, 129, 0.1); color: var(--accent-green); }
.stock-warn { background: rgba(245, 158, 11, 0.1); color: var(--accent-yellow); }
.stock-danger { background: rgba(239, 68, 68, 0.12); color: var(--accent-red); }
.stock-dot { width: 6px; height: 6px; border-radius: 50%; }
.stock-ok .stock-dot { background: var(--accent-green); }
.stock-warn .stock-dot { background: var(--accent-yellow); }
.stock-danger .stock-dot { background: var(--accent-red); }

.price-col {
    font-family: 'JetBrains Mono', monospace;
    font-weight: 700; color: var(--primary);
}
.profit-tag {
    font-size: 0.68rem; color: var(--accent-green);
    background: rgba(16, 185, 129, 0.08);
    padding: 2px 6px; border-radius: 6px;
    margin-left: 6px; font-weight: 600;
}

.row-actions { display: flex; gap: 6px; justify-content: flex-end; }
.row-act {
    width: 34px; height: 34px; border-radius: 10px;
    border: 1px solid var(--border);
    background: transparent;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 1rem; color: var(--text-muted);
    transition: all 0.2s;
    text-decoration: none;
}
.row-act:hover { border-color: var(--primary); color: var(--primary); background: var(--primary-soft); }
.row-act.del:hover { border-color: var(--accent-red); color: var(--accent-red); background: rgba(239,68,68,0.06); }

.empty-state {
    text-align: center; padding: 50px 20px; color: var(--text-muted);
}
.empty-state i { font-size: 3rem; margin-bottom: 12px; display: block; opacity: 0.3; }

/* ─── MODAL ─── */
.modal-bg {
    position: fixed; top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0,0,0,0.75); backdrop-filter: blur(8px);
    display: none; align-items: center; justify-content: center;
    z-index: 1000;
    animation: modalFadeIn 0.25s ease;
}
@keyframes modalFadeIn { from { opacity: 0; } to { opacity: 1; } }
.modal-box {
    background: var(--bg-card-solid);
    border: 1px solid var(--border);
    padding: 28px;
    border-radius: 22px;
    width: 92%; max-width: 420px;
    box-shadow: 0 24px 48px rgba(0,0,0,0.5);
    animation: modalSlide 0.3s ease;
}
@keyframes modalSlide { from { opacity: 0; transform: translateY(20px) scale(0.97); } to { opacity: 1; transform: translateY(0) scale(1); } }
.modal-title {
    font-family: 'Chakra Petch', sans-serif;
    font-size: 1.1rem; color: #fff; margin: 0 0 20px; display: flex; align-items: center; gap: 10px;
}
.modal-title i { color: var(--primary); }
.modal-label { font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; font-weight: 700; margin-bottom: 6px; display: block; }
.modal-row { margin-bottom: 16px; }
.modal-row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-bottom: 16px; }
.modal-fi {
    width: 100%;
    background: var(--bg-input); border: 1px solid var(--border);
    color: #fff; padding: 11px 14px; border-radius: var(--radius-sm);
    font-size: 0.88rem; outline: none;
    transition: all 0.25s;
    font-family: 'Plus Jakarta Sans', sans-serif;
}
.modal-fi:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-soft); }
.modal-footer { display: flex; justify-content: flex-end; gap: 10px; margin-top: 24px; }
.btn-cancel {
    padding: 10px 20px; border-radius: var(--radius-sm); border: 1px solid var(--border);
    background: transparent; color: var(--text-secondary); font-size: 0.85rem;
    cursor: pointer; transition: 0.2s; font-family: 'Plus Jakarta Sans', sans-serif;
}
.btn-cancel:hover { border-color: var(--text-muted); color: #fff; }
.btn-modal-save {
    padding: 10px 24px; border-radius: var(--radius-sm); border: none;
    background: linear-gradient(135deg, var(--primary), #0891b2); color: #000;
    font-size: 0.85rem; font-weight: 700; cursor: pointer; transition: 0.2s;
    font-family: 'Plus Jakarta Sans', sans-serif;
}
.btn-modal-save:hover { filter: brightness(1.1); box-shadow: 0 6px 20px var(--primary-glow); }

@media (max-width: 600px) {
    .page-hero { flex-direction: column; align-items: flex-start; }
    .stat-row { flex-direction: column; }
    .add-form-bar { flex-direction: column; }
    .fi-sm, .fi-xs { width: 100%; }
    .search-box { width: 100%; }
    .pkg-grid { grid-template-columns: 1fr 1fr; }
    .inv-table thead { display: none; }
    .inv-table tbody tr { display: flex; flex-wrap: wrap; padding: 14px 20px; gap: 8px; border-bottom: 1px solid var(--border); }
    .inv-table tbody td { padding: 4px 0; }
}
</style>

<!-- ═══════════════════════════════════════════════════ -->
<!-- PAGE HEADER + STATS                                -->
<!-- ═══════════════════════════════════════════════════ -->
<div class="page-hero">
    <div class="page-hero-left">
        <div class="page-hero-icon"><i class='bx bxs-package'></i></div>
        <div>
            <h2>Inventory & Harga</h2>
            <p>Kelola paket billing dan stok barang</p>
        </div>
    </div>
    <div class="stat-row">
        <div class="stat-pill"><i class='bx bxs-box' style="color:var(--primary)"></i> Produk <span class="val"><?= $total_snacks ?></span></div>
        <div class="stat-pill <?= $low_stock > 0 ? 'warn' : '' ?>"><i class='bx bxs-error-circle'></i> Stok Rendah <span class="val"><?= $low_stock ?></span></div>
        <div class="stat-pill"><i class='bx bxs-wallet' style="color:var(--accent-green)"></i> Nilai Modal <span class="val">Rp <?= number_format($total_stok_val) ?></span></div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════ -->
<!-- TAB SWITCH                                          -->
<!-- ═══════════════════════════════════════════════════ -->
<div class="tab-bar">
    <button class="tab-btn active" onclick="switchTab('paket', this)">
        <i class='bx bxs-time-five'></i> Paket Billing
        <span class="count"><?= count($pkg_list) ?></span>
    </button>
    <button class="tab-btn" onclick="switchTab('snack', this)">
        <i class='bx bxs-store'></i> Snacks & Drinks
        <span class="count"><?= $total_snacks ?></span>
    </button>
</div>

<!-- ═══════════════════════════════════════════════════ -->
<!-- TAB 1: PAKET BILLING                                -->
<!-- ═══════════════════════════════════════════════════ -->
<div id="tab-paket" class="tab-panel active">
    <div class="section-card">
        <form method="POST" class="add-form-bar">
            <input type="text" name="nama_paket" class="fi fi-grow" placeholder="Nama paket baru..." required>
            <input type="number" name="durasi_menit" class="fi fi-sm" placeholder="Menit" required>
            <input type="number" name="harga" class="fi" style="width:130px;" placeholder="Harga (Rp)" required>
            <button type="submit" name="add_package" class="btn-add"><i class='bx bx-plus'></i> Tambah</button>
        </form>

        <div class="pkg-grid">
            <?php if (empty($pkg_list)): ?>
                <div class="empty-state" style="grid-column:1/-1;"><i class='bx bxs-time-five'></i><p>Belum ada paket</p></div>
            <?php else: foreach ($pkg_list as $p): ?>
            <div class="pkg-card">
                <div class="pkg-actions">
                    <button type="button" class="pkg-act-btn" onclick="openEditPkg(<?= $p['id'] ?>,'<?= htmlspecialchars($p['nama_paket'],ENT_QUOTES) ?>',<?= $p['durasi_menit'] ?>,<?= $p['harga'] ?>)"><i class='bx bx-edit-alt'></i></button>
                    <a href="?delete_package=<?= $p['id'] ?>" class="pkg-act-btn del" onclick="return confirm('Hapus paket ini?')"><i class='bx bx-trash'></i></a>
                </div>
                <div class="pkg-duration"><?= $p['durasi_menit'] ?> <small>MENIT</small></div>
                <div class="pkg-name"><?= htmlspecialchars($p['nama_paket']) ?></div>
                <div class="pkg-price"><span>Rp</span> <?= number_format($p['harga']) ?></div>
            </div>
            <?php endforeach; endif; ?>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════ -->
<!-- TAB 2: SNACK & DRINKS                               -->
<!-- ═══════════════════════════════════════════════════ -->
<div id="tab-snack" class="tab-panel">
    <div class="section-card">
        <div class="section-header">
            <div class="section-header-left">
                <i class='bx bxs-store'></i>
                <h3>Daftar Produk</h3>
            </div>
            <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
                <div class="search-box">
                    <i class='bx bx-search'></i>
                    <input type="text" id="searchSnack" placeholder="Cari barang..." oninput="filterSnacks()">
                </div>
                <button type="button" class="btn-add" onclick="openAddSnack()"><i class='bx bx-plus'></i> Tambah</button>
            </div>
        </div>

        <div style="overflow-x:auto;">
            <table class="inv-table">
                <thead>
                    <tr>
                        <th>Produk</th>
                        <th>Stok</th>
                        <th>Harga Jual</th>
                        <th style="text-align:right;">Aksi</th>
                    </tr>
                </thead>
                <tbody id="snackBody">
                    <?php if (empty($snack_list)): ?>
                    <tr><td colspan="4"><div class="empty-state"><i class='bx bxs-store'></i><p>Belum ada produk</p></div></td></tr>
                    <?php else: foreach ($snack_list as $s):
                        $stok = (int)$s['stok'];
                        $stock_class = $stok >= 10 ? 'stock-ok' : ($stok >= 5 ? 'stock-warn' : 'stock-danger');
                        $profit = (int)$s['harga_jual'] - (int)$s['harga_beli'];
                        // Emoji berdasarkan nama (simple heuristic)
                        $nm = strtolower($s['nama_barang']);
                        $emoji = '📦';
                        if (strpos($nm,'air')!==false||strpos($nm,'aqua')!==false||strpos($nm,'mineral')!==false) $emoji='💧';
                        elseif (strpos($nm,'teh')!==false||strpos($nm,'tea')!==false) $emoji='🍵';
                        elseif (strpos($nm,'kopi')!==false||strpos($nm,'coffee')!==false) $emoji='☕';
                        elseif (strpos($nm,'mie')!==false||strpos($nm,'indomie')!==false||strpos($nm,'noodle')!==false) $emoji='🍜';
                        elseif (strpos($nm,'chips')!==false||strpos($nm,'keripik')!==false||strpos($nm,'snack')!==false||strpos($nm,'chitato')!==false) $emoji='🍿';
                        elseif (strpos($nm,'coklat')!==false||strpos($nm,'choco')!==false) $emoji='🍫';
                        elseif (strpos($nm,'susu')!==false||strpos($nm,'milk')!==false) $emoji='🥛';
                        elseif (strpos($nm,'roti')!==false||strpos($nm,'bread')!==false) $emoji='🍞';
                        elseif (strpos($nm,'es')!==false||strpos($nm,'ice')!==false) $emoji='🧊';
                        elseif (strpos($nm,'juice')!==false||strpos($nm,'jus')!==false) $emoji='🧃';
                        elseif (strpos($nm,'soda')!==false||strpos($nm,'cola')!==false||strpos($nm,'fanta')!==false||strpos($nm,'sprite')!==false) $emoji='🥤';
                        elseif (strpos($nm,'rokok')!==false||strpos($nm,'cigaret')!==false) $emoji='🚬';
                        elseif (strpos($nm,'permen')!==false||strpos($nm,'candy')!==false) $emoji='🍬';
                        elseif (strpos($nm,'biskuit')!==false||strpos($nm,'biscuit')!==false||strpos($nm,'oreo')!==false) $emoji='🍪';
                        elseif (strpos($nm,'nasi')!==false||strpos($nm,'rice')!==false) $emoji='🍚';
                    ?>
                    <tr class="snack-row" data-name="<?= strtolower($s['nama_barang']) ?>">
                        <td>
                            <div class="item-info">
                                <div class="item-avatar"><?= $emoji ?></div>
                                <div>
                                    <div class="item-name"><?= htmlspecialchars($s['nama_barang']) ?></div>
                                    <div class="item-modal">Modal: Rp <?= number_format($s['harga_beli']) ?></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="stock-badge <?= $stock_class ?>">
                                <span class="stock-dot"></span>
                                <?= $stok ?>
                            </span>
                        </td>
                        <td>
                            <span class="price-col">Rp <?= number_format($s['harga_jual']) ?></span>
                            <?php if ($profit > 0): ?><span class="profit-tag">+<?= number_format($profit) ?></span><?php endif; ?>
                        </td>
                        <td>
                            <div class="row-actions">
                                <button type="button" class="row-act" onclick="openEditSnack('<?= $s['id'] ?>','<?= htmlspecialchars($s['nama_barang'],ENT_QUOTES) ?>','<?= $s['harga_beli'] ?>','<?= $s['harga_jual'] ?>','<?= $s['stok'] ?>')"><i class='bx bx-edit-alt'></i></button>
                                <a href="?delete_snack=<?= $s['id'] ?>" class="row-act del" onclick="return confirm('Hapus produk ini?')"><i class='bx bx-trash'></i></a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════ -->
<!-- MODAL: EDIT PAKET                                   -->
<!-- ═══════════════════════════════════════════════════ -->
<div id="modalPkg" class="modal-bg">
    <div class="modal-box">
        <div class="modal-title"><i class='bx bxs-edit'></i> Edit Paket</div>
        <form method="POST">
            <input type="hidden" name="id" id="ep_id">
            <div class="modal-row">
                <label class="modal-label">Nama Paket</label>
                <input type="text" name="nama_paket" id="ep_nama" class="modal-fi" required>
            </div>
            <div class="modal-row-2">
                <div>
                    <label class="modal-label">Durasi (menit)</label>
                    <input type="number" name="durasi_menit" id="ep_durasi" class="modal-fi" required>
                </div>
                <div>
                    <label class="modal-label">Harga (Rp)</label>
                    <input type="number" name="harga" id="ep_harga" class="modal-fi" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-cancel" onclick="closeAllModals()">Batal</button>
                <button type="submit" name="update_paket" class="btn-modal-save"><i class='bx bx-save'></i> Simpan</button>
            </div>
        </form>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════ -->
<!-- MODAL: ADD/EDIT SNACK                               -->
<!-- ═══════════════════════════════════════════════════ -->
<div id="modalSnack" class="modal-bg">
    <div class="modal-box">
        <div class="modal-title"><i class='bx bxs-edit'></i> <span id="ms_title">Edit Produk</span></div>
        <form method="POST">
            <input type="hidden" name="id" id="es_id">
            <div class="modal-row">
                <label class="modal-label">Nama Barang</label>
                <input type="text" name="nama" id="es_nama" class="modal-fi" required>
            </div>
            <div class="modal-row-2">
                <div>
                    <label class="modal-label">Harga Beli</label>
                    <input type="number" name="beli" id="es_beli" class="modal-fi" required>
                </div>
                <div>
                    <label class="modal-label">Harga Jual</label>
                    <input type="number" name="jual" id="es_jual" class="modal-fi" required>
                </div>
            </div>
            <div class="modal-row">
                <label class="modal-label">Stok</label>
                <input type="number" name="stok" id="es_stok" class="modal-fi" required>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-cancel" onclick="closeAllModals()">Batal</button>
                <button type="submit" name="update_snack" id="ms_submit_btn" class="btn-modal-save"><i class='bx bx-save'></i> Simpan</button>
            </div>
        </form>
    </div>
</div>

<script>
// ─── TAB SWITCHING ───
function switchTab(tab, btn) {
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById('tab-' + tab).classList.add('active');
    btn.classList.add('active');
}

// ─── SEARCH SNACKS ───
function filterSnacks() {
    const q = document.getElementById('searchSnack').value.toLowerCase();
    document.querySelectorAll('.snack-row').forEach(row => {
        row.style.display = row.dataset.name.includes(q) ? '' : 'none';
    });
}

// ─── MODAL HELPERS ───
function closeAllModals() {
    document.querySelectorAll('.modal-bg').forEach(m => m.style.display = 'none');
}
window.onclick = function(e) { if (e.target.classList.contains('modal-bg')) closeAllModals(); };
document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeAllModals(); });

// Edit paket
function openEditPkg(id, nama, durasi, harga) {
    document.getElementById('ep_id').value = id;
    document.getElementById('ep_nama').value = nama;
    document.getElementById('ep_durasi').value = durasi;
    document.getElementById('ep_harga').value = harga;
    document.getElementById('modalPkg').style.display = 'flex';
}

// Edit snack
function openEditSnack(id, nama, beli, jual, stok) {
    document.getElementById('ms_title').textContent = 'Edit Produk';
    document.getElementById('es_id').value = id;
    document.getElementById('es_nama').value = nama;
    document.getElementById('es_beli').value = beli;
    document.getElementById('es_jual').value = jual;
    document.getElementById('es_stok').value = stok;
    document.getElementById('ms_submit_btn').name = 'update_snack';
    document.getElementById('modalSnack').style.display = 'flex';
}

// Add snack (reuse modal)
function openAddSnack() {
    document.getElementById('ms_title').textContent = 'Tambah Produk Baru';
    document.getElementById('es_id').value = '';
    document.getElementById('es_nama').value = '';
    document.getElementById('es_beli').value = '';
    document.getElementById('es_jual').value = '';
    document.getElementById('es_stok').value = '';
    document.getElementById('ms_submit_btn').name = 'add_snack';
    document.getElementById('modalSnack').style.display = 'flex';
}
</script>

<?php ob_end_flush(); ?>