<?php
session_start();
include("db_connect.php");

// Make sure user is logged in as cashier
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'cashier') {
    header("Location: login.php");
    exit();
}

// Ensure there is an open cash session
include 'require_cash_session.php';

$cashier       = $_SESSION['username'] ?? 'unknown';
$cashSessionId = $_SESSION['cash_session_id'] ?? null; // from open_cash_session.php
$page_title    = "Scan Products";
$active        = 'sales'; // highlight "Sales" in the top nav

if (!$cashSessionId) {
    // Extra defence in case require_cash_session.php didn't handle it
    header("Location: open_cash_session.php");
    exit();
}

/* -------------------------------
   FLASH MESSAGE (for redirects)
--------------------------------- */
$message = null;
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

/* -------------------------------
   CART + RECEIPT INITIALISATION
--------------------------------- */
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

if (!isset($_SESSION['receipt_id'])) {
    $_SESSION['receipt_id'] = 'RCP-' . date('ymd-His') . '-' . rand(1000, 9999);
}
$receiptId = $_SESSION['receipt_id'];

/* -------------------------------
   CANCEL SALE (clear cart + receipt)
--------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_sale'])) {
    $_SESSION['cart'] = [];
    unset($_SESSION['receipt_id']);

    $_SESSION['flash_message'] = "✔ Sale cancelled and cart cleared.";
    header("Location: scan_sales.php");
    exit();
}

/* -------------------------------
   HANDLE BARCODE SCAN
   (POST/REDIRECT/GET to avoid duplicates on refresh)
--------------------------------- */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['barcode'])
    && !isset($_POST['update_cart'])
    && !isset($_POST['finalize_sale'])
) {
    $barcode      = mysqli_real_escape_string($conn, $_POST['barcode']);
    $productQuery = mysqli_query($conn, "SELECT * FROM products WHERE barcode = '$barcode'");
    $product      = mysqli_fetch_assoc($productQuery);

    if ($product && $product['quantity'] > 0) {
        $productId = $product['id'];

        if (isset($_SESSION['cart'][$productId])) {
            $_SESSION['cart'][$productId]['quantity']++;
        } else {
            $_SESSION['cart'][$productId] = [
                'name'                  => $product['name'],
                'quantity'              => 1,
                'default_selling_price' => $product['selling_price'],
                'selling_price'         => $product['selling_price'],
                'buying_price'          => $product['buying_price']
            ];
        }
        $_SESSION['flash_message'] = "✔ Added " . htmlspecialchars($product['name']) . " to cart";
    } else {
        $_SESSION['flash_message'] = "❌ Product not found or out of stock";
    }

    // Redirect so that refresh does NOT resubmit the scan
    header("Location: scan_sales.php");
    exit();
}

/* -------------------------------
   UPDATE CART
--------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_cart'])) {
    if (isset($_POST['quantity'])) {
        foreach ($_POST['quantity'] as $id => $qty) {
            $id = (int)$id;
            if (isset($_SESSION['cart'][$id])) {
                $_SESSION['cart'][$id]['quantity'] = max(1, (int)$qty);
            }
        }
    }

    if (isset($_POST['selling_price'])) {
        foreach ($_POST['selling_price'] as $id => $price) {
            $id = (int)$id;
            if (isset($_SESSION['cart'][$id])) {
                $_SESSION['cart'][$id]['selling_price'] = (float)$price;
            }
        }
    }
}

/* -------------------------------
   GRAND TOTALS (for display + payment)
--------------------------------- */
$grandTotal    = 0;
$grandDiscount = 0;

foreach ($_SESSION['cart'] as $item) {
    $lineDiscount   = max(0, ($item['default_selling_price'] - $item['selling_price']) * $item['quantity']);
    $grandDiscount += $lineDiscount;
    $grandTotal    += $item['selling_price'] * $item['quantity'];
}

/* -------------------------------
   FINALISE SALE + PAYMENT
--------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['finalize_sale'])) {

    // Block if cart is empty
    if (empty($_SESSION['cart'])) {
        $message = "❌ Cart is empty. Add products before finalising the sale.";
    } else {

        // Recalculate totals on the server (never trust client)
        $grandTotalLocal    = 0;
        $grandDiscountLocal = 0;
        foreach ($_SESSION['cart'] as $item) {
            $lineDiscount       = max(0, ($item['default_selling_price'] - $item['selling_price']) * $item['quantity']);
            $grandDiscountLocal += $lineDiscount;
            $grandTotalLocal    += $item['selling_price'] * $item['quantity'];
        }

        $payment_method = $_POST['payment_method'] ?? 'mpesa';
        $allowedMethods = ['cash', 'mpesa', 'bank'];
        if (!in_array($payment_method, $allowedMethods, true)) {
            $payment_method = 'mpesa';
        }

        $mpesa_code = trim($_POST['mpesa_code'] ?? '');
        $bank_ref   = trim($_POST['bank_ref'] ?? '');
        $cash_paid  = isset($_POST['cash_paid']) ? (float)$_POST['cash_paid'] : 0.0;

        $amount_paid = 0.0;
        $change      = 0.0;
        $errors      = [];

        if ($payment_method === 'cash') {
            // cashier must enter amount paid by client
            if ($cash_paid <= 0) {
                $errors[] = "Please enter the cash amount paid by the client.";
            } elseif ($cash_paid < $grandTotalLocal) {
                $errors[] = "Cash paid (KES " . number_format($cash_paid, 2) .
                            ") is less than the total amount (KES " . number_format($grandTotalLocal, 2) . ").";
            } else {
                $amount_paid = $cash_paid;
                $change      = $cash_paid - $grandTotalLocal;
            }
        } elseif ($payment_method === 'mpesa') {
            // no change; but we need M-Pesa code
            if ($mpesa_code === '') {
                $errors[] = "Please enter the M-Pesa transaction code.";
            }
            $amount_paid = $grandTotalLocal;
            $change      = 0.0;
        } elseif ($payment_method === 'bank') {
            // no change; need bank reference
            if ($bank_ref === '') {
                $errors[] = "Please enter the bank transaction reference.";
            }
            $amount_paid = $grandTotalLocal;
            $change      = 0.0;
        }

        // If there are validation errors, DO NOT save the sale
        if (!empty($errors)) {
            $message = "❌ " . implode(' ', $errors);
        } else {
            /*  SAVE SALES LINES (linked to cash_session_id)  */
            foreach ($_SESSION['cart'] as $id => $item) {
                $productId  = $id;
                $qty        = $item['quantity'];
                $buyPrice   = $item['buying_price'];
                $sellPrice  = $item['selling_price'];
                $profit     = ($sellPrice - $buyPrice) * $qty;
                $totalSale  = $sellPrice * $qty;
                $discount   = max(0, ($item['default_selling_price'] - $sellPrice) * $qty);

                $stmt = $conn->prepare(
                    "INSERT INTO sales 
                     (receipt_id, sale_datetime, cashier, cash_session_id, product_id, quantity, buying_price, selling_price, total_sale, profit, discount, refunded)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?,0)"
                );
                $now = date('Y-m-d H:i:s');
                $stmt->bind_param(
                    "sssiidddddd",
                    $receiptId,
                    $now,
                    $cashier,
                    $cashSessionId,
                    $productId,
                    $qty,
                    $buyPrice,
                    $sellPrice,
                    $totalSale,
                    $profit,
                    $discount
                );
                $stmt->execute();
                $stmt->close();

                // Reduce stock
                $conn->query("UPDATE products SET quantity = quantity - $qty WHERE id = $productId");
            }

            // ---------- SAVE PAYMENT (linked to cash_session_id) ----------
            //
            // payments table expected columns now:
            // id, receipt_id, cashier, cash_session_id, payment_method,
            // amount_due, paid_at, change_amount,
            // mpesa_code, bank_ref, print_requested, created_at
            //
            $amount_due      = $grandTotalLocal; // total bill
            $paid_amount_col = $amount_paid;     // what the client actually paid
            $change_amount   = $change;

            // Checkbox controls redirect AND print_requested flag
            $openReceipt    = isset($_POST['open_receipt']) && $_POST['open_receipt'] === '1';
            $printRequested = $openReceipt ? 1 : 0;

            if ($stmtPay = $conn->prepare("
                INSERT INTO payments
                (receipt_id, cashier, cash_session_id, payment_method, amount_due, paid_at, change_amount, mpesa_code, bank_ref, print_requested)
                VALUES (?,?,?,?,?,?,?,?,?,?)
            ")) {
                // s = string, d = double, i = int
                $stmtPay->bind_param(
                    "sssidddssi",
                    $receiptId,
                    $cashier,
                    $cashSessionId,
                    $payment_method,
                    $amount_due,
                    $paid_amount_col,
                    $change_amount,
                    $mpesa_code,
                    $bank_ref,
                    $printRequested
                );
                $stmtPay->execute();
                $stmtPay->close();
            }

            // Clear cart & receipt
            $_SESSION['cart'] = [];
            unset($_SESSION['receipt_id']);

            // Redirect: open receipt or just go back to dashboard
            if ($openReceipt) {
                header("Location: receipt.php?id=$receiptId");
            } else {
                header("Location: today_transaction_history.php?msg=Sale%20saved");
            }
            exit();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        :root {
            --cash-accent-teal: var(--cash-accent-teal, #22d3ee);
            --cash-accent-alt:  var(--cash-accent-alt,  #7dd3fc);
        }

        .cashier-main {
            padding: 24px 30px 34px;
            min-width: 0;
        }

        @media (max-width: 900px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
        }

        .pos-wrapper {
            max-width: 1280px;
            margin: 0 auto;
            width: 100%;
        }

        /* CARD */

        .pos-card {
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.10), transparent 55%),
                var(--cash-bg-card);
            border-radius: 18px;
            padding: 22px 24px 26px;
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.55);
            border: 1px solid var(--cash-border-soft);
        }

        html[data-theme="light"] .pos-card {
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.12), transparent 55%),
                #ffffff;
            box-shadow: 0 10px 22px rgba(15,23,42,0.12);
            border-color: #dbeafe;
        }

        .pos-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 18px;
            gap: 10px;
        }

        .pos-header h2 {
            font-size: 18px;
            font-weight: 600;
        }

        .pos-header p {
            font-size: 13px;
            color: var(--cash-text-muted);
            margin-top: 2px;
        }

        html[data-theme="light"] .pos-header p {
            color: #475569;
        }

        .receipt-pill {
            padding: 6px 14px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.7);
            background:
                radial-gradient(circle at 0% 0%, rgba(34,211,238,0.24), transparent 60%),
                rgba(15,23,42,0.96);
            font-size: 12px;
            color: var(--cash-accent-alt);
            white-space: nowrap;
        }

        html[data-theme="light"] .receipt-pill {
            background:
                radial-gradient(circle at 0% 0%, rgba(56,189,248,0.18), transparent 60%),
                #eff6ff;
            color: #0369a1;
        }

        /* SCAN FORM */

        .scan-form-row {
            display: flex;
            gap: 10px;
            margin-bottom: 14px;
            margin-top: 4px;
        }

        .scan-form-row input[type="text"] {
            flex: 1;
            padding: 11px 12px;
            border-radius: 10px;
            border: 1px solid rgba(148,163,184,0.45);
            background: #001B3A;
            color: #ffffff;
            outline: none;
            font-size: 14px;
        }

        .scan-form-row input::placeholder {
            color: rgba(211, 224, 237, 0.9);
        }

        html[data-theme="light"] .scan-form-row input[type="text"] {
            background: #ffffff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        html[data-theme="light"] .scan-form-row input::placeholder {
            color: #9ca3af;
        }

        .scan-form-row input[type="text"]:focus {
            border-color: #22d3ee;
            box-shadow: 0 0 0 1px rgba(34,211,238,0.55);
        }

        .btn-primary-main {
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
            border: none;
            border-radius: 10px;
            padding: 11px 18px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            white-space: nowrap;
            box-shadow: 0 10px 26px rgba(0,0,0,0.55);
        }

        .btn-primary-main:hover {
            filter: brightness(1.06);
        }

        /* MESSAGES */

        .pos-message {
            margin-bottom: 10px;
            border-radius: 10px;
            padding: 10px 12px;
            font-size: 13px;
        }

        .pos-message.success {
            background: rgba(34,197,94,0.10);
            border-left: 3px solid #22c55e;
            color: #bbf7d0;
        }

        .pos-message.error {
            background: rgba(220,38,38,0.12);
            border-left: 3px solid #ef4444;
            color: #fecaca;
        }

        html[data-theme="light"] .pos-message.success {
            background: #dcfce7;
            color: #166534;
        }

        html[data-theme="light"] .pos-message.error {
            background: #fee2e2;
            color: #b91c1c;
        }

        /* CART TABLE */

        .pos-table-wrapper {
            margin-top: 18px;
            overflow-x: auto;
        }

        table.pos-table {
            width: 100%;
            border-collapse: collapse;
            border-radius: 12px;
            overflow: hidden;
            font-size: 13px;
        }

        .pos-table th,
        .pos-table td {
            padding: 10px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(148,163,184,0.35);
            color: #E5E7EB;
        }

        .pos-table th {
            background: #012a73;
            color: #82EEFD;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 0.06em;
        }

        .pos-table tr:nth-child(even) {
            background: rgba(2,35,98,0.82);
        }

        .pos-table tr:nth-child(odd) {
            background: rgba(1,26,80,0.82);
        }

        .pos-table tr:hover {
            background: rgba(130,238,253,0.18);
        }

        html[data-theme="light"] .pos-table th {
            background: #eff6ff;
            color: #0f172a;
        }

        html[data-theme="light"] .pos-table td {
            color: #0f172a;
        }

        html[data-theme="light"] .pos-table tr:nth-child(even) {
            background: #f9fafb;
        }

        html[data-theme="light"] .pos-table tr:nth-child(odd) {
            background: #ffffff;
        }

        html[data-theme="light"] .pos-table tr:hover {
            background: #e0f2fe;
        }

        .pos-table input[type="number"] {
            width: 90px;
            padding: 6px 8px;
            border-radius: 8px;
            border: 1px solid rgba(148,163,184,0.6);
            background: #001B3A;
            color: #ffffff;
            font-size: 13px;
        }

        html[data-theme="light"] .pos-table input[type="number"] {
            background: #ffffff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        .totals-row {
            background: rgba(3,4,94,0.98);
            font-weight: 600;
        }

        html[data-theme="light"] .totals-row {
            background: #e0f2fe;
        }

        /* PAYMENT SECTION */

        .payment-section {
            margin-top: 16px;
            padding: 14px 12px;
            border-radius: 14px;
            border: 1px solid rgba(148,163,184,0.6);
            background: rgba(2,16,40,0.85);
        }

        html[data-theme="light"] .payment-section {
            background: #f9fafb;
            border-color: #cbd5f5;
        }

        .payment-section h3 {
            font-size: 15px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .payment-section h3 span {
            font-size: 16px;
        }

        .payment-methods {
            display: flex;
            flex-wrap: wrap;
            gap: 14px;
            margin-bottom: 10px;
            font-size: 13px;
        }

        .payment-methods label {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            cursor: pointer;
        }

        .payment-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
            gap: 10px;
            font-size: 13px;
        }

        .payment-field {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .payment-field span.label {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            opacity: 0.85;
        }

        .payment-field input[type="text"],
        .payment-field input[type="number"] {
            padding: 8px 10px;
            border-radius: 10px;
            border: 1px solid rgba(148,163,184,0.6);
            background: #001B3A;
            color: #ffffff;
            font-size: 13px;
        }

        html[data-theme="light"] .payment-field input[type="text"],
        html[data-theme="light"] .payment-field input[type="number"] {
            background: #ffffff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        .payment-summary {
            margin-top: 8px;
            font-size: 13px;
        }

        .payment-summary .amount {
            font-weight: 600;
        }

        .payment-summary .change-positive {
            color: #4ade80;
        }

        .payment-summary .change-zero {
            color: #e5e7eb;
        }

        html[data-theme="light"] .payment-summary .change-zero {
            color: #111827;
        }

        .payment-options-extra {
            margin-top: 10px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* ACTION BUTTONS UNDER TABLE */

        .pos-actions {
            margin-top: 16px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .btn-secondary {
            background: rgba(15,23,42,0.9);
            color: #e5e7eb;
            border-radius: 10px;
            border: 1px solid rgba(148,163,184,0.7);
            padding: 10px 16px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
        }

        .btn-secondary:hover {
            background: rgba(15,23,42,1);
        }

        html[data-theme="light"] .btn-secondary {
            background: #f3f4f6;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        html[data-theme="light"] .btn-secondary:hover {
            background: #e5e7eb;
        }

        .btn-primary-submit {
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
            border-radius: 10px;
            border: none;
            padding: 10px 18px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 10px 26px rgba(0,0,0,0.55);
        }

        .btn-primary-submit:hover {
            filter: brightness(1.06);
        }

        .back-link {
            display: inline-block;
            margin-top: 18px;
            font-size: 13px;
            color: var(--cash-accent-alt);
            text-decoration: none;
        }

        .back-link:hover {
            text-decoration: underline;
        }

        @media (max-width: 800px) {
            .scan-form-row {
                flex-direction: column;
            }

            .scan-form-row input[type="text"],
            .btn-primary-main {
                width: 100%;
            }

            .pos-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>

<div class="cashier-shell">

    <?php include 'cashier_sidebar.php'; ?>

    <main class="cashier-main" id="cashierMain">
        <div class="pos-wrapper">

            <!-- TOP BAR (shared style) -->
            <div class="cashier-topbar">
                <div class="cashier-topbar-left">
                    <h1><?= htmlspecialchars($page_title); ?></h1>
                    <small>Use the barcode scanner or type the code to add items to the cart.</small>
                </div>

                <div class="cashier-topbar-right">
                    <nav class="cashier-topnav">
                        <a href="cashier_dashboard.php" class="<?= ($active === 'dashboard') ? 'active' : '' ?>">Dashboard</a>
                        <a href="record_sales.php" class="<?= ($active === 'sales') ? 'active' : '' ?>">Sales</a>
                        <a href="cashier_view_daily_sales.php" class="<?= ($active === 'daily_sales') ? 'active' : '' ?>">Today’s Sales</a>
                        <a href="customer_debts.php" class="<?= ($active === 'debts') ? 'active' : '' ?>">Debts</a>
                    </nav>

                    <button type="button" class="cashier-theme-toggle" onclick="toggleCashierTheme()">
                        <span class="icon">🌓</span>
                        <span class="label">Theme</span>
                    </button>

                    <button class="cashier-toggle" type="button" onclick="toggleCashierSidebar()">☰</button>
                </div>
            </div>

            <!-- MAIN POS CARD -->
            <section class="pos-card">
                <div class="pos-header">
                    <div>
                        <h2>Cashier POS · Scanner</h2>
                        <p>Scan, adjust quantities, choose payment method, and finalise the sale for this receipt.</p>
                    </div>
                    <span class="receipt-pill">
                        Receipt ID · <?= htmlspecialchars($receiptId); ?>
                    </span>
                </div>

                <?php if ($message) : ?>
                    <div class="pos-message <?= (function_exists('str_starts_with') && str_starts_with($message, '✔')) ? 'success' : 'error'; ?>">
                        <?= $message ?>
                    </div>
                <?php endif; ?>

                <!-- BARCODE FORM -->
                <form method="post" autocomplete="off" id="barcodeForm">
                    <div class="scan-form-row">
                        <input
                            type="text"
                            name="barcode"
                            id="barcodeInput"
                            placeholder="Scan or type barcode here..."
                            autofocus
                            required
                        >
                        <button type="submit" class="btn-primary-main">Add item</button>
                    </div>
                </form>

                <!-- CART TABLE + PAYMENT -->
                <?php if (!empty($_SESSION['cart'])): ?>
                    <form method="post" id="finalizeForm">
                        <div class="pos-table-wrapper">
                            <table class="pos-table">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Qty</th>
                                        <th>Selling price (KES)</th>
                                        <th>Discount (KES)</th>
                                        <th>Total (KES)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($_SESSION['cart'] as $id => $item):
                                        $lineDiscount = max(
                                            0,
                                            ($item['default_selling_price'] - $item['selling_price']) * $item['quantity']
                                        );
                                    ?>
                                        <tr>
                                            <td style="text-align:left; padding-left:14px;">
                                                <?= htmlspecialchars($item['name']); ?>
                                            </td>
                                            <td>
                                                <input
                                                    type="number"
                                                    name="quantity[<?= $id ?>]"
                                                    value="<?= (int)$item['quantity'] ?>"
                                                    min="1"
                                                >
                                            </td>
                                            <td>
                                                <input
                                                    type="number"
                                                    name="selling_price[<?= $id ?>]"
                                                    value="<?= htmlspecialchars($item['selling_price']) ?>"
                                                    step="0.01"
                                                >
                                            </td>
                                            <td><?= number_format($lineDiscount, 2); ?></td>
                                            <td><?= number_format($item['selling_price'] * $item['quantity'], 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>

                                    <tr class="totals-row">
                                        <td colspan="3" style="text-align:right;">Grand discount</td>
                                        <td colspan="2"><?= number_format($grandDiscount, 2); ?></td>
                                    </tr>
                                    <tr class="totals-row">
                                        <td colspan="4" style="text-align:right;">Grand total</td>
                                        <td id="grandTotalText">
                                            KES <?= number_format($grandTotal, 2); ?>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <!-- PAYMENT SECTION -->
                        <div class="payment-section">
                            <h3><span>💳</span> Payment details</h3>

                            <div class="payment-methods">
                                <label>
                                    <input type="radio" name="payment_method" value="mpesa" checked>
                                    M-Pesa
                                </label>
                                <label>
                                    <input type="radio" name="payment_method" value="cash">
                                    Cash
                                </label>
                                <label>
                                    <input type="radio" name="payment_method" value="bank">
                                    Bank
                                </label>
                            </div>

                            <div class="payment-grid">
                                <!-- M-Pesa code -->
                                <div class="payment-field" id="mpesaField">
                                    <span class="label">M-Pesa code</span>
                                    <input
                                        type="text"
                                        name="mpesa_code"
                                        placeholder="e.g. QJK1XY23AB"
                                    >
                                </div>

                                <!-- Bank reference -->
                                <div class="payment-field" id="bankField" style="display:none;">
                                    <span class="label">Bank reference</span>
                                    <input
                                        type="text"
                                        name="bank_ref"
                                        placeholder="Bank transaction ref"
                                    >
                                </div>

                                <!-- Cash paid -->
                                <div class="payment-field" id="cashField" style="display:none;">
                                    <span class="label">Cash paid (KES)</span>
                                    <input
                                        type="number"
                                        name="cash_paid"
                                        id="cashPaid"
                                        step="0.01"
                                        min="0"
                                        placeholder="Enter cash amount"
                                    >
                                </div>

                                <!-- Summary -->
                                <div class="payment-field">
                                    <span class="label">Summary</span>
                                    <div class="payment-summary">
                                        Total:
                                        <span
                                            class="amount"
                                            id="grandTotalValue"
                                            data-total="<?= htmlspecialchars($grandTotal); ?>"
                                        >
                                            KES <?= number_format($grandTotal, 2); ?>
                                        </span>
                                        <br>
                                        Change:
                                        <span
                                            class="amount change-zero"
                                            id="changeValue"
                                        >
                                            KES 0.00
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <div class="payment-options-extra">
                                <label>
                                    <input type="checkbox" name="open_receipt" value="1" checked>
                                    Open/print receipt after saving sale
                                </label>
                            </div>
                        </div>

                        <div class="pos-actions">
                            <button type="submit" name="update_cart" class="btn-secondary">
                                Update cart
                            </button>
                            <button type="submit" name="cancel_sale" class="btn-secondary"
                                    onclick="return confirm('Cancel this sale and clear the cart?');">
                                Cancel sale
                            </button>
                            <button type="submit" name="finalize_sale" class="btn-primary-submit">
                                Finalise sale &amp; save payment
                            </button>
                        </div>
                    </form>
                <?php endif; ?>

                <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>
            </section>

        </div>
    </main>
</div>

<?php include 'footer.php'; ?>

<script>
// Auto-submit barcode form on Enter (works with scanner too)
document.addEventListener('DOMContentLoaded', function () {
    const form  = document.getElementById('barcodeForm');
    const input = document.getElementById('barcodeInput');

    if (form && input) {
        input.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                if (input.value.trim() !== '') {
                    form.submit();
                }
            }
        });
    }

    // PAYMENT UI BEHAVIOUR
    const methodRadios = document.querySelectorAll('input[name="payment_method"]');
    const mpesaField   = document.getElementById('mpesaField');
    const bankField    = document.getElementById('bankField');
    const cashField    = document.getElementById('cashField');
    const cashPaid     = document.getElementById('cashPaid');
    const changeValue  = document.getElementById('changeValue');
    const totalSpan    = document.getElementById('grandTotalValue');

    let grandTotal = 0;
    if (totalSpan && totalSpan.dataset.total) {
        grandTotal = parseFloat(totalSpan.dataset.total) || 0;
    }

    function updatePaymentVisibility() {
        let method = 'mpesa';
        methodRadios.forEach(r => {
            if (r.checked) {
                method = r.value;
            }
        });

        if (method === 'mpesa') {
            if (mpesaField) mpesaField.style.display = '';
            if (bankField)  bankField.style.display  = 'none';
            if (cashField)  cashField.style.display  = 'none';
            if (changeValue) {
                changeValue.textContent = 'KES 0.00';
                changeValue.classList.remove('change-positive');
                changeValue.classList.add('change-zero');
            }
        } else if (method === 'cash') {
            if (mpesaField) mpesaField.style.display = 'none';
            if (bankField)  bankField.style.display  = 'none';
            if (cashField)  cashField.style.display  = '';
            updateCashChange();
        } else if (method === 'bank') {
            if (mpesaField) mpesaField.style.display = 'none';
            if (bankField)  bankField.style.display  = '';
            if (cashField)  cashField.style.display  = 'none';
            if (changeValue) {
                changeValue.textContent = 'KES 0.00';
                changeValue.classList.remove('change-positive');
                changeValue.classList.add('change-zero');
            }
        }
    }

    function formatKES(value) {
        return 'KES ' + value.toFixed(2);
    }

    function updateCashChange() {
        if (!cashPaid || !changeValue) return;
        let paid   = parseFloat(cashPaid.value) || 0;
        let change = paid - grandTotal;

        if (isNaN(change)) {
            change = 0;
        }

        changeValue.textContent = formatKES(Math.max(change, 0));

        changeValue.classList.remove('change-zero', 'change-positive');
        if (change > 0.0001) {
            changeValue.classList.add('change-positive');
        } else {
            changeValue.classList.add('change-zero');
        }
    }

    if (methodRadios.length > 0) {
        methodRadios.forEach(r => {
            r.addEventListener('change', updatePaymentVisibility);
        });
        updatePaymentVisibility();
    }

    if (cashPaid) {
        cashPaid.addEventListener('input', updateCashChange);
    }
});
</script>

</body>
</html>
