<?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;
        }
    }

    // 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) ----------
        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;

            // make sure your `sales` table has a `cash_session_id` column
            mysqli_query($conn, "
                INSERT INTO sales(
                    receipt_id,
                    sale_datetime,
                    cashier,
                    product_id,
                    quantity,
                    buying_price,
                    selling_price,
                    discount,
                    total_sale,
                    profit,
                    refunded,
                    cash_session_id
                ) VALUES(
                    '$receipt_id',
                    '$datetime',
                    '$cashier',
                    $product_id,
                    $qty,
                    $buy_price,
                    $sell_price,
                    $discount,
                    $total,
                    $profit,
                    0,
                    $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) ----------
        // payments table should have:
        // id, receipt_id, cashier, payment_method,
        // amount_due DECIMAL(10,2),
        // paid_at DECIMAL(10,2),
        // change_amount DECIMAL(10,2),
        // mpesa_code, bank_ref,
        // cash_session_id INT NULL,
        // print_requested TINYINT(1),
        // created_at DATETIME DEFAULT CURRENT_TIMESTAMP

        $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
$product_list = mysqli_query($conn, "SELECT * FROM products WHERE quantity > 0");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        :root {
            /* fallbacks in case not defined in cashier_head */
            --cash-accent-main: var(--cash-accent-main, #22d3ee);
            --cash-accent-soft: var(--cash-accent-soft, #7dd3fc);
        }

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

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

        .pos-card,
        .pos-table-card {
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.10), transparent 55%),
                var(--cash-bg-card);
            border-radius: 18px;
            padding: 18px 22px 20px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: var(--cash-text-main);
            border: 1px solid var(--cash-border-soft);
            margin-bottom: 22px;
        }

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

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

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

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

        .metric-strip {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 10px 0 4px;
        }

        .metric-chip {
            flex: 0 0 auto;
            padding: 8px 14px;
            border-radius: 999px;
            background: rgba(1,22,61,0.75);
            border: 1px solid rgba(130,238,253,0.8);
            font-size: 12px;
        }

        html[data-theme="light"] .metric-chip {
            background: #eff6ff;
            border-color: #bae6fd;
            color: #0f172a;
        }

        .metric-label {
            color: #82EEFD;
            font-weight: 500;
            margin-right: 6px;
        }

        html[data-theme="light"] .metric-label {
            color: #0369a1;
        }

        .metric-value {
            font-weight: 600;
        }

        /* PRODUCT ROWS */

        .product-rows {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 10px;
        }

        .product-row {
            display: grid;
            grid-template-columns: 2.2fr 0.8fr 0.9fr;
            gap: 10px;
        }

        @media (max-width: 900px) {
            .product-row {
                grid-template-columns: 1fr;
            }
        }

        .product-row select,
        .product-row input {
            padding: 9px 11px;
            border-radius: 10px;
            border: 1px solid rgba(130,238,253,0.5);
            background: #0a3d87;
            color: #E9F5FF;
            font-size: 13px;
        }

        .product-row select::placeholder,
        .product-row input::placeholder {
            color: rgba(226,232,240,0.7);
        }

        html[data-theme="light"] .product-row select,
        html[data-theme="light"] .product-row input {
            background: #ffffff;
            border-color: #cbd5f5;
            color: #0f172a;
        }

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

        .product-row select:focus,
        .product-row input:focus {
            outline: none;
            border-color: #00FFE5;
            box-shadow: 0 0 0 1px rgba(0,255,229,0.35);
        }

        html[data-theme="light"] .product-row select:focus,
        html[data-theme="light"] .product-row input:focus {
            border-color: #38bdf8;
            box-shadow: 0 0 0 1px rgba(56,189,248,0.35);
        }

        .product-row select option {
            background: #ffffff;
            color: #0f172a;
        }

        /* PAYMENT SECTION – after products */

        .payment-section {
            margin-top: 18px;
            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 */

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

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

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

        .btn-secondary {
            padding: 9px 16px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.7);
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            background: rgba(0,26,80,0.4);
            color: #E9F5FF;
        }

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

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

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

        .back-link {
            margin-left: auto;
            text-decoration: none;
            font-size: 13px;
            color: var(--cash-accent-soft);
        }

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

        /* TABLE SECTION (unchanged) */

        .pos-table-card {
            margin-top: 4px;
        }

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

        .pos-table-header h3 {
            font-size: 17px;
            font-weight: 600;
        }

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

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

        .entries-form {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
        }

        .entries-form label {
            color: var(--cash-text-muted);
        }

        .entries-form select {
            padding: 7px 11px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.6);
            background: #063d8c;
            color: #E9F5FF;
            font-size: 13px;
        }

        html[data-theme="light"] .entries-form select {
            background: #ffffff;
            border-color: #cbd5f5;
            color: #0f172a;
        }

        .pos-table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 6px;
        }

        table.pos-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
            min-width: 900px;
        }

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

        .pos-table th {
            background: #012a73;
            position: sticky;
            top: 0;
            z-index: 1;
            font-weight: 600;
        }

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

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

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

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

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

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

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

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

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

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

        .badge-refunded {
            font-size: 11px;
            padding: 4px 9px;
            border-radius: 999px;
            background: rgba(16,185,129,0.14);
            color: #6ee7b7;
        }

        html[data-theme="light"] .badge-refunded {
            background: #dcfce7;
            color: #166534;
        }

        .btn-refund {
            padding: 5px 10px;
            border-radius: 999px;
            border: none;
            background: #EF4444;
            color: #FFFBF5;
            font-size: 12px;
            cursor: pointer;
        }

        .btn-refund:hover {
            background: #DC2626;
        }

        /* MESSAGE BAR */
        .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;
        }
    </style>
</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">
                        <select name="product_id[]" class="product-select">
                            <?php while($row = mysqli_fetch_assoc($product_list)): ?>
                                <option value="<?= $row['id'] ?>"
                                        data-price="<?= htmlspecialchars($row['selling_price']) ?>">
                                    <?= htmlspecialchars($row['name']) ?>
                                    (Stock: <?= $row['quantity'] ?>,
                                     Price: <?= number_format($row['selling_price'],2) ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                        <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>

                <!-- 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();
}

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[]"]');

    if (select) {
        select.addEventListener('change', function () {
            syncPriceFromSelect(row); // default price when product changes
            recalcTotals();
        });
        // initial default price
        syncPriceFromSelect(row);
    }

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

function addRow() {
    const firstRow = document.querySelector('.product-row');
    if (!firstRow) return;

    const clone = firstRow.cloneNode(true);

    // clear quantity & price so new row is clean
    clone.querySelectorAll('input').forEach(input => {
        input.value = '';
    });

    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>
