<?php
    include 'config.php';

    // ====== ENDPOINT AJAX/API (harus dicek duluan, berdiri sendiri tanpa perlu konteks pesanan penuh) ======

    // hapus item dari keranjang
    if (isset($_GET["delete"])) {
        header('Content-Type: application/json');
        $id_delete = (int)$_GET["delete"];
        mysqli_query($conn, "DELETE FROM produk_temp WHERE temp_id = '$id_delete'");
        echo json_encode(["ok" => true]);
        exit();
    }

    // tambah produk ke keranjang (dipanggil via fetch AJAX dari grid produk)
    if (isset($_POST["tujuan"]) && $_POST["tujuan"] == 'ADD_ITEM') {
        header('Content-Type: application/json');
        $produk_id = (int)$_POST["produk_id"];
        $counter_ajax = $_POST["counter"];

        $cek = mysqli_query($conn, "SELECT * FROM produk_temp WHERE temp_master='$counter_ajax' AND temp_produk='$produk_id'");
        if (mysqli_num_rows($cek) > 0) {
            mysqli_query($conn, "UPDATE produk_temp SET temp_jumlah = temp_jumlah + 1 WHERE temp_master='$counter_ajax' AND temp_produk='$produk_id'");
        } else {
            $harga_row = mysqli_fetch_array(mysqli_query($conn, "SELECT produk_harga FROM produk WHERE produk_id='$produk_id'"));
            $harga = $harga_row ? $harga_row['produk_harga'] : 0;
            mysqli_query($conn, "INSERT INTO produk_temp (temp_master, temp_produk, temp_jumlah, temp_harga) VALUES ('$counter_ajax','$produk_id','1','$harga')");
        }
        echo json_encode(["ok" => true]);
        exit();
    }

    // ubah quantity item di keranjang (+/-)
    if (isset($_POST["tujuan"]) && $_POST["tujuan"] == 'SET_QTY') {
        header('Content-Type: application/json');
        $temp_id = (int)$_POST["temp_id"];
        $qty = (int)$_POST["qty"];
        if ($qty < 1) $qty = 1;
        mysqli_query($conn, "UPDATE produk_temp SET temp_jumlah = '$qty' WHERE temp_id = '$temp_id'");
        echo json_encode(["ok" => true]);
        exit();
    }

    // ambil daftar produk aktif per kategori (dipanggil via fetch AJAX)
    if (isset($_GET["ajax"]) && $_GET["ajax"] == 'produk_by_jenis') {
        header('Content-Type: application/json');
        $jenis_id = (int)$_GET["jenis_id"];
        $result = mysqli_query($conn, "SELECT produk_id, produk_nama, produk_harga FROM produk 
                                        WHERE produk_jenis = '$jenis_id' AND produk_aktif = 'Aktif' 
                                        AND produk_nama != '' AND produk_nama IS NOT NULL AND produk_harga > 0 
                                        ORDER BY produk_nama");
        $list = [];
        while ($row = mysqli_fetch_array($result)) {
            $list[] = [
                "id" => $row["produk_id"],
                "nama" => $row["produk_nama"],
                "harga" => (float)$row["produk_harga"]
            ];
        }
        echo json_encode($list);
        exit();
    }

    // ====== RENDER HALAMAN PENUH (butuh konteks data pemesan) ======

    if (isset($_POST["tujuan"]) && $_POST["tujuan"] == 'USER_ADD') {
        $tanggal = $_POST["tanggal"];
        $nama    = $_POST["nama"];
        $alamat  = isset($_POST["alamat"]) ? $_POST["alamat"] : '';
        $nowa    = isset($_POST["nowa"]) ? $_POST["nowa"] : '';
        $note    = isset($_POST["note"]) ? $_POST["note"] : '';

        if (empty($tanggal) || empty($nama)) {
            header("Location: order.php?status=kosong");
            exit();
        }

        // ambil & increment counter -> nomor pesanan baru
        $query_sql = "SELECT * FROM counter";
        $result = mysqli_query($conn, $query_sql);
        if (mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_array($result);
            $counter = $row['counter'] + 1;
            mysqli_query($conn, "UPDATE counter SET counter = $counter");
        } else {
            $counter = 1;
            mysqli_query($conn, "INSERT INTO counter (counter) VALUES (1)");
        }
    } elseif (isset($_GET["counter"])) {
        // kembali ke halaman ini setelah nambah/hapus produk
        $counter = $_GET["counter"];
        $tanggal = $_GET["tanggal"];
        $nama    = $_GET["nama"];
        $alamat  = isset($_GET["alamat"]) ? $_GET["alamat"] : '';
        $nowa    = isset($_GET["nowa"]) ? $_GET["nowa"] : '';
        $note    = isset($_GET["note"]) ? $_GET["note"] : '';
    } else {
        header("Location: order.php");
        exit();
    }
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Pesanan - IniSpikoe</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 0.75rem;
            padding-bottom: 2rem;
        }

        .header { text-align: center; color: white; margin-bottom: 1rem; padding: 0.5rem 0; }
        .header h2 { font-size: clamp(1.2rem, 4vw, 1.6rem); text-shadow: 2px 2px 4px rgba(0,0,0,0.3); }

        .back-btn {
            position: fixed; top: 0.75rem; left: 0.75rem;
            background: rgba(255,255,255,0.25); backdrop-filter: blur(10px);
            border: none; color: white; width: 42px; height: 42px;
            border-radius: 50%; cursor: pointer; font-size: 1.2rem; z-index: 1000;
        }

        .card {
            background: white; border-radius: 15px; padding: 1rem;
            margin-bottom: 1rem; box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .ticket-header {
            background: linear-gradient(135deg, #04AA6D, #45a049);
            color: white; padding: 1rem; border-radius: 12px; text-align: center; margin-bottom: 1rem;
        }
        .ticket-header .order-number { font-size: 1.6rem; font-weight: bold; }
        .ticket-info { font-size: 0.85rem; color: #555; }
        .ticket-info b { color: #222; }

        .section-title { font-size: 1.1rem; margin-bottom: 0.8rem; color: #333; }

        /* Grid kategori: tombol besar, mudah ditekan jempol */
        .category-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 0.6rem;
        }
        .category-btn {
            background: #f8f9fa;
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 1rem 0.5rem;
            font-size: 1rem;
            font-weight: 600;
            color: #333;
            cursor: pointer;
            transition: all 0.15s ease;
            min-height: 64px;
        }
        .category-btn:active { transform: scale(0.96); background: #e8f5e8; border-color: #04AA6D; }

        /* Grid produk dalam kategori terpilih */
        .product-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 0.6rem;
        }
        .product-btn {
            background: #f8f9fa;
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 0.8rem 0.6rem;
            text-align: left;
            cursor: pointer;
            transition: all 0.15s ease;
        }
        .product-btn:active { transform: scale(0.96); background: #e8f5e8; border-color: #04AA6D; }
        .product-btn .p-nama { font-weight: 600; font-size: 0.9rem; color: #333; margin-bottom: 0.3rem; }
        .product-btn .p-harga { color: #04AA6D; font-weight: 600; font-size: 0.85rem; }

        .kategori-back-row {
            display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0.8rem;
        }
        .kategori-back-btn {
            background: #eee; border: none; border-radius: 8px;
            padding: 0.6rem 1rem; font-size: 0.9rem; cursor: pointer; font-weight: 600;
        }
        .kategori-nama-aktif { font-weight: 700; color: #333; font-size: 1.05rem; }

        .loading-text { text-align: center; padding: 1.5rem; color: #888; }

        /* Keranjang */
        .cart-item {
            display: flex; justify-content: space-between; align-items: center;
            padding: 0.7rem 0; border-bottom: 1px solid #eee; gap: 0.5rem;
        }
        .cart-item:last-child { border-bottom: none; }
        .cart-item .c-nama { font-weight: 600; font-size: 0.9rem; color: #333; flex: 1; }
        .cart-item .c-harga { font-size: 0.8rem; color: #04AA6D; }
        .qty-control { display: flex; align-items: center; gap: 0.3rem; background: #f8f9fa; border-radius: 8px; padding: 0.2rem; }
        .qty-control button {
            background: #04AA6D; color: white; border: none; width: 30px; height: 30px;
            border-radius: 6px; font-size: 1rem; cursor: pointer;
        }
        .qty-control input {
            width: 40px; text-align: center; border: none; background: transparent; font-weight: 600; font-size: 1rem;
        }
        .delete-btn {
            background: none; border: none; color: #e74c3c; font-size: 1.1rem; cursor: pointer; padding: 0.3rem;
        }
        .empty-cart { text-align: center; padding: 1.5rem; color: #888; }

        .discount-row { display: flex; gap: 0.6rem; margin-top: 1rem; }
        .discount-group { flex: 1; }
        .discount-group label { font-size: 0.8rem; color: #666; display: block; margin-bottom: 0.3rem; }
        .discount-group input {
            width: 100%; padding: 0.6rem; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 0.95rem;
        }
        .total-box {
            text-align: center; margin-top: 1rem; padding: 0.9rem; background: #f8f9fa; border-radius: 10px;
            font-size: 1.15rem; font-weight: 700; color: #04AA6D;
        }
        .submit-btn {
            width: 100%; background: linear-gradient(135deg, #04AA6D, #45a049); color: white;
            border: none; padding: 1rem; font-size: 1.05rem; font-weight: 600; border-radius: 12px;
            cursor: pointer; margin-top: 1rem;
        }
        .toast {
            position: fixed; bottom: 1rem; left: 50%; transform: translateX(-50%);
            background: #04AA6D; color: white; padding: 0.7rem 1.2rem; border-radius: 30px;
            font-size: 0.9rem; box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            opacity: 0; pointer-events: none; transition: opacity 0.25s ease; z-index: 2000;
        }
        .toast.show { opacity: 1; }
    </style>
</head>
<body>
    <button class="back-btn" onclick="history.back()" title="Kembali">←</button>

    <div class="header"><h2>🍞 Input Pesanan</h2></div>

    <div class="ticket-header">
        <div style="font-size:0.85rem;">No. Pesanan</div>
        <div class="order-number">#<?php echo htmlspecialchars($counter); ?></div>
    </div>

    <div class="card ticket-info">
        <div><b>Nama:</b> <?php echo htmlspecialchars($nama); ?></div>
        <?php if(!empty($alamat)) { ?><div><b>Alamat:</b> <?php echo htmlspecialchars($alamat); ?></div><?php } ?>
        <?php if(!empty($nowa)) { ?><div><b>WA:</b> <?php echo htmlspecialchars($nowa); ?></div><?php } ?>
        <div><b>Tanggal:</b> <?php echo htmlspecialchars(date('d/m/Y H:i', strtotime($tanggal))); ?></div>
    </div>

    <!-- Kategori & Produk -->
    <div class="card">
        <div id="kategoriView">
            <div class="section-title">Pilih Kategori</div>
            <div class="category-grid">
                <?php
                $result_jenis = mysqli_query($conn, "SELECT * FROM jenis ORDER BY jenis_nama");
                while ($j = mysqli_fetch_array($result_jenis)) {
                ?>
                <button class="category-btn" onclick="showProduk(<?php echo $j['jenis_id']; ?>, '<?php echo htmlspecialchars(addslashes($j['jenis_nama'])); ?>')">
                    <?php echo htmlspecialchars($j['jenis_nama']); ?>
                </button>
                <?php } ?>
            </div>
        </div>

        <div id="produkView" style="display:none;">
            <div class="kategori-back-row">
                <button class="kategori-back-btn" onclick="backToKategori()">← Kategori</button>
                <span class="kategori-nama-aktif" id="kategoriNamaAktif"></span>
            </div>
            <div class="product-grid" id="produkGrid">
                <div class="loading-text">Memuat...</div>
            </div>
        </div>
    </div>

    <!-- Keranjang -->
    <div class="card">
        <div class="section-title">🛍️ Keranjang</div>
        <div id="cartContainer">
            <?php // diisi via renderCart() saat load pertama, lihat di bawah ?>
        </div>
    </div>

    <div class="toast" id="toast"></div>

    <script>
        const counter = <?php echo json_encode($counter); ?>;
        const tanggal = <?php echo json_encode($tanggal); ?>;
        const nama = <?php echo json_encode($nama); ?>;
        const alamat = <?php echo json_encode($alamat); ?>;
        const nowa = <?php echo json_encode($nowa); ?>;
        const note = <?php echo json_encode($note); ?>;

        function showToast(msg) {
            const t = document.getElementById('toast');
            t.textContent = msg;
            t.classList.add('show');
            setTimeout(() => t.classList.remove('show'), 1200);
        }

        function showProduk(jenisId, jenisNama) {
            document.getElementById('kategoriView').style.display = 'none';
            document.getElementById('produkView').style.display = 'block';
            document.getElementById('kategoriNamaAktif').textContent = jenisNama;
            const grid = document.getElementById('produkGrid');
            grid.innerHTML = '<div class="loading-text">Memuat...</div>';

            fetch(`order2.php?ajax=produk_by_jenis&jenis_id=${jenisId}`)
                .then(r => r.json())
                .then(list => {
                    if (list.length === 0) {
                        grid.innerHTML = '<div class="loading-text">Belum ada produk aktif di kategori ini</div>';
                        return;
                    }
                    grid.innerHTML = list.map(p => `
                        <button class="product-btn" onclick="addToCart(${p.id}, this)">
                            <div class="p-nama">${escapeHtml(p.nama)}</div>
                            <div class="p-harga">Rp ${Number(p.harga).toLocaleString('id-ID')}</div>
                        </button>
                    `).join('');
                });
        }

        function backToKategori() {
            document.getElementById('produkView').style.display = 'none';
            document.getElementById('kategoriView').style.display = 'block';
        }

        function escapeHtml(str) {
            const d = document.createElement('div');
            d.textContent = str;
            return d.innerHTML;
        }

        function addToCart(produkId, btnEl) {
            btnEl.style.opacity = '0.5';
            const body = new URLSearchParams({ tujuan: 'ADD_ITEM', produk_id: produkId, counter: counter });
            fetch('order2.php', { method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'}, body })
                .then(r => r.json())
                .then(() => {
                    showToast('✅ Ditambahkan ke keranjang');
                    refreshCart();
                    // otomatis balik ke layar kategori, siap pilih kategori lain
                    backToKategori();
                })
                .finally(() => { btnEl.style.opacity = '1'; });
        }

        function refreshCart() {
            fetch(`cart_fragment.php?counter=${encodeURIComponent(counter)}`)
                .then(r => r.text())
                .then(html => { document.getElementById('cartContainer').innerHTML = html; })
                .then(() => attachCartEvents());
        }

        function attachCartEvents() {
            document.querySelectorAll('.qty-control button[data-action]').forEach(btn => {
                btn.onclick = () => {
                    const tempId = btn.getAttribute('data-temp-id');
                    const input = document.querySelector(`input[data-temp-id="${tempId}"]`);
                    let val = parseInt(input.value) + (btn.getAttribute('data-action') === 'inc' ? 1 : -1);
                    if (val < 1) val = 1;
                    input.value = val;
                    setQty(tempId, val);
                };
            });
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.onclick = () => {
                    if (!confirm('Hapus item ini dari keranjang?')) return;
                    const tempId = btn.getAttribute('data-temp-id');
                    fetch(`order2.php?delete=${tempId}`)
                        .then(() => refreshCart());
                };
            });
            document.getElementById('diskpersen')?.addEventListener('input', updateTotalDisplay);
            document.getElementById('diskrp')?.addEventListener('input', updateTotalDisplay);
            updateTotalDisplay();
        }

        function setQty(tempId, qty) {
            const body = new URLSearchParams({ tujuan: 'SET_QTY', temp_id: tempId, qty: qty });
            fetch('order2.php', { method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'}, body })
                .then(() => refreshCart());
        }

        function updateTotalDisplay() {
            const rows = document.querySelectorAll('.cart-item[data-harga]');
            let total = 0;
            rows.forEach(r => {
                const harga = parseFloat(r.getAttribute('data-harga'));
                const qtyInput = r.querySelector('input[data-temp-id]');
                const qty = qtyInput ? parseInt(qtyInput.value) : 1;
                total += harga * qty;
            });
            const diskpersen = parseFloat(document.getElementById('diskpersen')?.value) || 0;
            const diskrp = parseFloat(document.getElementById('diskrp')?.value) || 0;
            total = total - (total * diskpersen / 100) - diskrp;
            if (total < 0) total = 0;
            const totalEl = document.getElementById('totalAmount');
            if (totalEl) totalEl.textContent = total.toLocaleString('id-ID');
        }

        // load keranjang saat halaman pertama dibuka
        refreshCart();
    </script>
</body>
</html>
