<?php
require 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// Rate biaya dari payment_settings (default: takeaway 5%, catering 10%, service 0%, ppn 0%)
$fee_rates = [];
try {
    $rows = $pdo->query("SELECT key_name, value FROM payment_settings WHERE key_name IN ('takeaway_rate','catering_rate','service_rate','ppn_rate','gojek_enabled','gojek_rate','grab_enabled','grab_rate','shopee_enabled','shopee_rate')")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) $fee_rates[$r['key_name']] = $r['value'];
} catch (Exception $e) {}
$fee_takeaway_rate = (float)($fee_rates['takeaway_rate'] ?? 5);
$fee_catering_rate = (float)($fee_rates['catering_rate'] ?? 10);
$fee_service_rate  = (float)($fee_rates['service_rate']  ?? 0);
$fee_ppn_rate      = (float)($fee_rates['ppn_rate']      ?? 0);

// Platform Online
$gojek_enabled  = ($fee_rates['gojek_enabled']  ?? '0') == '1';
$grab_enabled   = ($fee_rates['grab_enabled']   ?? '0') == '1';
$shopee_enabled = ($fee_rates['shopee_enabled'] ?? '0') == '1';
$fee_gojek_rate  = (float)($fee_rates['gojek_rate']  ?? 20);
$fee_grab_rate   = (float)($fee_rates['grab_rate']   ?? 20);
$fee_shopee_rate = (float)($fee_rates['shopee_rate'] ?? 20);

$kasir_name = $_SESSION['name'] ?? 'Kasir';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <meta charset="UTF-8">
    <!-- KUNCI: viewport fixed, no-zoom untuk tablet & desktop -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>EnakinChikekn • POS</title>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=DM+Mono:wght@500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js" defer></script>

    <style>
        /* =============================================
           RESET & ROOT VARIABLES
        ============================================= */
        *, *::before, *::after {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
            /* Cegah text-size-adjust di iOS/Android */
            -webkit-text-size-adjust: 100%;
            text-size-adjust: 100%;
        }

        :root {
            --bg:        #0f1117;
            --surface:   #181c27;
            --surface2:  #1f2435;
            --border:    #2a3050;
            --accent:    #f59e0b;
            --accent2:   #fbbf24;
            --text:      #e8ecf5;
            --text-muted:#8892b0;
            --green:     #10b981;
            --red:       #056ffa;
            --blue:      #6366f1;

            /* Font scale presisi tablet (768-1024px) & desktop (>1024px) */
            --fs-xs:     0.72rem;
            --fs-sm:     0.82rem;
            --fs-base:   0.92rem;
            --fs-md:     1.05rem;
            --fs-lg:     1.2rem;
            --fs-xl:     1.5rem;

            /* Spacing */
            --gap:       12px;
            --radius:    12px;
            --radius-lg: 18px;
        }

        html, body {
            width: 100%;
            height: 100%;
            overflow: hidden;
            background: var(--bg);
            color: var(--text);
            font-family: 'DM Sans', sans-serif;
            font-size: var(--fs-base);
            line-height: 1.4;
            /* Prevent pull-to-refresh & rubber band scroll */
            overscroll-behavior: none;
            touch-action: manipulation;
        }

        /* =============================================
           LAYOUT ROOT — FIXED, NO SCROLL
        ============================================= */
        #app {
            display: flex;
            flex-direction: column;
            width: 100vw;
            height: 100vh;
            height: 100dvh;
            overflow: hidden;
        }

        /* ── HEADER ── */
        #header {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 0 20px;
            height: 58px;
            background: var(--surface);
            border-bottom: 1px solid var(--border);
        }

        .header-brand {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: var(--fs-md);
            font-weight: 700;
            letter-spacing: -0.5px;
            white-space: nowrap;
        }
        .header-brand .logo {
            width: 34px; height: 34px;
            background: var(--accent);
            border-radius: 9px;
            display: flex; align-items: center; justify-content: center;
            font-size: 18px;
            flex-shrink: 0;
        }

        .header-nav {
            display: flex;
            align-items: center;
            gap: 6px;
            flex-shrink: 0;
        }
        .nav-btn {
            display: flex; align-items: center; gap: 6px;
            padding: 7px 14px;
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            color: var(--text-muted);
            font-size: var(--fs-sm);
            font-weight: 500;
            text-decoration: none;
            cursor: pointer;
            transition: color .15s, background .15s;
            white-space: nowrap;
        }
        .nav-btn:hover { background: var(--border); color: var(--text); }

        .kasir-badge {
            padding: 5px 12px;
            background: rgba(245,158,11,.12);
            border: 1px solid rgba(245,158,11,.3);
            border-radius: var(--radius);
            font-size: var(--fs-xs);
            color: var(--accent);
            font-weight: 600;
            white-space: nowrap;
        }

        /* ── MAIN BODY ── */
        #main {
            flex: 1;
            display: flex;
            overflow: hidden;
            min-height: 0;
        }

        /* ── LEFT: MENU PANEL ── */
        #panel-menu {
            flex: 1 1 0;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            min-width: 0;
            background: var(--bg);
        }

        #menu-toolbar {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 16px;
            background: var(--surface);
            border-bottom: 1px solid var(--border);
        }

        .cat-btn {
            padding: 7px 18px;
            border-radius: 8px;
            border: 1px solid var(--border);
            background: transparent;
            color: var(--text-muted);
            font-size: var(--fs-sm);
            font-weight: 600;
            cursor: pointer;
            transition: all .15s;
            white-space: nowrap;
        }
        .cat-btn:hover { border-color: var(--accent); color: var(--accent); }
        .cat-btn.active {
            background: var(--accent);
            border-color: var(--accent);
            color: #000;
        }

        #search-box {
            flex: 1;
            padding: 7px 14px;
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 8px;
            color: var(--text);
            font-size: var(--fs-sm);
            font-family: inherit;
            outline: none;
            transition: border-color .15s;
        }
        #search-box:focus { border-color: var(--accent); }
        #search-box::placeholder { color: var(--text-muted); }

        #menu-scroll {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 14px 16px;
            /* Smooth scroll untuk tablet */
            -webkit-overflow-scrolling: touch;
            overscroll-behavior: contain;
        }
        /* Scrollbar styling */
        #menu-scroll::-webkit-scrollbar { width: 5px; }
        #menu-scroll::-webkit-scrollbar-track { background: transparent; }
        #menu-scroll::-webkit-scrollbar-thumb { background: var(--border); border-radius: 99px; }

        #menu-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(155px, 1fr));
            gap: 12px;
        }

        /* Menu Card */
        .menu-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--radius-lg);
            overflow: hidden;
            cursor: pointer;
            transition: transform .15s, border-color .15s, box-shadow .15s;
            user-select: none;
            -webkit-user-select: none;
        }
        .menu-card:hover {
            transform: translateY(-2px);
            border-color: var(--accent);
            box-shadow: 0 8px 24px rgba(245,158,11,.12);
        }
        .menu-card:active { transform: scale(.97); }
        .menu-card img {
            width: 100%;
            aspect-ratio: 4/3;
            object-fit: cover;
            display: block;
            background: var(--surface2);
        }
        .menu-card-body { padding: 10px 12px; }
        .menu-card-name {
            font-size: var(--fs-sm);
            font-weight: 600;
            line-height: 1.3;
            margin-bottom: 4px;
            color: var(--text);
            /* Clamp 2 baris */
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        .menu-card-price {
            font-size: var(--fs-sm);
            font-weight: 700;
            color: var(--accent);
        }

        /* ── DIVIDER ── */
        #divider {
            width: 5px;
            flex-shrink: 0;
            background: var(--bg);
            border-left: 1px solid var(--border);
            border-right: 1px solid var(--border);
        }

        /* ── RIGHT: BILL PANEL ── */
        #panel-bill {
            width: 360px;
            flex-shrink: 0;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            background: var(--surface);
            border-left: 1px solid var(--border);
        }

        /* Bill top controls */
        #bill-controls {
            flex-shrink: 0;
            padding: 10px 14px;
            border-bottom: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .form-select, .form-input {
            width: 100%;
            padding: 8px 12px;
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text);
            font-family: inherit;
            font-size: var(--fs-sm);
            outline: none;
            transition: border-color .15s;
            appearance: none;
            -webkit-appearance: none;
        }
        .form-select:focus, .form-input:focus { border-color: var(--accent); }
        .form-input::placeholder { color: var(--text-muted); }

        .form-row { display: flex; gap: 8px; }
        .form-row .form-input { flex: 1; }

        /* Bill item list */
        #bill-scroll {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 10px 14px;
            -webkit-overflow-scrolling: touch;
            overscroll-behavior: contain;
        }
        #bill-scroll::-webkit-scrollbar { width: 4px; }
        #bill-scroll::-webkit-scrollbar-thumb { background: var(--border); border-radius: 99px; }

        #bill-items { display: flex; flex-direction: column; gap: 8px; }

        .bill-item {
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 10px 12px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .bill-item-top {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 8px;
        }
        .bill-item-info { flex: 1; min-width: 0; }
        .bill-item-name {
            font-size: var(--fs-sm);
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .bill-item-price-base {
            font-size: var(--fs-xs);
            color: var(--text-muted);
            margin-top: 2px;
        }
        .discount-badge {
            font-size: var(--fs-xs);
            color: var(--green);
            margin-left: 4px;
        }

        .bill-item-bottom {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .qty-ctrl {
            display: flex;
            align-items: center;
            gap: 0;
            background: var(--bg);
            border: 1px solid var(--border);
            border-radius: 8px;
            overflow: hidden;
        }
        .qty-btn {
            width: 32px; height: 32px;
            border: none; background: transparent;
            color: var(--text);
            font-size: 18px;
            cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            transition: background .12s;
            flex-shrink: 0;
        }
        .qty-btn:hover { background: var(--border); }
        .qty-btn:active { background: var(--accent); color: #000; }
        .qty-val {
            min-width: 36px;
            text-align: center;
            font-size: var(--fs-sm);
            font-weight: 700;
            color: var(--text);
            font-family: 'DM Mono', monospace;
        }
        .bill-item-line {
            font-size: var(--fs-sm);
            font-weight: 700;
            color: var(--accent);
            white-space: nowrap;
        }
        .btn-remove {
            background: none;
            border: none;
            color: var(--red);
            cursor: pointer;
            font-size: 18px;
            line-height: 1;
            padding: 2px;
            flex-shrink: 0;
            transition: opacity .12s;
        }
        .btn-remove:hover { opacity: .7; }

        #bill-empty {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            gap: 10px;
            color: var(--text-muted);
            font-size: var(--fs-sm);
            text-align: center;
        }
        #bill-empty .empty-icon { font-size: 42px; opacity: .3; }

        /* Bill Summary */
        #bill-summary {
            flex-shrink: 0;
            padding: 10px 14px;
            border-top: 1px solid var(--border);
            background: var(--surface);
        }
        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: var(--fs-sm);
            padding: 3px 0;
            color: var(--text-muted);
        }
        .summary-row .val { font-weight: 600; color: var(--text); font-family: 'DM Mono', monospace; }
        .summary-row.discount .val { color: var(--green); }
        .summary-divider { border: none; border-top: 1px solid var(--border); margin: 6px 0; }
        .summary-total {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: var(--fs-md);
            font-weight: 700;
        }
        .summary-total .total-val { color: var(--accent); font-size: var(--fs-lg); font-family: 'DM Mono', monospace; }

        /* Bill Actions */
        #bill-actions {
            flex-shrink: 0;
            padding: 10px 14px;
            border-top: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .action-row { display: flex; gap: 8px; }

        .btn-action {
            flex: 1;
            padding: 9px 6px;
            border: 1.5px solid var(--border);
            border-radius: 10px;
            background: transparent;
            color: var(--text-muted);
            font-size: var(--fs-xs);
            font-weight: 600;
            cursor: pointer;
            display: flex; align-items: center; justify-content: center; gap: 5px;
            transition: all .15s;
            white-space: nowrap;
            font-family: inherit;
        }
        .btn-action:hover { border-color: var(--accent); color: var(--accent); background: rgba(245,158,11,.07); }
        .btn-action.active-voucher { border-color: var(--green); color: var(--green); background: rgba(16,185,129,.08); }
        .btn-action.active-print { border-color: var(--blue); color: var(--blue); background: rgba(99,102,241,.08); cursor: pointer; }
        .btn-action:disabled { opacity: .4; cursor: not-allowed; }
        .btn-action:disabled:hover { border-color: var(--border); color: var(--text-muted); background: transparent; }

        .btn-charge {
            width: 100%;
            padding: 14px;
            background: var(--accent);
            border: none;
            border-radius: 12px;
            color: #000;
            font-size: var(--fs-md);
            font-weight: 800;
            cursor: pointer;
            transition: background .15s, transform .1s;
            font-family: inherit;
            letter-spacing: -.3px;
        }
        .btn-charge:hover { background: var(--accent2); }
        .btn-charge:active { transform: scale(.98); }
        .btn-charge:disabled { opacity: .5; cursor: not-allowed; }

        /* =============================================
           MODALS
        ============================================= */
        .modal-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,.75);
            z-index: 9000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .modal-overlay.open { display: flex; }
        .modal-box {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--radius-lg);
            padding: 24px;
            width: 100%;
            max-width: 400px;
        }
        .modal-title { font-size: var(--fs-lg); font-weight: 700; margin-bottom: 16px; }
        .modal-input {
            width: 100%;
            padding: 12px 16px;
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text);
            font-size: var(--fs-md);
            font-family: 'DM Mono', monospace;
            outline: none;
            text-transform: uppercase;
            letter-spacing: 1px;
            transition: border-color .15s;
        }
        .modal-input:focus { border-color: var(--accent); }
        .modal-btns { display: flex; gap: 10px; margin-top: 16px; }
        .modal-btn {
            flex: 1;
            padding: 12px;
            border-radius: 10px;
            border: 1px solid var(--border);
            background: transparent;
            color: var(--text);
            font-size: var(--fs-sm);
            font-weight: 600;
            cursor: pointer;
            font-family: inherit;
            transition: all .15s;
        }
        .modal-btn.primary { background: var(--accent); border-color: var(--accent); color: #000; }
        .modal-btn:hover:not(.primary) { background: var(--border); }

        /* Toast notification */
        #toast {
            position: fixed;
            bottom: 24px;
            left: 50%;
            transform: translateX(-50%) translateY(80px);
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 12px 20px;
            font-size: var(--fs-sm);
            font-weight: 600;
            z-index: 99999;
            transition: transform .25s ease;
            pointer-events: none;
            white-space: nowrap;
        }
        #toast.show { transform: translateX(-50%) translateY(0); }
        #toast.success { border-color: var(--green); color: var(--green); }
        #toast.error { border-color: var(--blue); color: var(--blue); }

        /* =============================================
           STRUK / RECEIPT (print only)
        ============================================= */
        /* ── Payment Modal ── */
        .pm-option {
            display: flex;
            align-items: center;
            gap: 14px;
            width: 100%;
            padding: 16px;
            background: var(--surface2);
            border: 1.5px solid var(--border);
            border-radius: 16px;
            color: var(--text);
            font-family: inherit;
            cursor: pointer;
            transition: all .25s cubic-bezier(0.4,0,0.2,1);
            text-align: left;
            position: relative;
            overflow: hidden;
        }
        .pm-option:hover {
            border-color: var(--accent);
            background: linear-gradient(135deg, rgba(245,158,11,.06), rgba(245,158,11,.02));
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,.1);
        }
        .pm-option.selected {
            border-color: var(--accent);
            background: linear-gradient(135deg, rgba(245,158,11,.1), rgba(245,158,11,.04));
            box-shadow: 0 0 0 2px rgba(245,158,11,.18);
        }
        .pm-icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            flex-shrink: 0;
            background: var(--surface);
            color: var(--text-muted);
            transition: all .25s;
        }
        .pm-option.tunai .pm-icon   { color: #10b981; background: rgba(16,185,129,.12); }
        .pm-option.qris .pm-icon    { color: #6366f1; background: rgba(99,102,241,.12); }
        .pm-option.bank .pm-icon    { color: #f59e0b; background: rgba(245,158,11,.12); }
        .pm-option.tunai.selected .pm-icon   { background: #10b981; color: #fff; box-shadow: 0 4px 16px rgba(16,185,129,.35); }
        .pm-option.qris.selected .pm-icon    { background: #6366f1; color: #fff; box-shadow: 0 4px 16px rgba(99,102,241,.35); }
        .pm-option.bank.selected .pm-icon    { background: #f59e0b; color: #000; box-shadow: 0 4px 16px rgba(245,158,11,.35); }
        .pm-info { flex: 1; }
        .pm-name { font-size: var(--fs-sm); font-weight: 700; letter-spacing: -0.01em; }
        .pm-desc { font-size: var(--fs-xs); color: var(--text-muted); margin-top: 2px; }
        .pm-check {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            border: 2px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            transition: all .25s;
            font-size: 10px;
            color: transparent;
        }
        .pm-option.selected .pm-check {
            border-color: var(--accent);
            background: var(--accent);
            color: #000;
        }

        .quick-btn {
            padding: 6px 12px;
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 8px;
            color: var(--text);
            font-size: var(--fs-xs);
            font-weight: 700;
            cursor: pointer;
            transition: all .12s;
        }
        .quick-btn:hover { border-color: var(--accent); color: var(--accent); }

        #receipt-print { display: none; }

        @media print {
            body * { visibility: hidden !important; }
            #receipt-print, #receipt-print * { visibility: visible !important; }
            #receipt-print {
                display: block !important;
                position: fixed;
                top: 0; left: 0;
                width: 56mm;
                padding-bottom: 20mm;
            }
            @page { size: 58mm auto; margin: 0; }
        }

        .receipt { 
            width: 58mm;
            padding: 10px 10px 20mm 10px;
            font-size: 11.5px;
            line-height: 1.35;
            font-family: 'Courier New', monospace;
            background: white;
            color: black;
        }
        .receipt hr { border: none; border-top: 1px dashed #000; margin: 5px 0; }

        /* =============================================
           TABLET RESPONSIVE (768–1024px)
        ============================================= */
        @media (max-width: 1024px) {
            :root {
                --fs-xs:   0.68rem;
                --fs-sm:   0.78rem;
                --fs-base: 0.85rem;
                --fs-md:   0.95rem;
                --fs-lg:   1.1rem;
                --fs-xl:   1.3rem;
            }
            #header { height: 52px; padding: 0 14px; }
            #panel-bill { width: 300px; }
            #menu-grid { grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 10px; }
            .btn-action { padding: 8px 4px; font-size: 10px; gap: 3px; }
        }

        @media (max-width: 850px) {
            .header-brand span { display: none; }
            .nav-btn span { display: none; }
            #panel-bill { width: 270px; }
            .form-row { flex-direction: column; gap: 6px; }
        }

        /* Prevent any OS-level font boosting */
        * { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
    </style>
</head>
<body>

<div id="app">

    <!-- ══════════════════════════════════════
         HEADER
    ══════════════════════════════════════ -->
    <header id="header">
        <div class="header-brand">
            <div class="logo">🍣</div>
            <span>EnakinChiken Resto</span>
        </div>

        <div class="header-nav">
            <div class="kasir-badge"><i class="fas fa-user-circle"></i> <?= htmlspecialchars($kasir_name) ?></div>
            <a href="admin.php" class="nav-btn"><i class="fas fa-cogs"></i> <span>Kelola</span></a>
            <a href="transactions.php" class="nav-btn"><i class="fas fa-list"></i> <span>Riwayat</span></a>
            <a href="logout.php" class="nav-btn"><i class="fas fa-sign-out-alt"></i> <span>Keluar</span></a>
        </div>
    </header>

    <!-- ══════════════════════════════════════
         MAIN
    ══════════════════════════════════════ -->
    <div id="main">

        <!-- LEFT: Menu -->
        <section id="panel-menu">
            <div id="menu-toolbar">
                <button class="cat-btn active" data-cat="all" onclick="filterCat(this,'all')">Semua</button>
                <button class="cat-btn" data-cat="food" onclick="filterCat(this,'food')">🍽 Food</button>
                <button class="cat-btn" data-cat="drink" onclick="filterCat(this,'drink')">🥤 Drink</button>
                <input id="search-box" type="search" placeholder="Cari menu…" oninput="renderMenu()">
            </div>
            <div id="menu-scroll">
                <div id="menu-grid"></div>
            </div>
        </section>

        <div id="divider"></div>

        <!-- RIGHT: Bill -->
        <section id="panel-bill">

            <!-- Controls -->
            <div id="bill-controls">
                <select id="order-type" class="form-select" onchange="recalc()">
                    <option value="dinein">Dine In</option>
                    <option value="takeaway">Take Away (+<?= $fee_takeaway_rate ?>%)</option>
                    <option value="catering">Event / Catering (+<?= $fee_catering_rate ?>%)</option>
                    <?php if ($gojek_enabled): ?><option value="gojek">Gojek (<?= $fee_gojek_rate ?>%)</option><?php endif; ?>
                    <?php if ($grab_enabled): ?><option value="grab">Grab (<?= $fee_grab_rate ?>%)</option><?php endif; ?>
                    <?php if ($shopee_enabled): ?><option value="shopee">ShopeeFood (<?= $fee_shopee_rate ?>%)</option><?php endif; ?>
                </select>
                <div class="form-row">
                    <input id="customer-name" class="form-input" type="text" placeholder="Nama Customer / Event">
                    <input id="customer-phone" class="form-input" type="tel" placeholder="No. Telepon">
                </div>
            </div>

            <!-- Item List -->
            <div id="bill-scroll">
                <div id="bill-items">
                    <div id="bill-empty">
                        <div class="empty-icon">🛒</div>
                        <div>Pilih menu untuk memulai pesanan</div>
                    </div>
                </div>
            </div>

            <!-- Summary -->
            <div id="bill-summary">
                <div class="summary-row">
                    <span>Sub Total</span>
                    <span class="val" id="sum-subtotal">Rp 0</span>
                </div>
                <div class="summary-row discount">
                    <span>Diskon</span>
                    <span class="val" id="sum-discount">-Rp 0</span>
                </div>
                <div class="summary-row">
                    <span>Service Charge (Incl. Harga)</span>
                    <span class="val" id="sum-service">Rp 0</span>
                </div>
                <div class="summary-row">
                    <span>PPN / Pajak</span>
                    <span class="val" id="sum-ppn">Rp 0</span>
                </div>
                <div class="summary-row">
                    <span id="sum-fee-label">Take Away Fee</span>
                    <span class="val" id="sum-fee">Rp 0</span>
                </div>
                <hr class="summary-divider">
                <div class="summary-total">
                    <span>TOTAL</span>
                    <span class="total-val" id="sum-total">Rp 0</span>
                </div>
            </div>

            <!-- Actions -->
            <div id="bill-actions">
                <div class="action-row">
                    <button class="btn-action" onclick="doGlobalDiscount()" title="Diskon semua item">
                        💰 Diskon
                    </button>
                    <button class="btn-action" id="btn-voucher" onclick="openVoucher()" title="Kode voucher">
                        🎟 Voucher
                    </button>
                    <button class="btn-action" id="btn-print" disabled onclick="printReceipt()" title="Cetak struk">
                        🖨 Struk
                    </button>
                </div>
                <button class="btn-charge" id="btn-charge" onclick="doCharge()">
                    💳 CHARGE &nbsp;<span id="charge-label">Rp 0</span>
                </button>
            </div>
        </section>
    </div><!-- /main -->
</div><!-- /app -->

<!-- ══════════════════════════════════════
     VOUCHER MODAL
══════════════════════════════════════ -->
<div id="voucher-modal" class="modal-overlay">
    <div class="modal-box">
        <div class="modal-title">🎟 Kode Voucher</div>
        <input id="voucher-code" class="modal-input" type="text" placeholder="CONTOHKODE" maxlength="30">
        <div class="modal-btns">
            <button class="modal-btn" onclick="closeVoucher()">Batal</button>
            <button class="modal-btn primary" onclick="applyVoucher()">Terapkan</button>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════
     PAYMENT MODAL
══════════════════════════════════════ -->
<div id="payment-modal" class="modal-overlay">
    <div class="modal-box" style="width:360px;max-width:95vw;padding:0;overflow:hidden;border-radius:20px">
        <!-- Header -->
        <div style="background:var(--surface2);padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
            <div>
                <div style="font-weight:700;font-size:var(--fs-md)">💳 Pilih Pembayaran</div>
                <div style="font-size:var(--fs-xs);color:var(--text-muted)">Total: <strong id="pm-total" style="color:var(--accent)">Rp 0</strong></div>
            </div>
            <button onclick="closePaymentModal()" style="background:none;border:none;color:var(--text-muted);font-size:20px;cursor:pointer;line-height:1">×</button>
        </div>

        <!-- Loading -->
        <div id="pm-loading" style="display:flex;align-items:center;justify-content:center;padding:40px;gap:10px;color:var(--text-muted)">
            <i class="fas fa-spinner fa-spin"></i> Memuat…
        </div>

        <!-- Body -->
        <div id="pm-body" style="display:none">
            <!-- Options List -->
            <div id="pm-options" style="padding:12px;display:flex;flex-direction:column;gap:8px"></div>

            <!-- QRIS Panel -->
            <div id="pm-qris-panel" style="display:none;padding:20px;text-align:center">
                <div style="font-size:var(--fs-sm);color:var(--text-muted);margin-bottom:4px">Scan QR untuk bayar ke</div>
                <div id="qris-name" style="font-weight:700;font-size:var(--fs-md);margin-bottom:14px;color:var(--accent)"></div>
                <img id="qris-img" src="" style="display:none;width:200px;height:200px;object-fit:contain;border-radius:12px;margin:0 auto 12px;background:white;padding:8px">
                <div id="qris-placeholder" style="display:none;width:200px;height:200px;border:2px dashed var(--border);border-radius:12px;margin:0 auto 12px;align-items:center;justify-content:center;flex-direction:column;gap:8px;color:var(--text-muted)">
                    <i class="fas fa-qrcode" style="font-size:48px;opacity:.3"></i>
                    <div style="font-size:var(--fs-xs)">Gambar QR belum diupload</div>
                </div>
                <div style="font-size:var(--fs-xs);color:var(--text-muted)">Tunjukkan struk setelah scan berhasil</div>
            </div>

            <!-- Bank Panel -->
            <div id="pm-bank-panel" style="display:none;padding:20px">
                <div style="font-size:var(--fs-sm);color:var(--text-muted);margin-bottom:12px">Transfer ke rekening:</div>
                <div style="background:var(--surface2);border:1px solid var(--border);border-radius:14px;padding:16px">
                    <div style="font-size:var(--fs-xl);font-weight:800;color:var(--text);margin-bottom:4px" id="bank-name"></div>
                    <div style="font-family:'DM Mono',monospace;font-size:var(--fs-lg);color:var(--accent);letter-spacing:2px;margin-bottom:4px" id="bank-norek"></div>
                    <div style="font-size:var(--fs-xs);color:var(--text-muted)">a/n <span id="bank-atas-nama"></span></div>
                </div>
                <div style="margin-top:10px;font-size:var(--fs-xs);color:var(--text-muted);text-align:center">Konfirmasi setelah transfer berhasil</div>
            </div>

            <!-- Tunai Panel -->
            <div id="pm-tunai-panel" style="display:none;padding:20px">
                <div style="margin-bottom:14px">
                    <div style="font-size:var(--fs-xs);color:var(--text-muted);margin-bottom:2px">Total Tagihan</div>
                    <div id="tunai-total" style="font-size:var(--fs-xl);font-weight:800;color:var(--accent)">Rp 0</div>
                </div>
                <div style="margin-bottom:14px">
                    <label style="font-size:var(--fs-xs);color:var(--text-muted);display:block;margin-bottom:6px">Uang yang Diterima (Rp)</label>
                    <input id="tunai-bayar" type="number" min="0" step="1000" placeholder="Masukkan nominal..."
                        oninput="calcKembalian()"
                        style="width:100%;padding:12px 14px;background:var(--surface2);border:1px solid var(--border);border-radius:10px;color:var(--text);font-family:inherit;font-size:var(--fs-md);font-weight:700;outline:none;transition:border-color .15s"
                        onfocus="this.style.borderColor='var(--accent)'"
                        onblur="this.style.borderColor='var(--border)'">
                    <!-- Quick amount buttons -->
                    <div style="display:flex;gap:6px;margin-top:8px;flex-wrap:wrap" id="quick-amounts"></div>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;background:var(--surface2);border:1px solid var(--border);border-radius:10px;padding:12px 14px">
                    <span style="font-size:var(--fs-sm);color:var(--text-muted)">Kembalian</span>
                    <span id="tunai-kembalian" style="font-size:var(--fs-md);font-weight:800;color:var(--green)">—</span>
                </div>
            </div>

            <!-- Footer Buttons -->
            <div style="padding:12px 16px 16px;display:flex;gap:8px;border-top:1px solid var(--border)">
                <button id="pm-back-btn" onclick="backToPaymentOptions()"
                    style="display:none;align-items:center;gap:6px;padding:10px 16px;background:var(--surface2);border:1px solid var(--border);border-radius:10px;color:var(--text-muted);font-size:var(--fs-sm);font-weight:600;cursor:pointer">
                    ← Kembali
                </button>
                <button id="pm-confirm-btn" onclick="confirmPayment()"
                    style="display:none;flex:1;padding:12px;background:var(--green);border:none;border-radius:10px;color:white;font-weight:700;font-size:var(--fs-sm);cursor:pointer">
                    ✅ Konfirmasi
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════
     TOAST
══════════════════════════════════════ -->
<div id="toast"></div>

<!-- ══════════════════════════════════════
     RECEIPT (print only)
══════════════════════════════════════ -->
<div id="receipt-print">
    <div class="receipt">
        <div style="text-align:center">
            <div style="font-weight:bold;font-size:14px">EnakinChiken</div>
            <div style="font-size:10px">Alun-alun Pamulang</div>
            <div style="font-size:10px">Telp: 08988860770</div>
            <hr>
            <div style="font-size:10px">Invoice: <strong id="pr-invoice"></strong></div>
            <div style="font-size:10px">Tanggal: <span id="pr-date"></span></div>
            <div style="font-size:10px">Kasir: <?= htmlspecialchars($kasir_name) ?></div>
            <hr>
        </div>
        <div id="pr-items" style="font-size:11px"></div>
        <hr>
        <div style="font-size:11px">
            <div style="display:flex;justify-content:space-between"><span>Sub Total</span><span id="pr-subtotal"></span></div>
            <div style="display:flex;justify-content:space-between"><span>Diskon</span><span id="pr-discount"></span></div>
            <div style="display:flex;justify-content:space-between"><span>Service</span><span id="pr-service"></span></div>
            <div style="display:flex;justify-content:space-between"><span>PPN</span><span id="pr-ppn"></span></div>
            <div style="display:flex;justify-content:space-between"><span id="pr-fee-lbl"></span><span id="pr-fee"></span></div>
            <hr>
            <div style="display:flex;justify-content:space-between;font-weight:bold;font-size:13px"><span>TOTAL</span><span id="pr-total"></span></div>
        </div>
        <hr>
        <div style="text-align:center;font-size:10px;margin-top:6px">Terima Kasih!<br>Silakan Datang Kembali</div>
        <div style="text-align:center;margin-top:8px"><svg id="barcode"></svg></div>
    </div>
</div>

<!-- ══════════════════════════════════════
     JAVASCRIPT
══════════════════════════════════════ -->
<script>
'use strict';

/* ─── State ─── */
const RATE_TAKEAWAY = Number(<?= $fee_takeaway_rate ?>);
const RATE_CATERING = Number(<?= $fee_catering_rate ?>);
const RATE_SERVICE  = Number(<?= $fee_service_rate ?>);
const RATE_PPN      = Number(<?= $fee_ppn_rate ?>);
const RATE_GOJEK    = Number(<?= $fee_gojek_rate ?>);
const RATE_GRAB     = Number(<?= $fee_grab_rate ?>);
const RATE_SHOPEE   = Number(<?= $fee_shopee_rate ?>);

let allProducts     = [];
let cart            = [];       // [{id, name, price, qty, disc, isPercent, item_order_type}]
let currentCat      = 'all';
let voucherDiscount = 0;
let voucherCode     = '';
let lastTransaction = null;    // data transaksi terakhir buat print
let subtotalSaved   = 0, discTotalSaved = 0, feeSaved = 0, totalSaved = 0;
let feeLabelSaved   = '';
let currentInvoice  = null;
let isCharging      = false;    // debounce

/* ─── Formatting ─── */
const idr = n => 'Rp ' + Math.round(n).toLocaleString('id-ID');

/* ─── Toast ─── */
let toastTimer;
function toast(msg, type = 'success') {
    const el = document.getElementById('toast');
    el.textContent = msg;
    el.className = 'show ' + type;
    clearTimeout(toastTimer);
    toastTimer = setTimeout(() => { el.className = ''; }, 3000);
}

/* ─── Load Products ─── */
async function loadProducts() {
    try {
        const res = await fetch('get_products.php');
        if (!res.ok) throw new Error('HTTP ' + res.status);
        allProducts = await res.json();
        renderMenu();
    } catch(e) {
        console.error(e);
        toast('Gagal memuat menu', 'error');
    }
}

/* ─── Filter ─── */
function filterCat(btn, cat) {
    currentCat = cat;
    document.querySelectorAll('.cat-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    renderMenu();
}

/* ─── Render Menu ─── */
function renderMenu() {
    const q    = (document.getElementById('search-box').value || '').toLowerCase().trim();
    const grid = document.getElementById('menu-grid');

    const filtered = allProducts.filter(p => {
        const catOk = currentCat === 'all' || p.category === currentCat;
        const qOk   = !q || p.name.toLowerCase().includes(q);
        return catOk && qOk;
    });

    /* Gunakan fragment untuk DOM batch insert (performa) */
    const frag = document.createDocumentFragment();
    filtered.forEach(p => {
        const img = (p.img && p.img !== 'uploads/default.jpg')
            ? p.img
            : `https://picsum.photos/seed/${p.id}/300/200`;

        const card = document.createElement('div');
        card.className = 'menu-card';
        card.innerHTML =
            `<img src="${esc(img)}" alt="${esc(p.name)}" loading="lazy" onerror="this.src='https://picsum.photos/seed/${p.id}/300/200'">
             <div class="menu-card-body">
                 <div class="menu-card-name">${esc(p.name)}</div>
                 <div class="menu-card-price">${idr(p.price)}</div>
             </div>`;
        card.addEventListener('click', () => addToCart(p), { passive: true });
        frag.appendChild(card);
    });

    grid.innerHTML = '';
    if (filtered.length === 0) {
        grid.innerHTML = '<div style="color:var(--text-muted);font-size:var(--fs-sm);padding:20px;grid-column:1/-1">Tidak ada menu ditemukan.</div>';
    } else {
        grid.appendChild(frag);
    }
}

function esc(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

/* ─── Cart ─── */
function addToCart(p) {
    const idx = cart.findIndex(i => i.id === p.id);
    if (idx >= 0) {
        cart[idx].qty++;
    } else {
        const defType = document.getElementById('order-type').value || 'dinein';
        cart.push({ id: p.id, name: p.name, price: +p.price, qty: 1, disc: 0, isPercent: false, item_order_type: defType });
    }
    renderBill();
}

function changeQty(idx, delta) {
    cart[idx].qty += delta;
    if (cart[idx].qty < 1) cart.splice(idx, 1);
    renderBill();
}

function toggleOrderType(idx) {
    const types = ['dinein', 'takeaway', 'catering', 'gojek', 'grab', 'shopee'];
    const cur = cart[idx].item_order_type || 'dinein';
    const nextIdx = (types.indexOf(cur) + 1) % types.length;
    cart[idx].item_order_type = types[nextIdx];
    renderBill();
}

function removeItem(idx) {
    cart.splice(idx, 1);
    renderBill();
}

/* ─── Render Bill ─── */
function editPrice(idx) {
    const newPrice = prompt('Harga baru untuk item ini:', cart[idx].price);
    if (newPrice !== null && !isNaN(newPrice) && parseInt(newPrice) >= 0) {
        cart[idx].price = parseInt(newPrice);
        renderBill();
        showToast('Harga diupdate ke Rp ' + idr(cart[idx].price));
    }
}

function renderBill() {
    const container = document.getElementById('bill-items');
    const empty     = document.getElementById('bill-empty');

    if (cart.length === 0) {
        container.innerHTML = '';
        container.appendChild(empty);
        document.getElementById('btn-charge').disabled = true;
        recalc();
        return;
    }

    const frag = document.createDocumentFragment();
    cart.forEach((item, idx) => {
        let finalPrice = item.price;
        if (item.disc > 0) {
            finalPrice = item.isPercent
                ? item.price * (1 - item.disc / 100)
                : Math.max(0, item.price - item.disc);
        }
        const lineTotal = finalPrice * item.qty;

        const div = document.createElement('div');
        div.className = 'bill-item';
        div.innerHTML =
            `<div class="bill-item-top">
                <div class="bill-item-info">
                    <div class="bill-item-name">${esc(item.name)}
                        <span style="font-size:0.65rem;color:${(()=>{const t=(item.item_order_type||'dinein');if(t==='takeaway')return'#f59e0b';if(t==='catering')return'#6366f1';if(t==='gojek')return'#00AA13';if(t==='grab')return'#00B14F';if(t==='shopee')return'#EE4D2D';return'#10b981'})()};margin-left:4px;font-weight:600;">${(()=>{const t=(item.item_order_type||'dinein');if(t==='takeaway')return'[Bungkus]';if(t==='catering')return'[Catering]';if(t==='gojek')return'[Gojek]';if(t==='grab')return'[Grab]';if(t==='shopee')return'[Shopee]';return'[Dine In]'})()}</span>
                    </div>
                    <div class="bill-item-price-base">${idr(item.price)}
                        <button onclick="editPrice(${idx})" style="background:none;border:none;color:var(--text-muted);cursor:pointer;font-size:0.65rem;padding:0 2px;" title="Edit harga">&#9998;</button>
                        ${item.disc > 0 ? `<span class="discount-badge">[${item.isPercent ? item.disc+'%' : idr(item.disc)}]</span>` : ''}
                        <button onclick="toggleOrderType(${idx})" style="background:${(()=>{const t=(item.item_order_type||'dinein');if(t==='takeaway')return'#f59e0b';if(t==='catering')return'#6366f1';if(t==='gojek')return'#00AA13';if(t==='grab')return'#00B14F';if(t==='shopee')return'#EE4D2D';return'#10b981'})()};color:#fff;border:none;border-radius:4px;padding:1px 5px;font-size:0.6rem;cursor:pointer;margin-left:4px;" title="Ganti tipe">&#8644;</button>
                    </div>
                </div>
                <button class="btn-remove" onclick="removeItem(${idx})" title="Hapus">&#10005;</button>
            </div>
            <div class="bill-item-bottom">
                <div class="qty-ctrl">
                    <button class="qty-btn" onclick="changeQty(${idx},-1)">-</button>
                    <span class="qty-val">${item.qty}</span>
                    <button class="qty-btn" onclick="changeQty(${idx},1)">+</button>
                </div>
                <span class="bill-item-line">${idr(lineTotal)}</span>
            </div>`;
        frag.appendChild(div);
    });

    container.innerHTML = '';
    container.appendChild(frag);
    document.getElementById('btn-charge').disabled = false;
    recalc();
}

/* ─── Recalculate Summary ─── */
function recalc() {
    let subtotal = 0, discTotal = 0;
    cart.forEach(item => {
        let finalPrice = item.price;
        if (item.disc > 0) {
            finalPrice = item.isPercent
                ? item.price * (1 - item.disc / 100)
                : Math.max(0, item.price - item.disc);
        }
        subtotal  += item.price * item.qty;
        discTotal += (item.price - finalPrice) * item.qty;
    });

    const service   = Math.round((subtotal - discTotal - voucherDiscount) * RATE_SERVICE / 100);
    // Hitung fee per item berdasarkan item_order_type
    let feeTakeaway = 0, feeCatering = 0;
    cart.forEach(item => {
        const otype = item.item_order_type || 'dinein';
        if (otype === 'takeaway') feeTakeaway += item.price * item.qty;
        if (otype === 'catering') feeCatering += item.price * item.qty;
    });
    feeTakeaway = Math.round(feeTakeaway * RATE_TAKEAWAY / 100);
    feeCatering = Math.round(feeCatering * RATE_CATERING / 100);
    let fee = feeTakeaway + feeCatering;
    let feeLabel = '';
    if (feeTakeaway > 0 && feeCatering > 0) feeLabel = "Takeaway(" + RATE_TAKEAWAY + "%) + Catering(" + RATE_CATERING + "%)";
    else if (feeTakeaway > 0) feeLabel = "Take Away Fee (" + RATE_TAKEAWAY + "%)";
    else if (feeCatering > 0) feeLabel = "Catering Fee (" + RATE_CATERING + "%)";

    const ppn        = Math.round((subtotal - discTotal - voucherDiscount + service + fee) * RATE_PPN / 100);
    const grandTotal = subtotal - discTotal - voucherDiscount + service + fee + ppn;

    document.getElementById('sum-subtotal').textContent  = idr(subtotal);
    document.getElementById('sum-discount').textContent  = '−' + idr(discTotal + voucherDiscount);
    document.getElementById('sum-service').textContent   = idr(service);
    document.getElementById('sum-ppn').textContent       = idr(ppn);
    document.getElementById('sum-fee-label').textContent = feeLabel || 'Fee';
    document.getElementById('sum-fee').textContent       = idr(fee);
    document.getElementById('sum-total').textContent     = idr(Math.max(0, grandTotal));
    document.getElementById('charge-label').textContent  = idr(Math.max(0, grandTotal));
}

/* ─── Global Discount ─── */
function doGlobalDiscount() {
    if (cart.length === 0) { toast('Keranjang masih kosong', 'error'); return; }
    const input = prompt('Diskon untuk SEMUA item:\n• Angka < 100 = persen (mis: 10 = 10%)\n• Angka ≥ 100 = nominal Rp (mis: 5000)', '10');
    if (input === null) return;
    const val = parseFloat(input);
    if (isNaN(val) || val < 0) { toast('Nilai tidak valid', 'error'); return; }
    const isPercent = val < 100;
    cart.forEach(i => { i.disc = val; i.isPercent = isPercent; });
    renderBill();
    toast(`Diskon ${isPercent ? val+'%' : idr(val)} diterapkan`);
}

/* ─── Voucher ─── */
function openVoucher() {
    document.getElementById('voucher-modal').classList.add('open');
    setTimeout(() => document.getElementById('voucher-code').focus(), 100);
}
function closeVoucher() {
    document.getElementById('voucher-modal').classList.remove('open');
}
async function applyVoucher() {
    const code = document.getElementById('voucher-code').value.trim().toUpperCase();
    if (!code) { toast('Masukkan kode voucher', 'error'); return; }

    let subtotal = 0;
    cart.forEach(i => { subtotal += i.price * i.qty; });

    const fd = new FormData();
    fd.append('code', code);
    fd.append('subtotal', subtotal);

    try {
        const res    = await fetch('check_voucher.php', { method: 'POST', body: fd });
        const result = await res.json();
        if (result.success) {
            voucherDiscount = result.discount_amount;
            voucherCode     = result.code;
            const btn = document.getElementById('btn-voucher');
            btn.textContent = '✅ ' + result.code;
            btn.classList.add('active-voucher');
            closeVoucher();
            recalc();
            toast(result.message);
        } else {
            toast(result.message, 'error');
        }
    } catch(e) {
        toast('Gagal konek ke server', 'error');
    }
}

/* ─── Payment Modal ─── */
let paymentMethods = null;
let selectedPayment = null; // {type:'tunai'|'qris'|'bank', bank?: {...}}

async function doCharge() {
    if (cart.length === 0 || isCharging) return;
    // Buka modal pembayaran
    await openPaymentModal();
}

async function openPaymentModal() {
    const modal = document.getElementById('payment-modal');
    modal.classList.add('open');

    // Load metode sekali saja
    if (!paymentMethods) {
        document.getElementById('pm-loading').style.display = 'flex';
        document.getElementById('pm-body').style.display = 'none';
        try {
            const res = await fetch('get_payment_methods.php');
            paymentMethods = await res.json();
        } catch(e) {
            paymentMethods = { tunai:{enabled:true}, qris:{enabled:false,image:null}, banks:[] };
        }
    }

    renderPaymentModal();
}

function renderPaymentModal() {
    const loading = document.getElementById('pm-loading');
    const body    = document.getElementById('pm-body');
    loading.style.display = 'none';
    body.style.display    = 'block';

    const totalEl = document.getElementById('sum-total').textContent;
    document.getElementById('pm-total').textContent = totalEl;

    const pm = paymentMethods;
    let html = '';

    // TUNAI
    if (pm.tunai?.enabled !== false) {
        html += `<button class="pm-option tunai" onclick="selectPayment('tunai')">
            <span class="pm-icon"><i class="fas fa-money-bill-wave"></i></span>
            <div class="pm-info"><div class="pm-name">Tunai</div><div class="pm-desc">Bayar dengan uang cash</div></div>
            <span class="pm-check"><i class="fas fa-check"></i></span>
        </button>`;
    }

    // QRIS
    if (pm.qris?.enabled) {
        html += `<button class="pm-option qris" onclick="selectPayment('qris')">
            <span class="pm-icon"><i class="fas fa-qrcode"></i></span>
            <div class="pm-info"><div class="pm-name">QRIS</div><div class="pm-desc">Scan QR Code</div></div>
            <span class="pm-check"><i class="fas fa-check"></i></span>
        </button>`;
    }

    // BANK
    if (pm.banks && pm.banks.length > 0) {
        pm.banks.forEach(b => {
            html += `<button class="pm-option bank" onclick='selectPayment("bank", ${JSON.stringify(b)})'>
                <span class="pm-icon"><i class="fas fa-building-columns"></i></span>
                <div class="pm-info"><div class="pm-name">${esc(b.bank_name)}</div><div class="pm-desc">a/n ${esc(b.account_name)} • ${esc(b.account_number)}</div></div>
                <span class="pm-check"><i class="fas fa-check"></i></span>
            </button>`;
        });
    }

    if (!html) {
        html = '<div style="text-align:center;color:var(--text-muted);padding:30px">Tidak ada metode pembayaran aktif.<br>Atur di Admin Panel.</div>';
    }

    document.getElementById('pm-options').innerHTML = html;
    // Highlight yg udah dipilih sebelumnya (kalau balik dari panel detail)
    if (selectedPayment) {
        let selClass = selectedPayment.type === 'bank' ? 'bank' : selectedPayment.type;
        const selBtn = document.querySelector('.pm-option.' + selClass);
        if (selBtn) selBtn.classList.add('selected');
    }

    // Sembunyikan sub-panel
    document.getElementById('pm-qris-panel').style.display    = 'none';
    document.getElementById('pm-bank-panel').style.display    = 'none';
    document.getElementById('pm-tunai-panel').style.display   = 'none';
    document.getElementById('pm-options').style.display       = 'block';
    document.getElementById('pm-back-btn').style.display      = 'none';
    document.getElementById('pm-confirm-btn').style.display   = 'none';
}

function selectPayment(type, bank) {
    selectedPayment = { type, bank: bank || null };
    const opts = document.getElementById('pm-options');
    const back = document.getElementById('pm-back-btn');
    const confirm = document.getElementById('pm-confirm-btn');

    opts.style.display = 'none';
    back.style.display = 'inline-flex';

    if (type === 'qris') {
        const panel = document.getElementById('pm-qris-panel');
        const pm    = paymentMethods;
        const name  = pm.qris?.merchant_name || 'GoldenWok Resto';
        const img   = pm.qris?.image;
        panel.querySelector('#qris-name').textContent = name;
        if (img) {
            panel.querySelector('#qris-img').src = img;
            panel.querySelector('#qris-img').style.display = 'block';
            panel.querySelector('#qris-placeholder').style.display = 'none';
        } else {
            panel.querySelector('#qris-img').style.display = 'none';
            panel.querySelector('#qris-placeholder').style.display = 'flex';
        }
        panel.style.display = 'block';
        confirm.style.display = 'inline-flex';
        confirm.textContent = '✅ Sudah Dibayar';

    } else if (type === 'bank') {
        const panel = document.getElementById('pm-bank-panel');
        panel.querySelector('#bank-name').textContent   = bank.bank_name;
        panel.querySelector('#bank-norek').textContent  = bank.account_number;
        panel.querySelector('#bank-atas-nama').textContent = bank.account_name;
        panel.style.display = 'block';
        confirm.style.display = 'inline-flex';
        confirm.textContent = '✅ Sudah Transfer';

    } else if (type === 'tunai') {
        const totalEl = document.getElementById('sum-total').textContent;
        const total   = parseInt(totalEl.replace(/[^0-9]/g, ''));
        document.getElementById('tunai-total').textContent = idr(total);
        document.getElementById('tunai-bayar').value = '';
        document.getElementById('tunai-kembalian').textContent = '—';
        const panel = document.getElementById('pm-tunai-panel');
        panel.style.display = 'block';
        confirm.style.display = 'inline-flex';
        confirm.textContent = '✅ Konfirmasi Bayar';
        setTimeout(() => document.getElementById('tunai-bayar').focus(), 100);
    }
}

function calcKembalian() {
    const totalEl = document.getElementById('sum-total').textContent;
    const total   = parseInt(totalEl.replace(/[^0-9]/g, ''));
    const bayar   = parseInt(document.getElementById('tunai-bayar').value) || 0;
    const kemb    = bayar - total;
    const el      = document.getElementById('tunai-kembalian');
    if (bayar >= total) {
        el.textContent = idr(kemb);
        el.style.color = 'var(--green)';
    } else if (bayar === 0) {
        el.textContent = '—';
        el.style.color = 'var(--text-muted)';
    } else {
        el.textContent = 'Kurang ' + idr(total - bayar);
        el.style.color = 'var(--red)';
    }
}

function backToPaymentOptions() {
    selectedPayment = null;
    document.getElementById('pm-qris-panel').style.display  = 'none';
    document.getElementById('pm-bank-panel').style.display  = 'none';
    document.getElementById('pm-tunai-panel').style.display = 'none';
    document.getElementById('pm-options').style.display     = 'block';
    document.getElementById('pm-back-btn').style.display    = 'none';
    document.getElementById('pm-confirm-btn').style.display = 'none';
}

function closePaymentModal() {
    document.getElementById('payment-modal').classList.remove('open');
    selectedPayment = null;
}

async function confirmPayment() {
    if (!selectedPayment) return;
    if (selectedPayment.type === 'tunai') {
        const totalEl = document.getElementById('sum-total').textContent;
        const total   = parseInt(totalEl.replace(/[^0-9]/g, ''));
        const bayar   = parseInt(document.getElementById('tunai-bayar').value) || 0;
        if (bayar < total) {
            toast('Uang bayar kurang dari total!', 'error');
            document.getElementById('tunai-bayar').focus();
            return;
        }
    }
    closePaymentModal();
    await processTransaction();
}

async function processTransaction() {
    if (isCharging) return;

    const totalEl  = document.getElementById('sum-total').textContent;
    const total    = parseInt(totalEl.replace(/[^0-9]/g, ''));
    const customer = document.getElementById('customer-name').value.trim() || 'Umum';
    const phone    = document.getElementById('customer-phone').value.trim();
    const orderType = document.getElementById('order-type').value;

    // Simpan totals buat lastTransaction
    subtotalSaved   = parseInt((document.getElementById('sum-subtotal').textContent || '0').replace(/[^0-9]/g, ''));
    discTotalSaved  = parseInt((document.getElementById('sum-discount').textContent || '0').replace(/[^0-9-]/g, ''));
    feeSaved        = parseInt((document.getElementById('sum-fee').textContent || '0').replace(/[^0-9]/g, ''));
    feeLabelSaved   = document.getElementById('sum-fee-label').textContent || '';
    totalSaved      = total;

    isCharging = true;
    const btn  = document.getElementById('btn-charge');
    btn.disabled  = true;
    btn.innerHTML = '⏳ Memproses…';

    const fd = new FormData();
    fd.append('cart',             JSON.stringify(cart));
    fd.append('total',            total);
    fd.append('customer',         customer);
    fd.append('phone',            phone);
    fd.append('order_type',       orderType);
    fd.append('voucher_discount', voucherDiscount);
    fd.append('voucher_code',     voucherCode);
    fd.append('payment_method',   selectedPayment?.type || 'tunai');

    try {
        const res  = await fetch('save_transaction.php', { method: 'POST', body: fd });
        const rawText = await res.text();
        let data;
        try { data = JSON.parse(rawText); }
        catch(parseErr) { console.error("Raw response:", rawText); throw new Error("Response bukan JSON: " + rawText.substring(0,100)); }

        if (data.success) {
            currentInvoice = data.invoice;
            toast(`✅ Transaksi OK · Invoice: ${data.invoice}`);

            const printBtn = document.getElementById('btn-print');
            printBtn.disabled = false;
            printBtn.classList.add('active-print');

            cart            = [];
            voucherDiscount = 0;
            voucherCode     = '';
            selectedPayment = null;
            document.getElementById('btn-voucher').textContent = '🎟 Voucher';
            document.getElementById('btn-voucher').classList.remove('active-voucher');
            renderBill();
        } else {
            toast('Gagal: ' + (data.message || 'Unknown error'), 'error');
        }
    } catch(e) {
        console.error(e);
        toast('Transaksi Berhasil', 'error');
    } finally {
        isCharging    = false;
        btn.disabled  = cart.length === 0;
        btn.innerHTML = '💳 CHARGE &nbsp;<span id="charge-label">' + document.getElementById('sum-total').textContent + '</span>';
    }
}

/* ─── Print Receipt ─── */
function printReceipt() {
    if (!currentInvoice) { toast('Lakukan pembayaran dulu', 'error'); return; }

    let itemsHTML = '', subtotal = 0, discTotal = 0;
    cart.forEach(item => {
        let fp = item.price;
        if (item.disc > 0) fp = item.isPercent ? item.price*(1-item.disc/100) : Math.max(0,item.price-item.disc);
        const lt = fp * item.qty;
        subtotal  += item.price * item.qty;
        discTotal += (item.price - fp) * item.qty;
        itemsHTML += `<div style="display:flex;justify-content:space-between"><span>${item.qty}x ${item.name}</span><span>${idr(lt)}</span></div>`;
    });

    const service   = 0;
    const orderType = document.getElementById('order-type').value;
    let fee = 0, feeLabel = '-';
    let feeTakeaway2 = 0, feeCatering2 = 0;
    cart.forEach(item => {
        const otype2 = item.item_order_type || 'dinein';
        if (otype2 === 'takeaway') feeTakeaway2 += item.price * item.qty;
        if (otype2 === 'catering') feeCatering2 += item.price * item.qty;
    });
    feeTakeaway2 = Math.round(feeTakeaway2 * RATE_TAKEAWAY / 100);
    feeCatering2 = Math.round(feeCatering2 * RATE_CATERING / 100);
    fee = feeTakeaway2 + feeCatering2;
    if (feeTakeaway2 > 0 && feeCatering2 > 0) feeLabel = "Takeaway(" + RATE_TAKEAWAY + "%) + Catering(" + RATE_CATERING + "%)";
    else if (feeTakeaway2 > 0) feeLabel = 'Take Away (' + RATE_TAKEAWAY + '%)';
    else if (feeCatering2 > 0) feeLabel = "Catering (" + RATE_CATERING + "%)";
    if (orderType === 'catering') { fee = Math.round(subtotal * RATE_CATERING / 100); feeLabel = "Catering (" + RATE_CATERING + "%)"; }
    const ppn2  = Math.round((subtotal - discTotal - voucherDiscount + service + fee) * RATE_PPN / 100);
    const grand = subtotal - discTotal - voucherDiscount + service + fee + ppn2;

    document.getElementById('pr-invoice').textContent  = currentInvoice;
    document.getElementById('pr-date').textContent     = new Date().toLocaleString('id-ID');
    document.getElementById('pr-items').innerHTML      = itemsHTML;
    document.getElementById('pr-subtotal').textContent = idr(subtotal);
    document.getElementById('pr-discount').textContent = '−' + idr(discTotal + voucherDiscount);
    document.getElementById('pr-service').textContent  = idr(service);
        document.getElementById('pr-ppn').textContent      = idr(ppn2);
    document.getElementById('pr-fee-lbl').textContent  = feeLabel;
    document.getElementById('pr-fee').textContent      = idr(fee);
    document.getElementById('pr-total').textContent    = idr(Math.max(0, grand));

    JsBarcode('#barcode', currentInvoice, {
        format: 'CODE128', lineColor: '#000', width: 1.6, height: 38,
        displayValue: true, fontSize: 11
    });

    setTimeout(() => window.print(), 2000);
}

/* ─── Init ─── */
document.addEventListener('DOMContentLoaded', () => {
    loadProducts();

    /* Payment modal: tutup saat klik overlay */
    document.getElementById('payment-modal').addEventListener('click', function(e) {
        if (e.target === this) closePaymentModal();
    });

    /* Quick amount buttons — dibuat saat total berubah */
    document.getElementById('payment-modal').addEventListener('click', function() {
        const totalEl = document.getElementById('sum-total').textContent;
        const total   = parseInt(totalEl.replace(/[^0-9]/g, '')) || 0;
        const rounds  = [total, Math.ceil(total/10000)*10000, Math.ceil(total/50000)*50000, Math.ceil(total/100000)*100000];
        const uniq    = [...new Set(rounds)].filter(v => v >= total).slice(0,4);
        const cont    = document.getElementById('quick-amounts');
        if (cont) {
            cont.innerHTML = uniq.map(v =>
                `<button class="quick-btn" onclick="document.getElementById('tunai-bayar').value=${v};calcKembalian()">${idr(v)}</button>`
            ).join('');
        }
    });

    /* Voucher modal: tutup saat klik overlay */
    document.getElementById('voucher-modal').addEventListener('click', function(e) {
        if (e.target === this) closeVoucher();
    });

    /* Enter di voucher input */
    document.getElementById('voucher-code').addEventListener('keydown', e => {
        if (e.key === 'Enter') applyVoucher();
    });
});
</script>

</body>
</html>