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

        $errors = [];

        /* --------- 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 create / lookup customer if at least one field is filled
        if ($customer_name !== '' || $customer_phone !== '' || $customer_id_number !== '') {

            // Try to find existing customer by phone or ID number
            $lookup_sql   = "SELECT id FROM customers WHERE 1=0";
            $lookup_types = "";
            $lookup_args  = [];

            if ($customer_phone !== '') {
                $lookup_sql   .= " OR phone = ?";
                $lookup_types .= "s";
                $lookup_args[] = $customer_phone;
            }
            if ($customer_id_number !== '') {
                $lookup_sql   .= " OR id_number = ?";
                $lookup_types .= "s";
                $lookup_args[] = $customer_id_number;
            }

            if ($lookup_types !== '') {
                if ($stmt_lookup = $conn->prepare($lookup_sql)) {
                    $stmt_lookup->bind_param($lookup_types, ...$lookup_args);
                    $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();
                }
            }

            // If 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.";
                }
            }
        }
        /* --------- END CUSTOMER LOGIC ---------- */

        /* --------- 3) 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 cart.";
        } else {
            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 + optional customer_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);

                // Ensure your `sales` table has a nullable INT column `customer_id`
                $stmt = $conn->prepare(
                    "INSERT INTO sales 
                     (receipt_id, sale_datetime, cashier, cash_session_id, customer_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(
                    "sssiiidddddd",
                    $receiptId,
                    $now,
                    $cashier,
                    $cashSessionId,
                    $customer_id,
                    $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, NO customer_id column here) ----------
            $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'; ?>
    <link rel="stylesheet" href="scan_sales.css">
</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, capture optional customer details, choose payment method, and finalise the sale.</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>

                        <!-- OPTIONAL CUSTOMER DETAILS -->
                        <div class="customer-section">
                            <h3><span>👤</span> Customer details (optional)</h3>
                            <div class="customer-grid">
                                <div class="customer-field">
                                    <span class="label">Customer name</span>
                                    <input
                                        type="text"
                                        name="customer_name"
                                        placeholder="e.g. John Doe"
                                    >
                                </div>
                                <div class="customer-field">
                                    <span class="label">Phone number</span>
                                    <input
                                        type="text"
                                        name="customer_phone"
                                        placeholder="e.g. 07xx xxx xxx"
                                    >
                                </div>
                                <div class="customer-field">
                                    <span class="label">ID / Passport No.</span>
                                    <input
                                        type="text"
                                        name="customer_id_number"
                                        placeholder="e.g. 12345678"
                                    >
                                </div>
                            </div>
                        </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>
