<?php 
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'cashier') {
    header("Location: login.php");
    exit();
}

include("db_connect.php");
include 'require_cash_session.php'; // makes sure a cash session is open

$page_title = "Record Sale | Cashier POS";
$active     = 'sales'; // highlight "Sales" in top nav

// current open cash session for this cashier
$cash_session_id = isset($_SESSION['cash_session_id']) ? (int)$_SESSION['cash_session_id'] : null;
if (!$cash_session_id) {
    // safety fallback – should normally be handled inside require_cash_session.php
    header("Location: open_cash_session.php");
    exit();
}

// Generate Unique Receipt ID
function generateReceiptID() {
    return 'RCP-' . date('ymd-His') . '-' . rand(1000,9999);
}

$errors  = [];
$message = "";

// Handle Form Submission (products + payment)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['product_id'])) {

    $cashier    = $_SESSION['username'];
    $datetime   = date('Y-m-d H:i:s');
    $receipt_id = generateReceiptID();
    $_SESSION['receipt_id'] = $receipt_id;

    $grandTotalLocal    = 0.0;
    $grandDiscountLocal = 0.0;
    $validLines         = [];

    // --------- 1) COLLECT & VALIDATE PRODUCTS, CALCULATE TOTALS ----------
    foreach ($_POST['product_id'] as $index => $product_id) {
        $product_id = intval($product_id);
        $quantity   = isset($_POST['quantity'][$index])   ? floatval($_POST['quantity'][$index])   : 0;
        $sell_price = isset($_POST['sell_price'][$index]) ? floatval($_POST['sell_price'][$index]) : 0;

        // skip empty / incomplete rows
        if ($product_id <= 0 || $quantity <= 0 || $sell_price <= 0) {
            continue;
        }

        $productRes = mysqli_query($conn, "SELECT * FROM products WHERE id = $product_id");
        $product    = mysqli_fetch_assoc($productRes);

        if (!$product) {
            $errors[] = "Product with ID $product_id does not exist.";
            continue;
        }

        $buy_price     = floatval($product['buying_price']);
        $default_price = floatval($product['selling_price']);
        $stock         = intval($product['quantity']);

        if ($quantity > $stock) {
            $errors[] = "Not enough stock for \"" . htmlspecialchars($product['name']) .
                        "\". Available: $stock, requested: $quantity.";
            continue;
        }

        $lineTotal    = $sell_price * $quantity;
        $lineDiscount = max(0, ($default_price - $sell_price) * $quantity);
        $lineProfit   = ($sell_price - $buy_price) * $quantity;

        $grandTotalLocal    += $lineTotal;
        $grandDiscountLocal += $lineDiscount;

        $validLines[] = [
            'product_id'    => $product_id,
            'product_name'  => $product['name'],
            'qty'           => $quantity,
            'buy_price'     => $buy_price,
            'sell_price'    => $sell_price,
            'default_price' => $default_price,
            'line_total'    => $lineTotal,
            'line_discount' => $lineDiscount,
            'line_profit'   => $lineProfit,
            'stock'         => $stock
        ];
    }

    if (empty($validLines)) {
        $errors[] = "Please add at least one valid product with quantity and selling price.";
    }

    // --------- 2) PAYMENT VALIDATION ----------
    $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;

    if ($grandTotalLocal <= 0) {
        $errors[] = "Total amount for this sale is zero. Please check the products and quantities.";
    } else {
        if ($payment_method === 'cash') {
            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') {
            if ($mpesa_code === '') {
                $errors[] = "Please enter the M-Pesa transaction code.";
            }
            $amount_paid = $grandTotalLocal;
            $change      = 0.0;
        } elseif ($payment_method === 'bank') {
            if ($bank_ref === '') {
                $errors[] = "Please enter the bank transaction reference.";
            }
            $amount_paid = $grandTotalLocal;
            $change      = 0.0;
        }
    }
// --------- 2b) OPTIONAL CUSTOMER DETAILS ----------
$customer_name      = isset($_POST['customer_name'])      ? trim($_POST['customer_name'])      : '';
$customer_phone     = isset($_POST['customer_phone'])     ? trim($_POST['customer_phone'])     : '';
$customer_id_number = isset($_POST['customer_id_number']) ? trim($_POST['customer_id_number']) : '';

$customer_id = null;

// Only try to find / create customer if at least one field is filled
if ($customer_name !== '' || $customer_phone !== '' || $customer_id_number !== '') {

    // 1) First try to find by ID NUMBER (our main unique identifier)
    if ($customer_id_number !== '') {
        if ($stmt_lookup = $conn->prepare("SELECT id, customer_name, phone, id_number FROM customers WHERE id_number = ? LIMIT 1")) {
            $stmt_lookup->bind_param("s", $customer_id_number);
            $stmt_lookup->execute();
            $res_lookup = $stmt_lookup->get_result();
            if ($row_c = $res_lookup->fetch_assoc()) {
                $customer_id = (int)$row_c['id'];
            }
            $stmt_lookup->close();
        }
    }

    // 2) If still NOT found, you can optionally try by phone
    if ($customer_id === null && $customer_phone !== '') {
        if ($stmt_lookup = $conn->prepare("SELECT id, id_number FROM customers WHERE phone = ? LIMIT 1")) {
            $stmt_lookup->bind_param("s", $customer_phone);
            $stmt_lookup->execute();
            $res_lookup = $stmt_lookup->get_result();
            if ($row_c = $res_lookup->fetch_assoc()) {
                $customer_id = (int)$row_c['id'];

                // If the record has no id_number yet and we now have one, update it
                if ($customer_id_number !== '' && ($row_c['id_number'] === null || $row_c['id_number'] === '')) {
                    if ($stmt_upd = $conn->prepare("UPDATE customers SET id_number = ? WHERE id = ?")) {
                        $stmt_upd->bind_param("si", $customer_id_number, $customer_id);
                        $stmt_upd->execute();
                        $stmt_upd->close();
                    }
                }
            }
            $stmt_lookup->close();
        }
    }

    // 3) If still not found, INSERT new customer
    if ($customer_id === null) {
        if ($stmt_c = $conn->prepare("
            INSERT INTO customers (customer_name, phone, id_number, created_at)
            VALUES (?, ?, ?, NOW())
        ")) {
            $stmt_c->bind_param("sss", $customer_name, $customer_phone, $customer_id_number);
            if ($stmt_c->execute()) {
                $customer_id = $stmt_c->insert_id;
            } else {
                $errors[] = "Error saving customer details: " . htmlspecialchars($stmt_c->error);
            }
            $stmt_c->close();
        } else {
            $errors[] = "Error preparing customer insert.";
        }
    }
}


    // open/print receipt checkbox
    $openReceipt    = isset($_POST['open_receipt']) && $_POST['open_receipt'] === '1';
    $printRequested = $openReceipt ? 1 : 0;

    // --------- 3) IF ERRORS, DO NOT SAVE ANYTHING ----------
    if (!empty($errors)) {
        $message = "❌ " . implode(' ', $errors);
    } else {
        // --------- 4) WRITE SALES LINES (linked to cash_session_id & customer_id) ----------
        foreach ($validLines as $line) {
            $product_id  = $line['product_id'];
            $qty         = $line['qty'];
            $buy_price   = $line['buy_price'];
            $sell_price  = $line['sell_price'];
            $total       = $line['line_total'];
            $profit      = $line['line_profit'];
            $discount    = $line['line_discount'];
            $new_stock   = $line['stock'] - $qty;

            mysqli_query($conn, "
                INSERT INTO sales(
                    receipt_id,
                    sale_datetime,
                    cashier,
                    product_id,
                    quantity,
                    buying_price,
                    selling_price,
                    discount,
                    total_sale,
                    profit,
                    refunded,
                    customer_id,
                    cash_session_id
                ) VALUES(
                    '$receipt_id',
                    '$datetime',
                    '$cashier',
                    $product_id,
                    $qty,
                    $buy_price,
                    $sell_price,
                    $discount,
                    $total,
                    $profit,
                    0,
                    " . ($customer_id !== null ? (int)$customer_id : "NULL") . ",
                    $cash_session_id
                )
            ");

            mysqli_query($conn, "UPDATE products SET quantity = $new_stock WHERE id = $product_id");
        }

        // --------- 5) WRITE PAYMENT ROW (linked to cash_session_id) ----------
        $amount_due      = $grandTotalLocal;
        $paid_amount_col = $amount_paid;
        $change_amount   = $change;

        if ($stmtPay = $conn->prepare("
            INSERT INTO payments
            (receipt_id, cashier, payment_method, amount_due, paid_at, change_amount, mpesa_code, bank_ref, cash_session_id, print_requested)
            VALUES (?,?,?,?,?,?,?,?,?,?)
        ")) {
            $stmtPay->bind_param(
                "sssdddssii",
                $receipt_id,
                $cashier,
                $payment_method,
                $amount_due,
                $paid_amount_col,
                $change_amount,
                $mpesa_code,
                $bank_ref,
                $cash_session_id,
                $printRequested
            );
            $stmtPay->execute();
            $stmtPay->close();
        }

        // --------- 6) REDIRECT ----------
        if ($openReceipt) {
            header("Location: receipt.php?id=$receipt_id");
        } else {
            header("Location: record_sales.php?msg=Sale%20saved");
        }
        exit();
    }
}

// entries + pagination (unchanged)
$entries_options = [20, 50, 100];
$entries = $_GET['entries'] ?? 20;
$today   = date('Y-m-d');

if ($entries === 'all') {
    $sales_query = "
        SELECT s.*, p.name AS product_name
        FROM sales s
        JOIN products p ON s.product_id = p.id
        WHERE DATE(s.sale_datetime) = '$today'
        ORDER BY s.receipt_id DESC, s.sale_datetime ASC
    ";
} else {
    $entries = intval($entries);
    $page    = $_GET['page'] ?? 1;
    $offset  = ($page - 1) * $entries;

    $sales_query = "
        SELECT s.*, p.name AS product_name
        FROM sales s
        JOIN products p ON s.product_id = p.id
        WHERE DATE(s.sale_datetime) = '$today'
        ORDER BY s.receipt_id DESC, s.sale_datetime ASC
        LIMIT $entries OFFSET $offset
    ";
}
$sales = mysqli_query($conn, $sales_query);

// grand totals
$totals_row = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT SUM(total_sale) AS grand_total_sale,
           SUM(profit)     AS grand_total_profit,
           SUM(discount)   AS grand_total_discount
    FROM sales
    WHERE DATE(sale_datetime) = '$today'
"));
$grand_total_sale     = $totals_row['grand_total_sale'] ?? 0;
$grand_total_profit   = $totals_row['grand_total_profit'] ?? 0;
$grand_total_discount = $totals_row['grand_total_discount'] ?? 0;

// products (must include barcode column in your DB)
$product_list = mysqli_query($conn, "SELECT * FROM products WHERE quantity > 0 ORDER BY name");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <link rel="stylesheet" type="text/css" href="record_sales.css">
</head>
<body>

<div class="cashier-shell">

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

    <main class="cashier-main">

        <!-- TOP BAR with nav + theme toggle -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1>Record sale</h1>
                <small>Capture a new customer transaction and review today’s activity.</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>

        <!-- record sale -->
        <section class="pos-card">
            <div class="pos-card-header">
                <h2>New sale</h2>
                <p>Select products, adjust quantities or prices, then choose payment method and submit.</p>
            </div>

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

            <form method="POST" id="recordSaleForm">
                <!-- PRODUCTS FIRST -->
                <div id="product-rows" class="product-rows">
                    <div class="product-row">
                        <div class="product-select-wrapper">
                            <!-- SEARCH BOX FOR THIS ROW -->
                            <input 
                                type="text"
                                class="product-search-input"
                                placeholder="Search product by name or barcode…"
                            >

                            <select name="product_id[]" class="product-select">
                                <?php while($row = mysqli_fetch_assoc($product_list)): ?>
                                    <?php $barcode = $row['barcode'] ?? ''; ?>
                                    <option value="<?= $row['id'] ?>"
                                            data-price="<?= htmlspecialchars($row['selling_price']) ?>"
                                            data-barcode="<?= htmlspecialchars($barcode) ?>">
                                        <?= $barcode !== '' ? htmlspecialchars($barcode) . ' - ' : '' ?>
                                        <?= htmlspecialchars($row['name']) ?>
                                        (Stock: <?= $row['quantity'] ?>,
                                         Price: <?= number_format($row['selling_price'],2) ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <input type="number" name="quantity[]" placeholder="Quantity" min="1" required>
                        <input type="number" name="sell_price[]" class="sell-price-input"
                               placeholder="Selling price (KES)" step="0.01" required>
                    </div>
                </div>

                <!-- ACTIONS JUST FOR ADDING MORE PRODUCTS -->
                <div class="pos-actions">
                    <button type="button" class="btn-secondary" onclick="addRow()">Add another product</button>
                </div>

                <!-- CUSTOMER DETAILS (OPTIONAL) -->
                <div class="customer-section">
                    <h3><span>👤</span> Customer details (optional)</h3>
                    <p class="hint">Fill these if you want the receipt to show customer info and to track their purchase history.</p>
                    <div class="customer-grid">
                        <input type="text" name="customer_name" placeholder="Customer name">
                        <input type="text" name="customer_phone" placeholder="Phone number">
                        <input type="text" name="customer_id_number" placeholder="ID / Passport number">
                    </div>
                </div>

                <!-- PAYMENT SECTION AFTER ALL PRODUCTS -->
                <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="0"
                                >
                                    KES 0.00
                                </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>

                <!-- FINAL ACTION BUTTONS -->
                <div class="pos-actions" style="margin-top: 18px;">
                    <button type="submit" class="btn-primary">Submit sale and view receipt</button>
                    <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>
                </div>
            </form>
        </section>

        <!-- today's sales -->
        <section class="pos-table-card">
            <div class="pos-table-header">
                <div>
                    <h3>Today’s sales (<?= htmlspecialchars($today) ?>)</h3>
                    <p>Live summary of transactions recorded during this shift.</p>
                </div>

                <form method="GET" class="entries-form">
                    <label>Show</label>
                    <select name="entries" onchange="this.form.submit()">
                        <?php foreach($entries_options as $option): ?>
                            <option value="<?= $option ?>" <?= ($entries == $option) ? 'selected' : '' ?>>
                                <?= $option ?>
                            </option>
                        <?php endforeach; ?>
                            <option value="all" <?= ($entries === 'all') ? 'selected' : '' ?>>All</option>
                    </select>
                    <span style="color:var(--cash-text-muted);">entries</span>
                </form>
            </div>

            <div class="pos-table-wrapper">
                <table class="pos-table">
                    <thead>
                        <tr>
                            <th>Receipt</th>
                            <th>Date</th>
                            <th>Time</th>
                            <th>Cashier</th>
                            <th>Product</th>
                            <th>Qty</th>
                            <th>Selling price</th>
                            <th>Discount</th>
                            <th>Total sale</th>
                            <th>Refund</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $page_total_sale     = 0;
                        $page_total_discount = 0;
                        while($row = mysqli_fetch_assoc($sales)):
                            $page_total_sale     += $row['total_sale'];
                            $page_total_discount += $row['discount'];
                        ?>
                        <tr>
                            <td><?= htmlspecialchars($row['receipt_id']) ?></td>
                            <td><?= date('Y-m-d', strtotime($row['sale_datetime'])) ?></td>
                            <td><?= date('H:i',   strtotime($row['sale_datetime'])) ?></td>
                            <td><?= htmlspecialchars($row['cashier']) ?></td>
                            <td style="text-align:left;"><?= htmlspecialchars($row['product_name']) ?></td>
                            <td><?= $row['quantity'] ?></td>
                            <td><?= number_format($row['selling_price'], 2) ?></td>
                            <td><?= number_format($row['discount'],     2) ?></td>
                            <td><?= number_format($row['total_sale'],   2) ?></td>
                            <td>
                                <?php if($row['refunded'] == 0): ?>
                                    <a href="refund_sale.php?id=<?= $row['id'] ?>"
                                       onclick="return confirm('Refund this sale?');">
                                        <button type="button" class="btn-refund">Refund</button>
                                    </a>
                                <?php else: ?>
                                    <span class="badge-refunded">Refunded</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>

                        <tr class="totals-row">
                            <td colspan="7" style="text-align:right;">Page total</td>
                            <td><?= number_format($page_total_discount, 2) ?></td>
                            <td><?= number_format($page_total_sale,     2) ?></td>
                            <td></td>
                        </tr>
                        <tr class="totals-row">
                            <td colspan="7" style="text-align:right;">Grand total (today)</td>
                            <td><?= number_format($grand_total_discount, 2) ?></td>
                            <td><?= number_format($grand_total_sale,     2) ?></td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>

    </main>
</div>


<script>
let grandTotal = 0;

function syncPriceFromSelect(row) {
    const select     = row.querySelector('select[name="product_id[]"]');
    const priceInput = row.querySelector('input[name="sell_price[]"]');
    if (!select || !priceInput) return;

    const opt = select.options[select.selectedIndex];
    if (!opt) return;

    const price = opt.getAttribute('data-price');
    if (price !== null) {
        const num = parseFloat(price);
        if (!isNaN(num)) {
            priceInput.value = num.toFixed(2);
        }
    }
}

function recalcTotals() {
    const rows = document.querySelectorAll('.product-row');
    let total  = 0;

    rows.forEach(row => {
        const qInput  = row.querySelector('input[name="quantity[]"]');
        const pInput  = row.querySelector('input[name="sell_price[]"]');
        const qty     = qInput ? parseFloat(qInput.value)  || 0 : 0;
        const price   = pInput ? parseFloat(pInput.value)  || 0 : 0;
        total += qty * price;
    });

    grandTotal = total;

    const totalSpan = document.getElementById('grandTotalValue');
    if (totalSpan) {
        totalSpan.dataset.total  = grandTotal.toString();
        totalSpan.textContent    = 'KES ' + grandTotal.toFixed(2);
    }

    updateCashChange();
}

// attachRowEvents with per-row search (name + barcode)
function attachRowEvents(row) {
    const select      = row.querySelector('select[name="product_id[]"]');
    const qtyInput    = row.querySelector('input[name="quantity[]"]');
    const priceInput  = row.querySelector('input[name="sell_price[]"]');
    const searchInput = row.querySelector('.product-search-input');

    let optionsCache = null;

    if (select) {
        // cache options for this row
        optionsCache = Array.from(select.options);
        optionsCache.forEach(opt => opt.hidden = false);

        select.addEventListener('change', function () {
            syncPriceFromSelect(row);
            recalcTotals();
        });

        // initial default price
        syncPriceFromSelect(row);
    }

    if (searchInput && select && optionsCache) {
        searchInput.addEventListener('input', function () {
            const term = this.value.trim().toLowerCase();

            optionsCache.forEach(opt => {
                const text    = opt.textContent.toLowerCase(); // name + label
                const barcode = (opt.getAttribute('data-barcode') || '').toLowerCase();

                // hide if it doesn't match name/text OR barcode
                opt.hidden = term !== '' && !text.includes(term) && !barcode.includes(term);
            });

            // if current selected option is hidden, pick first visible
            const currentSelected = select.selectedOptions[0];
            if (currentSelected && currentSelected.hidden) {
                const firstVisible = optionsCache.find(opt => !opt.hidden);
                if (firstVisible) {
                    select.value = firstVisible.value;
                    syncPriceFromSelect(row);
                    recalcTotals();
                }
            }
        });
    }

    if (qtyInput) {
        qtyInput.addEventListener('input', recalcTotals);
    }
    if (priceInput) {
        priceInput.addEventListener('input', recalcTotals);
    }
}

// make sure new rows also get search + events
function addRow() {
    const firstRow = document.querySelector('.product-row');
    if (!firstRow) return;

    const clone = firstRow.cloneNode(true);

    // clear all inputs in the cloned row (search, qty, price)
    clone.querySelectorAll('input').forEach(input => {
        input.value = '';
    });

    // reset select to first visible option
    const select = clone.querySelector('select[name="product_id[]"]');
    if (select && select.options.length > 0) {
        select.selectedIndex = 0;
    }

    document.getElementById('product-rows').appendChild(clone);
    attachRowEvents(clone);
    recalcTotals();
}

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

function updatePaymentVisibility() {
    const methodRadios = document.querySelectorAll('input[name="payment_method"]');
    const mpesaField   = document.getElementById('mpesaField');
    const bankField    = document.getElementById('bankField');
    const cashField    = document.getElementById('cashField');
    const changeValue  = document.getElementById('changeValue');

    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 updateCashChange() {
    const cashPaid    = document.getElementById('cashPaid');
    const changeValue = document.getElementById('changeValue');
    if (!cashPaid || !changeValue) return;

    const paid   = parseFloat(cashPaid.value) || 0;
    let change   = paid - grandTotal;
    if (isNaN(change)) change = 0;

    if (change < 0) {
        changeValue.textContent = 'KES 0.00';
        changeValue.classList.remove('change-positive');
        changeValue.classList.add('change-zero');
    } else {
        changeValue.textContent = formatKES(change);
        changeValue.classList.remove('change-zero', 'change-positive');
        if (change > 0.0001) {
            changeValue.classList.add('change-positive');
        } else {
            changeValue.classList.add('change-zero');
        }
    }
}

document.addEventListener('DOMContentLoaded', function () {
    // attach to first row
    document.querySelectorAll('.product-row').forEach(attachRowEvents);
    recalcTotals();

    // payment method events
    const methodRadios = document.querySelectorAll('input[name="payment_method"]');
    if (methodRadios.length > 0) {
        methodRadios.forEach(r => {
            r.addEventListener('change', updatePaymentVisibility);
        });
        updatePaymentVisibility();
    }

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

</body>
</html>
