<?php
require_once '../init.php';

if ($_SESSION['role'] !== 'admin' && isset($subsStats) && !$subsStats['is_active']) {
    Helper::redirect(APP_URL . '/subscription/expired.php');
}

$cart = $_SESSION['cart'] ?? [];
$cartTotal = 0;
foreach ($cart as $item) $cartTotal += $item['subtotal'];
$cartCount = count($cart);

$allProducts = $product->getAll($_SESSION['user_id'], 200);

// Build category list
$categories = [];
foreach ($allProducts as $p) {
    if (!empty($p['category']) && !in_array($p['category'], $categories)) {
        $categories[] = $p['category'];
    }
}
sort($categories);

$pageTitle = 'Kasir - KasirMurah.biz.id';
?>
<?php include '../layout/header.php'; ?>
    <?php include '../layout/navbar.php'; ?>

    <div class="pos-wrapper">
        <!-- ===== Product Area ===== -->
        <div class="pos-products">
            <!-- Search -->
            <div class="mb-3">
                <input type="text" id="productSearch" class="form-control"
                       placeholder="Cari produk atau SKU..." style="border-radius:12px;padding:12px 16px;">
            </div>

            <!-- Category tabs -->
            <?php if (!empty($categories)): ?>
            <div class="cat-tabs mb-3" id="catTabs">
                <div class="cat-tab active" data-cat="">Semua</div>
                <?php foreach ($categories as $cat): ?>
                <div class="cat-tab" data-cat="<?php echo htmlspecialchars($cat); ?>"><?php echo htmlspecialchars($cat); ?></div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- Product list -->
            <div class="card">
                <div class="card-body py-1 px-3" id="productList">
                    <?php if (empty($allProducts)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-box fa-3x mb-3 d-block" style="color:var(--primary-light)"></i>
                        Belum ada produk. <a href="../products/create.php">Tambah produk</a>
                    </div>
                    <?php endif; ?>
                    <?php foreach ($allProducts as $prod): ?>
                    <div class="product-row product-item"
                         data-name="<?php echo strtolower(htmlspecialchars($prod['name'])); ?>"
                         data-sku="<?php echo strtolower(htmlspecialchars($prod['sku'])); ?>"
                         data-cat="<?php echo htmlspecialchars($prod['category'] ?? ''); ?>"
                         data-id="<?php echo $prod['id']; ?>"
                         data-price="<?php echo $prod['selling_price']; ?>"
                         data-pname="<?php echo htmlspecialchars($prod['name'], ENT_QUOTES); ?>">
                        <div class="product-row-thumb">
                            <i class="fas fa-box"></i>
                        </div>
                        <div class="product-row-info">
                            <div class="product-row-name"><?php echo htmlspecialchars($prod['name']); ?></div>
                            <div class="product-row-sku"><?php echo htmlspecialchars($prod['sku']); ?> · Stok: <?php echo $prod['quantity']; ?></div>
                            <div class="product-row-price"><?php echo Helper::formatCurrency($prod['selling_price']); ?></div>
                        </div>
                        <?php
                            $inCart = isset($_SESSION['cart'][$prod['id']]) ? $_SESSION['cart'][$prod['id']]['quantity'] : 0;
                        ?>
                        <?php
                            $addAction = htmlspecialchars(json_encode([
                                'action'       => 'add',
                                'product_id'   => $prod['id'],
                                'product_name' => $prod['name'],
                                'sku'          => $prod['sku'],
                                'unit_price'   => $prod['selling_price'],
                            ]), ENT_QUOTES);
                        ?>
                        <div class="qty-ctrl" id="qtyCtrl_<?php echo $prod['id']; ?>">
                            <?php if ($inCart > 0): ?>
                            <button class="qty-btn qty-btn-minus"
                                    onclick="cartAction({action:'remove_one',product_id:<?php echo $prod['id']; ?>}, updateAll)">−</button>
                            <span class="qty-num"><?php echo $inCart; ?></span>
                            <button class="qty-btn qty-btn-plus"
                                    onclick="cartAction(JSON.parse(this.dataset.p), updateAll)"
                                    data-p="<?php echo $addAction; ?>">+</button>
                            <?php else: ?>
                            <button class="qty-btn qty-btn-plus"
                                    onclick="cartAction(JSON.parse(this.dataset.p), updateAll)"
                                    data-p="<?php echo $addAction; ?>">+</button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- ===== Cart Area (Desktop sidebar / Mobile drawer) ===== -->
        <div class="pos-cart" id="posCart">
            <div class="pos-cart-header">
                <span><i class="fas fa-shopping-cart me-2" style="color:var(--primary)"></i>Pesanan
                    <span class="badge ms-1" style="background:var(--primary)" id="cartBadgeHeader"><?php echo $cartCount; ?></span>
                </span>
                <button class="btn btn-sm btn-outline-secondary d-lg-none" onclick="toggleCart()">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <div class="pos-cart-items" id="cartItems">
                <?php if (empty($cart)): ?>
                <div class="text-muted text-center py-5" style="font-size:14px">
                    <i class="fas fa-shopping-cart fa-2x mb-2 d-block" style="color:var(--border)"></i>
                    Keranjang kosong
                </div>
                <?php else: ?>
                <?php foreach ($cart as $item): ?>
                <div class="cart-item">
                    <div style="flex:1;min-width:0">
                        <div class="cart-item-name"><?php echo htmlspecialchars(Helper::truncate($item['product_name'], 22)); ?></div>
                        <div class="cart-item-price"><?php echo $item['quantity']; ?> × <?php echo Helper::formatCurrency($item['unit_price']); ?></div>
                    </div>
                    <div class="text-end" style="flex-shrink:0">
                        <div style="font-size:14px;font-weight:700;color:var(--primary)"><?php echo Helper::formatCurrency($item['subtotal']); ?></div>
                        <button class="btn btn-sm mt-1" style="color:var(--danger);padding:2px 6px"
                                onclick="cartAction({action:'remove',product_id:<?php echo $item['product_id']; ?>}, updateAll)">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="pos-cart-footer">
                <div class="d-flex justify-content-between mb-2" style="font-size:13px">
                    <span class="text-muted">Subtotal</span>
                    <strong id="subtotal"><?php echo Helper::formatCurrency($cartTotal); ?></strong>
                </div>
                <div class="row g-2 mb-2 align-items-center">
                    <div class="col-6">
                        <label class="form-label mb-1">Tax (%)</label>
                        <input type="number" id="taxPercent" class="form-control form-control-sm" value="10" min="0" max="100">
                    </div>
                    <div class="col-6 text-end">
                        <div class="text-muted" style="font-size:11px">Tax</div>
                        <strong id="tax" style="font-size:13px">Rp 0</strong>
                    </div>
                </div>
                <div class="row g-2 mb-3 align-items-center">
                    <div class="col-6">
                        <label class="form-label mb-1">Diskon (Rp)</label>
                        <input type="number" id="discount" class="form-control form-control-sm" value="0" min="0">
                    </div>
                    <div class="col-6 text-end">
                        <div class="text-muted" style="font-size:11px">Diskon</div>
                        <strong id="discountAmount" style="font-size:13px">Rp 0</strong>
                    </div>
                </div>
                <div class="d-flex justify-content-between align-items-center border-top pt-3 mb-3">
                    <span class="fw-bold">TOTAL</span>
                    <span class="fw-bold fs-5" style="color:var(--primary)" id="total"><?php echo Helper::formatCurrency($cartTotal); ?></span>
                </div>

                <form method="POST" action="process.php" id="paymentForm">
                    <input type="hidden" name="items" id="itemsInput">
                    <input type="hidden" name="subtotal" id="subtotalInput">
                    <input type="hidden" name="tax" id="taxInput">
                    <input type="hidden" name="discount" id="discountInput">
                    <input type="hidden" name="total" id="totalInput">
                    <select name="payment_method" class="form-select form-select-sm mb-2" required>
                        <option value="">— Metode Pembayaran —</option>
                        <option value="cash">Tunai</option>
                        <option value="card">Kartu Kredit/Debit</option>
                        <option value="transfer">Transfer Bank</option>
                        <option value="qris">QRIS</option>
                    </select>
                    <button type="submit" class="btn btn-primary w-100 fw-bold">
                        <i class="fas fa-check-circle me-1"></i> Proses Pembayaran
                    </button>
                    <button type="button" class="btn btn-outline-secondary w-100 mt-2 btn-sm" onclick="clearCart()">
                        Batalkan Transaksi
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Mobile bottom action bar (tap to open cart) -->
    <button class="pos-action-bar" onclick="toggleCart()" id="posActionBar" style="display:none">
        <div>
            <div class="pa-label"><i class="fas fa-shopping-cart me-2"></i>Lihat Pesanan</div>
            <div class="pa-meta"><span id="actionBarCount"><?php echo $cartCount; ?></span> item</div>
        </div>
        <div class="pa-total" id="actionBarTotal"><?php echo Helper::formatCurrency($cartTotal); ?></div>
        <div class="pa-arrow"><i class="fas fa-chevron-up"></i></div>
    </button>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    function formatCurrency(num) {
        return 'Rp ' + new Intl.NumberFormat('id-ID').format(Math.round(num));
    }

    function toggleCart() {
        document.getElementById('posCart').classList.toggle('cart-open');
    }

    function cartAction(data, callback) {
        const form = new FormData();
        for (const k in data) form.append(k, data[k]);
        fetch('cart_action.php', { method: 'POST', body: form })
            .then(r => r.json())
            .then(res => { if (res.success) callback(res); })
            .catch(() => alert('Gagal menghubungi server'));
    }

    function updateQtyControls(cart) {
        document.querySelectorAll('.qty-ctrl').forEach(ctrl => {
            const productId = ctrl.id.replace('qtyCtrl_', '');
            const item = cart.find(i => String(i.product_id) === productId);
            const qty = item ? item.quantity : 0;
            const row = ctrl.closest('.product-row');
            const name  = row ? row.getAttribute('data-pname') : '';
            const price = row ? parseFloat(row.getAttribute('data-price')) : 0;
            const addPayload = JSON.stringify({action:'add',product_id:parseInt(productId),product_name:name,unit_price:price});

            if (qty > 0) {
                ctrl.innerHTML = `
                    <button class="qty-btn qty-btn-minus"
                        onclick="cartAction({action:'remove_one',product_id:${productId}}, updateAll)">−</button>
                    <span class="qty-num">${qty}</span>
                    <button class="qty-btn qty-btn-plus"
                        onclick="cartAction(JSON.parse(this.dataset.p), updateAll)"
                        data-p='${addPayload.replace(/'/g, "&#39;")}'>+</button>`;
            } else {
                ctrl.innerHTML = `
                    <button class="qty-btn qty-btn-plus"
                        onclick="cartAction(JSON.parse(this.dataset.p), updateAll)"
                        data-p='${addPayload.replace(/'/g, "&#39;")}'>+</button>`;
            }
        });
    }

    function renderCart(cart) {
        const container = document.getElementById('cartItems');
        if (cart.length === 0) {
            container.innerHTML = '<div class="text-muted text-center py-5" style="font-size:14px"><i class="fas fa-shopping-cart fa-2x mb-2 d-block" style="color:var(--border)"></i>Keranjang kosong</div>';
        } else {
            container.innerHTML = cart.map(item => `
                <div class="cart-item">
                    <div style="flex:1;min-width:0">
                        <div class="cart-item-name">${item.product_name.substring(0, 22)}</div>
                        <div class="cart-item-price">${item.quantity} × ${formatCurrency(item.unit_price)}</div>
                    </div>
                    <div class="text-end" style="flex-shrink:0">
                        <div style="font-size:14px;font-weight:700;color:var(--primary)">${formatCurrency(item.subtotal)}</div>
                        <button class="btn btn-sm mt-1" style="color:var(--danger);padding:2px 6px"
                            onclick="cartAction({action:'remove',product_id:${item.product_id}}, updateAll)">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </div>`).join('');
        }
        const count = cart.length;
        document.getElementById('cartBadgeHeader').textContent = count;
        document.getElementById('actionBarCount').textContent = count;
    }

    function updateTotals(subtotal) {
        subtotal = subtotal || 0;
        const taxPct = parseFloat(document.getElementById('taxPercent').value) || 0;
        const disc   = parseFloat(document.getElementById('discount').value) || 0;
        const tax    = subtotal * taxPct / 100;
        document.getElementById('subtotal').textContent       = formatCurrency(subtotal);
        document.getElementById('tax').textContent            = formatCurrency(tax);
        document.getElementById('discountAmount').textContent = formatCurrency(disc);
        document.getElementById('total').textContent          = formatCurrency(subtotal + tax - disc);
        document.getElementById('actionBarTotal').textContent = formatCurrency(subtotal + tax - disc);
    }

    function updateFormInputs(cart, subtotal) {
        subtotal = subtotal || 0;
        const taxPct = parseFloat(document.getElementById('taxPercent').value) || 0;
        const disc   = parseFloat(document.getElementById('discount').value) || 0;
        const tax    = subtotal * taxPct / 100;
        document.getElementById('itemsInput').value    = JSON.stringify(cart);
        document.getElementById('subtotalInput').value = subtotal;
        document.getElementById('taxInput').value      = tax;
        document.getElementById('discountInput').value = disc;
        document.getElementById('totalInput').value    = subtotal + tax - disc;
    }

    function updateAll(res) {
        renderCart(res.cart);
        updateQtyControls(res.cart);
        updateTotals(res.total);
        updateFormInputs(res.cart, res.total);
    }

    ['taxPercent','discount'].forEach(id => {
        document.getElementById(id).addEventListener('input', () => {
            const sub = parseFloat(document.getElementById('subtotalInput').value) || 0;
            updateTotals(sub);
            updateFormInputs(JSON.parse(document.getElementById('itemsInput').value || '[]'), sub);
        });
    });

    // Search
    document.getElementById('productSearch').addEventListener('input', function() {
        const q = this.value.toLowerCase();
        filterProducts(q, activeCat);
    });

    // Category tabs
    let activeCat = '';
    document.querySelectorAll('.cat-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            activeCat = this.getAttribute('data-cat');
            filterProducts(document.getElementById('productSearch').value.toLowerCase(), activeCat);
        });
    });

    function filterProducts(q, cat) {
        document.querySelectorAll('.product-item').forEach(el => {
            const matchQ   = !q || el.getAttribute('data-name').includes(q) || el.getAttribute('data-sku').includes(q);
            const matchCat = !cat || el.getAttribute('data-cat') === cat;
            el.style.display = matchQ && matchCat ? '' : 'none';
        });
    }

    // Show/hide mobile action bar
    function checkActionBar() {
        const bar = document.getElementById('posActionBar');
        if (window.innerWidth < 992) {
            bar.style.display = 'flex';
        } else {
            bar.style.display = 'none';
        }
    }
    window.addEventListener('resize', checkActionBar);
    checkActionBar();

    // Init
    updateTotals(<?php echo $cartTotal; ?>);
    updateFormInputs(<?php echo json_encode(array_values($cart)); ?>, <?php echo $cartTotal; ?>);
    </script>
</body>
</html>
