<?php
ob_start();
include 'config.php';
checkLogin();

$page_title  = "Manajemen Voucher";
$active_page = "voucher";
include 'layout.php';

// ── Auto-migrate tabel vouchers ──────────────────────────────
$conn->query("CREATE TABLE IF NOT EXISTS `vouchers` (
    `id`            INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `kode`          VARCHAR(50)  NOT NULL UNIQUE,
    `nama`          VARCHAR(100) NOT NULL DEFAULT '',
    `jenis`         ENUM('nominal','persen','menit') NOT NULL DEFAULT 'nominal',
    `nilai`         INT UNSIGNED NOT NULL DEFAULT 0,
    `min_jam`       DECIMAL(4,1) UNSIGNED NOT NULL DEFAULT 0,
    `status`        ENUM('aktif','used','expired','nonaktif') NOT NULL DEFAULT 'aktif',
    `used_by_trx`   INT UNSIGNED NULL DEFAULT NULL,
    `used_at`       DATETIME NULL DEFAULT NULL,
    `expired_at`    DATETIME NULL DEFAULT NULL,
    `keterangan`    VARCHAR(255) NOT NULL DEFAULT '',
    `created_at`    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_kode`   (`kode`),
    KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// ── Helpers ───────────────────────────────────────────────────
function gen_kode(string $suffix = ''): string {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    if ($suffix === '') {
        $suffix = '';
        for ($i = 0; $i < 4; $i++) $suffix .= $chars[random_int(0, strlen($chars)-1)];
        $suffix .= '-';
        for ($i = 0; $i < 4; $i++) $suffix .= $chars[random_int(0, strlen($chars)-1)];
    }
    return 'CECOWEL-' . strtoupper($suffix);
}

$errors = []; $success = '';

// ── Handle: Buat Voucher ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buat_voucher'])) {
    $jenis      = $_POST['jenis']      ?? 'nominal';
    $nilai      = (int)($_POST['nilai']  ?? 0);
    $min_jam    = (float)($_POST['min_jam'] ?? 0);
    $nama       = trim($_POST['nama']   ?? '');
    $keterangan = trim($_POST['keterangan'] ?? '');
    $jumlah     = max(1, min(100, (int)($_POST['jumlah'] ?? 1)));
    $exp_raw    = trim($_POST['expired_at'] ?? '');
    $expired_at = $exp_raw ? date('Y-m-d H:i:s', strtotime($exp_raw)) : null;
    $custom_sfx = strtoupper(preg_replace('/[^A-Z0-9\-]/i','', trim($_POST['custom_suffix'] ?? '')));

    if (!in_array($jenis, ['nominal','persen','menit'])) $errors[] = "Jenis tidak valid";
    if ($nilai <= 0) $errors[] = "Nilai harus > 0";
    if ($jenis === 'persen' && $nilai > 100) $errors[] = "Persen maksimal 100";
    if ($jenis === 'menit'  && $nilai > 300) $errors[] = "Gratis menit maksimal 300";
    if ($jumlah > 1 && $custom_sfx !== '') $errors[] = "Custom kode hanya untuk 1 voucher";

    if (empty($errors)) {
        $dibuat = 0;
        for ($i = 0; $i < $jumlah; $i++) {
            $kode = ($custom_sfx !== '') ? gen_kode($custom_sfx) : gen_kode();
            $attempt = 0;
            while ($attempt < 10) {
                $chk = $conn->prepare("SELECT id FROM vouchers WHERE kode=?");
                $chk->bind_param("s",$kode); $chk->execute();
                if ($chk->get_result()->num_rows === 0) { $chk->close(); break; }
                $chk->close();
                $kode = gen_kode();
                $attempt++;
            }
            $stmt = $conn->prepare("INSERT INTO vouchers (kode,nama,jenis,nilai,min_jam,expired_at,keterangan) VALUES (?,?,?,?,?,?,?)");
            $stmt->bind_param("sssidss", $kode, $nama, $jenis, $nilai, $min_jam, $expired_at, $keterangan);
            if ($stmt->execute()) $dibuat++;
            $stmt->close();
        }
        $success = "✓ {$dibuat} voucher berhasil dibuat!";
        write_log($conn, 'VOUCHER_CREATE', "Buat {$dibuat} voucher jenis={$jenis} nilai={$nilai}");
    }
}

// ── Handle: Toggle / Hapus ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_id'])) {
    $vid    = (int)$_POST['toggle_id'];
    $action = $_POST['toggle_action'] ?? 'nonaktif';
    if ($action === 'hapus') {
        $s = $conn->prepare("DELETE FROM vouchers WHERE id=?");
        $s->bind_param("i",$vid); $s->execute(); $s->close();
        $success = "✓ Voucher dihapus.";
    } else {
        $new_status = ($action === 'aktifkan') ? 'aktif' : 'nonaktif';
        $s = $conn->prepare("UPDATE vouchers SET status=? WHERE id=?");
        $s->bind_param("si",$new_status,$vid); $s->execute(); $s->close();
        $success = "✓ Status diperbarui.";
    }
}

// ── Ambil data voucher ────────────────────────────────────────
$filter_status = $_GET['fs'] ?? 'semua';
$filter_jenis  = $_GET['fj'] ?? 'semua';
$search        = trim($_GET['q'] ?? '');

$where = "WHERE 1=1";
$params = []; $types = '';
if ($filter_status !== 'semua') { $where .= " AND status=?"; $params[] = $filter_status; $types .= 's'; }
if ($filter_jenis  !== 'semua') { $where .= " AND jenis=?";  $params[] = $filter_jenis;  $types .= 's'; }
if ($search !== '') {
    $like = "%{$search}%";
    $where .= " AND (kode LIKE ? OR nama LIKE ?)";
    $params[] = $like; $params[] = $like; $types .= 'ss';
}

$sql  = "SELECT * FROM vouchers {$where} ORDER BY created_at DESC LIMIT 200";
$stmt = $conn->prepare($sql);
if (!empty($params)) $stmt->bind_param($types, ...$params);
$stmt->execute();
$vouchers = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$stat = $conn->query("SELECT
    COUNT(*) as total,
    SUM(status='aktif') as aktif,
    SUM(status='used') as used,
    SUM(status='expired') as expired,
    SUM(status='nonaktif') as nonaktif
FROM vouchers")->fetch_assoc();
?>

<style>
/* ── Variables ── */
:root {
    --v-bg: #070d1a;
    --v-surface: rgba(10, 20, 40, 0.8);
    --v-surface2: rgba(15, 30, 60, 0.6);
    --v-border: rgba(6, 182, 212, 0.12);
    --v-border-bright: rgba(6, 182, 212, 0.35);
    --v-primary: #06b6d4;
    --v-primary-dim: rgba(6, 182, 212, 0.15);
    --v-success: #10b981;
    --v-success-dim: rgba(16, 185, 129, 0.15);
    --v-warning: #f59e0b;
    --v-warning-dim: rgba(245, 158, 11, 0.12);
    --v-danger: #ef4444;
    --v-danger-dim: rgba(239, 68, 68, 0.12);
    --v-purple: #a78bfa;
    --v-purple-dim: rgba(167, 139, 250, 0.15);
    --v-muted: #475569;
    --v-text: #e2e8f0;
    --v-mono: 'JetBrains Mono', 'Fira Code', monospace;
}

/* ── Layout ── */
.vp-wrap {
    display: flex;
    flex-direction: column;
    gap: 24px;
    max-width: 1300px;
    padding-bottom: 48px;
}

/* ── Alert ── */
.vp-alert {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 20px;
    border-radius: 14px;
    font-size: .88rem;
    font-weight: 600;
    animation: slideDown .3s ease;
}
.vp-alert.err { background: var(--v-danger-dim); border: 1px solid rgba(239,68,68,.3); color: #fca5a5; }
.vp-alert.ok  { background: var(--v-success-dim); border: 1px solid rgba(16,185,129,.3); color: #6ee7b7; }
.vp-alert i   { font-size: 1.3rem; flex-shrink: 0; }
@keyframes slideDown { from { opacity:0; transform:translateY(-8px); } to { opacity:1; transform:translateY(0); } }

/* ── Stat Cards ── */
.vp-stats {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 14px;
}
@media (max-width: 900px) { .vp-stats { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 500px) { .vp-stats { grid-template-columns: repeat(2, 1fr); } }

.vp-stat {
    background: var(--v-surface);
    border: 1px solid var(--v-border);
    border-radius: 18px;
    padding: 20px 16px;
    text-align: center;
    position: relative;
    overflow: hidden;
    transition: transform .2s, border-color .2s;
    cursor: default;
}
.vp-stat:hover { transform: translateY(-3px); border-color: var(--v-border-bright); }
.vp-stat::after {
    content: '';
    position: absolute;
    bottom: 0; left: 0; right: 0;
    height: 2px;
    border-radius: 0 0 18px 18px;
}
.vp-stat.s-total::after  { background: linear-gradient(90deg, var(--v-primary), transparent); }
.vp-stat.s-aktif::after  { background: linear-gradient(90deg, var(--v-success), transparent); }
.vp-stat.s-used::after   { background: linear-gradient(90deg, var(--v-muted), transparent); }
.vp-stat.s-exp::after    { background: linear-gradient(90deg, var(--v-danger), transparent); }
.vp-stat.s-nonaktif::after { background: linear-gradient(90deg, var(--v-warning), transparent); }

.vp-stat-num {
    font-family: var(--v-mono);
    font-size: 2rem;
    font-weight: 900;
    line-height: 1;
    margin-bottom: 6px;
}
.vp-stat-lbl {
    font-size: .65rem;
    text-transform: uppercase;
    letter-spacing: 1.5px;
    font-weight: 700;
    color: var(--v-muted);
}
.s-total  .vp-stat-num { color: #fff; }
.s-aktif  .vp-stat-num { color: var(--v-success); }
.s-used   .vp-stat-num { color: var(--v-muted); }
.s-exp    .vp-stat-num { color: var(--v-danger); }
.s-nonaktif .vp-stat-num { color: var(--v-warning); }

/* ── Panel ── */
.vp-panel {
    background: var(--v-surface);
    border: 1px solid var(--v-border);
    border-radius: 22px;
    overflow: hidden;
    backdrop-filter: blur(12px);
}
.vp-panel-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 20px 26px;
    border-bottom: 1px solid var(--v-border);
    background: rgba(255,255,255,.02);
}
.vp-panel-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1rem;
    font-weight: 800;
    color: #fff;
}
.vp-panel-title i { color: var(--v-primary); font-size: 1.3rem; }
.vp-panel-body { padding: 26px; }

/* ── Create Form ── */
.vp-form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 16px;
}
.vp-field { display: flex; flex-direction: column; gap: 7px; }
.vp-field label {
    font-size: .68rem;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: var(--v-muted);
}
.vp-field input,
.vp-field select {
    background: rgba(0,0,0,.35);
    border: 1px solid var(--v-border);
    border-radius: 12px;
    color: var(--v-text);
    padding: 11px 15px;
    font-size: .9rem;
    outline: none;
    width: 100%;
    transition: border-color .2s, background .2s;
    font-family: inherit;
    -webkit-appearance: none;
    color-scheme: dark;
}
.vp-field input:focus,
.vp-field select:focus {
    border-color: var(--v-primary);
    background: rgba(6,182,212,.06);
}
.vp-field option { background: #0f172a; }
.vp-hint {
    font-size: .7rem;
    color: var(--v-muted);
    margin-top: 2px;
    display: flex;
    align-items: center;
    gap: 5px;
}

.vp-kode-wrap { display: flex; }
.vp-kode-prefix {
    background: var(--v-primary-dim);
    border: 1px solid var(--v-border-bright);
    border-right: none;
    border-radius: 12px 0 0 12px;
    padding: 11px 12px;
    color: var(--v-primary);
    font-family: var(--v-mono);
    font-size: .82rem;
    font-weight: 700;
    white-space: nowrap;
    display: flex;
    align-items: center;
}
.vp-kode-input { border-radius: 0 12px 12px 0 !important; }

/* Jenis Selector */
.jenis-tabs {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    grid-column: span 1;
}
.jenis-tab {
    padding: 10px 8px;
    border-radius: 12px;
    border: 1.5px solid var(--v-border);
    background: rgba(0,0,0,.3);
    color: var(--v-muted);
    font-size: .75rem;
    font-weight: 700;
    cursor: pointer;
    text-align: center;
    transition: all .2s;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}
.jenis-tab span { font-size: 1.2rem; }
.jenis-tab:hover { border-color: var(--v-primary); color: var(--v-text); }
.jenis-tab.active.nominal { border-color: var(--v-success); background: var(--v-success-dim); color: var(--v-success); }
.jenis-tab.active.persen  { border-color: var(--v-primary); background: var(--v-primary-dim); color: var(--v-primary); }
.jenis-tab.active.menit   { border-color: var(--v-purple);  background: var(--v-purple-dim);  color: var(--v-purple); }

/* Submit row */
.vp-submit-row {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--v-border);
}
.vp-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    border-radius: 12px;
    border: none;
    font-weight: 800;
    font-size: .88rem;
    cursor: pointer;
    transition: all .2s;
    white-space: nowrap;
}
.vp-btn:hover { transform: translateY(-2px); }
.vp-btn.primary {
    background: linear-gradient(135deg, var(--v-primary), #0891b2);
    color: #000;
    box-shadow: 0 4px 20px -8px rgba(6,182,212,.5);
}
.vp-btn.primary:hover { box-shadow: 0 8px 24px -8px rgba(6,182,212,.6); }
.vp-btn.ghost {
    background: rgba(255,255,255,.06);
    border: 1px solid rgba(255,255,255,.1);
    color: var(--v-text);
}
.vp-btn.ghost:hover { background: rgba(255,255,255,.1); }

/* ── Filter Bar ── */
.vp-filter {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
    padding: 16px 26px;
    border-bottom: 1px solid var(--v-border);
    background: rgba(0,0,0,.2);
}
.vp-filter input,
.vp-filter select {
    background: rgba(0,0,0,.4);
    border: 1px solid var(--v-border);
    border-radius: 10px;
    color: var(--v-text);
    padding: 9px 14px;
    font-size: .83rem;
    outline: none;
    font-family: inherit;
    transition: border-color .2s;
    -webkit-appearance: none;
    color-scheme: dark;
}
.vp-filter input { min-width: 220px; }
.vp-filter input:focus,
.vp-filter select:focus { border-color: var(--v-primary); }
.vp-filter option { background: #0f172a; }
.vp-filter-btn {
    background: var(--v-primary-dim);
    border: 1px solid var(--v-border-bright);
    border-radius: 10px;
    color: var(--v-primary);
    padding: 9px 18px;
    font-weight: 700;
    font-size: .83rem;
    cursor: pointer;
    transition: all .2s;
    white-space: nowrap;
}
.vp-filter-btn:hover { background: rgba(6,182,212,.25); }

/* ── Table ── */
.vp-table-wrap { overflow-x: auto; }
.vp-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 900px;
}
.vp-table th {
    text-align: left;
    padding: 12px 16px;
    font-size: .65rem;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: var(--v-muted);
    font-weight: 800;
    background: rgba(0,0,0,.3);
    border-bottom: 1px solid var(--v-border);
    white-space: nowrap;
    position: sticky;
    top: 0;
    z-index: 2;
}
.vp-table td {
    padding: 14px 16px;
    font-size: .87rem;
    border-bottom: 1px solid rgba(255,255,255,.04);
    vertical-align: middle;
    color: var(--v-text);
}
.vp-table tr:hover td { background: rgba(6,182,212,.03); }
.vp-table tr:last-child td { border-bottom: none; }

/* Kode badge */
.kode-chip {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    background: rgba(6,182,212,.1);
    border: 1px solid rgba(6,182,212,.25);
    border-radius: 8px;
    padding: 6px 11px;
    font-family: var(--v-mono);
    font-size: .8rem;
    font-weight: 700;
    color: var(--v-primary);
    cursor: pointer;
    transition: all .2s;
    letter-spacing: .5px;
    white-space: nowrap;
}
.kode-chip:hover { background: rgba(6,182,212,.2); border-color: var(--v-primary); }
.kode-chip i { font-size: .85rem; opacity: .7; }

/* Pills */
.pill {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: .68rem;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: .5px;
    white-space: nowrap;
}
.pill-nominal { background: var(--v-success-dim); color: var(--v-success); border: 1px solid rgba(16,185,129,.25); }
.pill-persen  { background: var(--v-primary-dim);  color: var(--v-primary);  border: 1px solid rgba(6,182,212,.25); }
.pill-menit   { background: var(--v-purple-dim);   color: var(--v-purple);   border: 1px solid rgba(167,139,250,.25); }
.pill-aktif   { background: var(--v-success-dim); color: var(--v-success); border: 1px solid rgba(16,185,129,.3); }
.pill-used    { background: rgba(71,85,105,.2);    color: #94a3b8;          border: 1px solid rgba(71,85,105,.3); }
.pill-expired { background: var(--v-danger-dim);   color: var(--v-danger);  border: 1px solid rgba(239,68,68,.3); }
.pill-nonaktif{ background: var(--v-warning-dim);  color: var(--v-warning); border: 1px solid rgba(245,158,11,.3); }

.nilai-text { font-family: var(--v-mono); font-weight: 700; color: #fff; }

/* Action buttons */
.act-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 11px;
    border-radius: 8px;
    border: none;
    font-size: .72rem;
    font-weight: 700;
    cursor: pointer;
    transition: all .2s;
    white-space: nowrap;
}
.act-btn:hover { transform: translateY(-1px); }
.act-del    { background: var(--v-danger-dim);   border: 1px solid rgba(239,68,68,.25);  color: var(--v-danger); }
.act-del:hover  { background: rgba(239,68,68,.25); }
.act-off    { background: var(--v-warning-dim);  border: 1px solid rgba(245,158,11,.25); color: var(--v-warning); }
.act-off:hover  { background: rgba(245,158,11,.25); }
.act-on     { background: var(--v-success-dim);  border: 1px solid rgba(16,185,129,.25); color: var(--v-success); }
.act-on:hover   { background: rgba(16,185,129,.25); }

/* Empty */
.vp-empty {
    text-align: center;
    padding: 70px 20px;
    color: var(--v-muted);
}
.vp-empty i { font-size: 4rem; display: block; margin-bottom: 14px; opacity: .5; }
.vp-empty p { font-size: .95rem; }

/* Toast */
.vp-toast {
    position: fixed;
    bottom: 28px;
    left: 50%;
    transform: translateX(-50%) translateY(80px);
    background: var(--v-success);
    color: #000;
    padding: 11px 22px;
    border-radius: 12px;
    font-weight: 800;
    font-size: .88rem;
    z-index: 9999;
    transition: transform .3s cubic-bezier(.34,1.56,.64,1);
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
    pointer-events: none;
    box-shadow: 0 8px 30px rgba(0,0,0,.4);
}
.vp-toast.show { transform: translateX(-50%) translateY(0); }

/* Scrollbar */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(6,182,212,.2); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: rgba(6,182,212,.4); }
</style>

<div class="vp-wrap">

<?php if (!empty($errors)): ?>
<div class="vp-alert err">
    <i class='bx bx-error-circle'></i>
    <span><?= implode('<br>', array_map('htmlspecialchars', $errors)) ?></span>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="vp-alert ok">
    <i class='bx bx-check-circle'></i>
    <span><?= htmlspecialchars($success) ?></span>
</div>
<?php endif; ?>

<!-- ── Statistik ── -->
<div class="vp-stats">
    <div class="vp-stat s-total">
        <div class="vp-stat-num"><?= (int)$stat['total'] ?></div>
        <div class="vp-stat-lbl">Total</div>
    </div>
    <div class="vp-stat s-aktif">
        <div class="vp-stat-num"><?= (int)$stat['aktif'] ?></div>
        <div class="vp-stat-lbl">Aktif</div>
    </div>
    <div class="vp-stat s-used">
        <div class="vp-stat-num"><?= (int)$stat['used'] ?></div>
        <div class="vp-stat-lbl">Dipakai</div>
    </div>
    <div class="vp-stat s-exp">
        <div class="vp-stat-num"><?= (int)$stat['expired'] ?></div>
        <div class="vp-stat-lbl">Expired</div>
    </div>
    <div class="vp-stat s-nonaktif">
        <div class="vp-stat-num"><?= (int)$stat['nonaktif'] ?></div>
        <div class="vp-stat-lbl">Nonaktif</div>
    </div>
</div>

<!-- ── Form Buat Voucher ── -->
<div class="vp-panel">
    <div class="vp-panel-head">
        <div class="vp-panel-title">
            <i class='bx bx-gift'></i> Buat Voucher Baru
        </div>
    </div>
    <div class="vp-panel-body">
        <form method="POST" id="form-buat">
            <input type="hidden" name="buat_voucher" value="1">
            <input type="hidden" name="jenis" id="jenis_hidden" value="nominal">

            <div class="vp-form-grid">

                <!-- Jenis Selector -->
                <div class="vp-field" style="grid-column: span 1;">
                    <label>Jenis Diskon</label>
                    <div class="jenis-tabs">
                        <div class="jenis-tab active nominal" onclick="setJenis('nominal',this)">
                            <span>💰</span> Nominal
                        </div>
                        <div class="jenis-tab persen" onclick="setJenis('persen',this)">
                            <span>📊</span> Persen
                        </div>
                        <div class="jenis-tab menit" onclick="setJenis('menit',this)">
                            <span>⏱</span> Menit
                        </div>
                    </div>
                </div>

                <!-- Nilai -->
                <div class="vp-field">
                    <label id="nilai_lbl">Nilai Diskon (Rp)</label>
                    <input type="number" name="nilai" id="nilai_input"
                           placeholder="contoh: 10000" min="1" required>
                    <div class="vp-hint" id="nilai_hint">
                        <i class='bx bx-info-circle'></i> Nominal potongan dalam Rupiah
                    </div>
                </div>

                <!-- Nama -->
                <div class="vp-field">
                    <label>Nama Voucher</label>
                    <input type="text" name="nama" placeholder="contoh: Promo Weekend" maxlength="100">
                    <div class="vp-hint"><i class='bx bx-tag'></i> Tampil di daftar kasir</div>
                </div>

                <!-- Jumlah -->
                <div class="vp-field">
                    <label>Jumlah Voucher</label>
                    <input type="number" name="jumlah" value="1" min="1" max="100"
                           id="jumlah_input" oninput="toggleCustom()">
                    <div class="vp-hint"><i class='bx bx-copy'></i> Maks. 100 sekaligus</div>
                </div>

                <!-- Kode Custom -->
                <div class="vp-field" id="custom_group">
                    <label>Kode Custom (opsional)</label>
                    <div class="vp-kode-wrap">
                        <span class="vp-kode-prefix">CECOWEL-</span>
                        <input type="text" name="custom_suffix" id="custom_suffix"
                               placeholder="GAMER1"
                               maxlength="20"
                               class="vp-kode-input"
                               oninput="this.value=this.value.toUpperCase().replace(/[^A-Z0-9\-]/g,'')">
                    </div>
                    <div class="vp-hint"><i class='bx bx-shuffle'></i> Kosong = acak otomatis</div>
                </div>

                <!-- Min Jam -->
                <div class="vp-field">
                    <label>Min. Jam Bermain</label>
                    <input type="number" name="min_jam" placeholder="0 = bebas"
                           min="0" max="24" step="0.5" value="0">
                    <div class="vp-hint"><i class='bx bx-time'></i> 0 = tidak ada syarat</div>
                </div>

                <!-- Expired -->
                <div class="vp-field">
                    <label>Expired Date (opsional)</label>
                    <input type="datetime-local" name="expired_at">
                    <div class="vp-hint"><i class='bx bx-calendar-x'></i> Kosong = tidak expired</div>
                </div>

                <!-- Keterangan -->
                <div class="vp-field">
                    <label>Keterangan Internal</label>
                    <input type="text" name="keterangan" placeholder="catatan untuk kasir" maxlength="255">
                    <div class="vp-hint"><i class='bx bx-note'></i> Hanya tampil di daftar admin</div>
                </div>

            </div>

            <div class="vp-submit-row">
                <button type="submit" class="vp-btn primary">
                    <i class='bx bx-plus-circle'></i> BUAT VOUCHER
                </button>
                <button type="button" class="vp-btn ghost" onclick="previewKode()">
                    <i class='bx bx-show'></i> PREVIEW KODE
                </button>
                <span id="preview_text" style="font-family:var(--v-mono);font-size:.82rem;color:var(--v-primary);opacity:.8;"></span>
            </div>
        </form>
    </div>
</div>

<!-- ── Tabel Voucher ── -->
<div class="vp-panel">
    <div class="vp-panel-head">
        <div class="vp-panel-title">
            <i class='bx bx-list-ul'></i> Daftar Voucher
        </div>
        <span style="font-size:.75rem;color:var(--v-muted);background:rgba(0,0,0,.3);padding:4px 10px;border-radius:8px;font-weight:600;">
            <?= count($vouchers) ?> data
        </span>
    </div>

    <!-- Filter -->
    <form method="GET" class="vp-filter">
        <input type="text" name="q" value="<?= htmlspecialchars($search) ?>"
               placeholder="🔍  Cari kode atau nama...">
        <select name="fs" onchange="this.form.submit()">
            <option value="semua"    <?= $filter_status==='semua'   ?'selected':'' ?>>Semua Status</option>
            <option value="aktif"    <?= $filter_status==='aktif'   ?'selected':'' ?>>✅ Aktif</option>
            <option value="used"     <?= $filter_status==='used'    ?'selected':'' ?>>✔ Dipakai</option>
            <option value="expired"  <?= $filter_status==='expired' ?'selected':'' ?>>⛔ Expired</option>
            <option value="nonaktif" <?= $filter_status==='nonaktif'?'selected':'' ?>>🔕 Nonaktif</option>
        </select>
        <select name="fj" onchange="this.form.submit()">
            <option value="semua"   <?= $filter_jenis==='semua'  ?'selected':'' ?>>Semua Jenis</option>
            <option value="nominal" <?= $filter_jenis==='nominal'?'selected':'' ?>>💰 Nominal</option>
            <option value="persen"  <?= $filter_jenis==='persen' ?'selected':'' ?>>📊 Persen</option>
            <option value="menit"   <?= $filter_jenis==='menit'  ?'selected':'' ?>>⏱ Menit</option>
        </select>
        <button type="submit" class="vp-filter-btn">
            <i class='bx bx-search'></i> Cari
        </button>
        <?php if ($search || $filter_status !== 'semua' || $filter_jenis !== 'semua'): ?>
        <a href="voucher.php" style="font-size:.78rem;color:var(--v-muted);text-decoration:none;padding:9px 12px;border-radius:10px;border:1px solid var(--v-border);transition:.2s;"
           onmouseover="this.style.color='#fff'" onmouseout="this.style.color=''">
            ✕ Reset
        </a>
        <?php endif; ?>
    </form>

    <?php if (empty($vouchers)): ?>
    <div class="vp-empty">
        <i class='bx bx-gift'></i>
        <p>Belum ada voucher<?= ($filter_status !== 'semua' || $search) ? ' sesuai filter' : '' ?>.</p>
    </div>
    <?php else: ?>
    <div class="vp-table-wrap">
        <table class="vp-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Kode</th>
                    <th>Nama</th>
                    <th>Jenis</th>
                    <th>Nilai</th>
                    <th>Min Jam</th>
                    <th>Status</th>
                    <th>Expired</th>
                    <th>Dipakai</th>
                    <th>Dibuat</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($vouchers as $i => $v): ?>
            <?php
                if ($v['status'] === 'aktif' && !empty($v['expired_at']) && strtotime($v['expired_at']) < time()) {
                    $conn->query("UPDATE vouchers SET status='expired' WHERE id={$v['id']}");
                    $v['status'] = 'expired';
                }
                $nilai_str = match($v['jenis']) {
                    'nominal' => 'Rp ' . number_format($v['nilai'],0,',','.'),
                    'persen'  => $v['nilai'] . '%',
                    'menit'   => '+' . $v['nilai'] . ' mnt',
                    default   => $v['nilai'],
                };
                $jenis_icon = match($v['jenis']) {
                    'nominal' => '💰', 'persen' => '📊', 'menit' => '⏱', default => ''
                };
                $status_icon = match($v['status']) {
                    'aktif' => '●', 'used' => '✔', 'expired' => '⛔', 'nonaktif' => '○', default => ''
                };
            ?>
            <tr>
                <td style="color:var(--v-muted);font-size:.78rem;"><?= $i+1 ?></td>
                <td>
                    <span class="kode-chip" onclick="copyKode('<?= htmlspecialchars($v['kode']) ?>')" title="Klik untuk copy">
                        <?= htmlspecialchars($v['kode']) ?>
                        <i class='bx bx-copy'></i>
                    </span>
                </td>
                <td style="color:var(--v-muted);max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                    <?= htmlspecialchars($v['nama'] ?: '—') ?>
                </td>
                <td>
                    <span class="pill pill-<?= $v['jenis'] ?>">
                        <?= $jenis_icon ?> <?= $v['jenis'] ?>
                    </span>
                </td>
                <td><span class="nilai-text"><?= $nilai_str ?></span></td>
                <td style="color:var(--v-muted);font-size:.82rem;">
                    <?= $v['min_jam'] > 0 ? $v['min_jam'].' jam' : '—' ?>
                </td>
                <td>
                    <span class="pill pill-<?= $v['status'] ?>">
                        <?= $status_icon ?> <?= $v['status'] ?>
                    </span>
                </td>
                <td style="font-size:.78rem;color:var(--v-muted);white-space:nowrap;">
                    <?= $v['expired_at'] ? date('d/m/y H:i', strtotime($v['expired_at'])) : '—' ?>
                </td>
                <td style="font-size:.78rem;white-space:nowrap;">
                    <?php if ($v['used_at']): ?>
                        <span style="color:var(--v-muted);"><?= date('d/m/y H:i', strtotime($v['used_at'])) ?></span>
                        <?php if ($v['used_by_trx']): ?>
                            <br><span style="color:var(--v-primary);font-family:var(--v-mono);font-size:.72rem;">
                                Trx #<?= $v['used_by_trx'] ?>
                            </span>
                        <?php endif; ?>
                    <?php else: ?>
                        <span style="color:var(--v-muted);">—</span>
                    <?php endif; ?>
                </td>
                <td style="font-size:.78rem;color:var(--v-muted);white-space:nowrap;">
                    <?= date('d/m/y', strtotime($v['created_at'])) ?>
                </td>
                <td>
                    <div style="display:flex;gap:6px;flex-wrap:nowrap;">
                        <?php if ($v['status'] === 'aktif'): ?>
                        <form method="POST" style="display:inline">
                            <input type="hidden" name="toggle_id" value="<?= $v['id'] ?>">
                            <input type="hidden" name="toggle_action" value="nonaktif">
                            <button type="submit" class="act-btn act-off" title="Nonaktifkan">
                                <i class='bx bx-hide'></i> Off
                            </button>
                        </form>
                        <?php elseif ($v['status'] === 'nonaktif'): ?>
                        <form method="POST" style="display:inline">
                            <input type="hidden" name="toggle_id" value="<?= $v['id'] ?>">
                            <input type="hidden" name="toggle_action" value="aktifkan">
                            <button type="submit" class="act-btn act-on" title="Aktifkan">
                                <i class='bx bx-show'></i> On
                            </button>
                        </form>
                        <?php endif; ?>
                        <?php if (in_array($v['status'], ['used','expired','nonaktif'])): ?>
                        <form method="POST" style="display:inline"
                              onsubmit="return confirm('Hapus voucher <?= htmlspecialchars(addslashes($v['kode'])) ?>?')">
                            <input type="hidden" name="toggle_id" value="<?= $v['id'] ?>">
                            <input type="hidden" name="toggle_action" value="hapus">
                            <button type="submit" class="act-btn act-del" title="Hapus">
                                <i class='bx bx-trash'></i>
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

</div><!-- /vp-wrap -->

<!-- Toast -->
<div class="vp-toast" id="vp-toast">
    <i class='bx bx-check'></i> Kode disalin!
</div>

<script>
// ── Jenis selector ──
function setJenis(val, el) {
    document.querySelectorAll('.jenis-tab').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
    document.getElementById('jenis_hidden').value = val;

    const lbl  = document.getElementById('nilai_lbl');
    const hint = document.getElementById('nilai_hint');
    const inp  = document.getElementById('nilai_input');

    const cfg = {
        nominal: { lbl:'Nilai Diskon (Rp)', hint:'Nominal potongan dalam Rupiah', max:9999999, ph:'contoh: 10000' },
        persen:  { lbl:'Persen Diskon (%)', hint:'Persentase potongan, maks 100%', max:100, ph:'contoh: 20' },
        menit:   { lbl:'Gratis Waktu (menit)', hint:'Tambah waktu gratis, maks 300 menit', max:300, ph:'contoh: 30' },
    };
    const c = cfg[val];
    lbl.textContent  = c.lbl;
    hint.innerHTML   = `<i class='bx bx-info-circle'></i> ${c.hint}`;
    inp.max          = c.max;
    inp.placeholder  = c.ph;
    updatePreview();
}

// ── Toggle custom kode ──
function toggleCustom() {
    const n   = parseInt(document.getElementById('jumlah_input').value) || 1;
    const grp = document.getElementById('custom_group');
    const inp = document.getElementById('custom_suffix');
    grp.style.opacity = n > 1 ? '.4' : '1';
    inp.disabled      = n > 1;
    updatePreview();
}

// ── Preview kode ──
function updatePreview() {
    const sfx = document.getElementById('custom_suffix').value.trim();
    const el  = document.getElementById('preview_text');
    if (sfx) el.textContent = '→ CECOWEL-' + sfx.toUpperCase();
    else el.textContent = '';
}

function previewKode() {
    const sfx = document.getElementById('custom_suffix').value.trim();
    if (sfx) {
        showToast('Preview: CECOWEL-' + sfx.toUpperCase(), '📋');
    } else {
        showToast('Kode acak: CECOWEL-ABCD-1234', '🔀');
    }
}

document.getElementById('custom_suffix').addEventListener('input', updatePreview);

// ── Copy kode ──
function copyKode(kode) {
    navigator.clipboard.writeText(kode)
        .then(() => showToast('Disalin: ' + kode, '✓'))
        .catch(() => {
            const el = document.createElement('textarea');
            el.value = kode;
            document.body.appendChild(el);
            el.select();
            document.execCommand('copy');
            document.body.removeChild(el);
            showToast('Disalin: ' + kode, '✓');
        });
}

// ── Toast ──
let _toastTimer = null;
function showToast(msg, icon = '✓') {
    const t = document.getElementById('vp-toast');
    t.innerHTML = `<span>${icon}</span> ${msg}`;
    t.classList.add('show');
    clearTimeout(_toastTimer);
    _toastTimer = setTimeout(() => t.classList.remove('show'), 2500);
}
</script>