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

require 'db_connect.php';

date_default_timezone_set('Africa/Nairobi');

$page_title = "Credit Sales | Cashier POS";
$active     = 'debts';

$message = "";

/* -------------------------------
   PAGINATION + SHOW X ENTRIES
--------------------------------- */
$limit_options = [10, 15, 25, 50, 100, 0]; // 0 = All
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 15;
if (!in_array($limit, $limit_options, true)) {
    $limit = 15;
}
$page  = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

if ($limit > 0) {
    $offset = ($page - 1) * $limit;
} else {
    $offset = 0;
    $page   = 1;
}

// Count total credit sales records
$countResult = $conn->query("SELECT COUNT(*) AS total FROM customer_debts");
$totalRows   = (int)($countResult->fetch_assoc()['total'] ?? 0);
$totalPages  = ($limit > 0 && $totalRows > 0) ? max(1, (int)ceil($totalRows / $limit)) : 1;

/* -------------------------------
   LOAD PRODUCTS (FOR DROPDOWN & SCAN)
--------------------------------- */
$productsData = [];
$productsResult = $conn->query("
    SELECT id, name, quantity, selling_price, barcode
    FROM products
    WHERE quantity > 0
    ORDER BY name ASC
");
if ($productsResult) {
    while ($row = $productsResult->fetch_assoc()) {
        $productsData[] = $row;
    }
}

/* -------------------------------
   ADD NEW CREDIT SALE (MULTIPLE PRODUCTS)
--------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_debt'])) {
    $customer   = trim($_POST['customer_name'] ?? '');
    $phone      = trim($_POST['phone'] ?? '');
    $note       = trim($_POST['items'] ?? '');

    $product_ids = $_POST['product_id'] ?? [];
    $quantities  = $_POST['quantity'] ?? [];
    $discounts   = $_POST['discount'] ?? [];

    // Build valid product lines
    $lines = [];
    if (is_array($product_ids)) {
        $countLines = count($product_ids);
        for ($i = 0; $i < $countLines; $i++) {
            $pid  = isset($product_ids[$i]) ? (int)$product_ids[$i] : 0;
            $qty  = isset($quantities[$i]) ? (int)$quantities[$i] : 0;
            $disc = isset($discounts[$i]) ? (float)$discounts[$i] : 0.0;

            if ($pid > 0 && $qty > 0) {
                $lines[] = [
                    'product_id' => $pid,
                    'qty'        => $qty,
                    'discount'   => $disc,
                ];
            }
        }
    }

    if ($customer === '' || empty($lines)) {
        $message = "<div class='alert alert-error'>❌ Please provide a customer name and at least one valid product line.</div>";
    } else {
        // Collect unique product IDs
        $productIdList = array_values(array_unique(array_column($lines, 'product_id')));

        if (empty($productIdList)) {
            $message = "<div class='alert alert-error'>❌ Please select at least one product.</div>";
        } else {
            // Fetch all needed products in one query
            $placeholders = implode(',', array_fill(0, count($productIdList), '?'));
            $types        = str_repeat('i', count($productIdList));

            $stmtProd = $conn->prepare("
                SELECT id, name, quantity, selling_price
                FROM products
                WHERE id IN ($placeholders)
            ");
            $stmtProd->bind_param($types, ...$productIdList);
            $stmtProd->execute();
            $resultProd = $stmtProd->get_result();

            $productMap = [];
            while ($pRow = $resultProd->fetch_assoc()) {
                $productMap[(int)$pRow['id']] = $pRow;
            }
            $stmtProd->close();

            // Validate products exist
            $missingProduct = false;
            foreach ($lines as $line) {
                if (!isset($productMap[$line['product_id']])) {
                    $missingProduct = true;
                    break;
                }
            }

            if ($missingProduct) {
                $message = "<div class='alert alert-error'>❌ One or more selected products were not found.</div>";
            } else {
                // Check stock per product (sum qty if multiple lines of same product)
                $requestedPerProduct = [];
                foreach ($lines as $line) {
                    $pid = $line['product_id'];
                    if (!isset($requestedPerProduct[$pid])) {
                        $requestedPerProduct[$pid] = 0;
                    }
                    $requestedPerProduct[$pid] += $line['qty'];
                }

                $stockError = '';
                foreach ($requestedPerProduct as $pid => $reqQty) {
                    $available = (int)$productMap[$pid]['quantity'];
                    if ($reqQty > $available) {
                        $stockError = "❌ Not enough stock for <strong>" . htmlspecialchars($productMap[$pid]['name']) . "</strong>. Requested: $reqQty, Available: $available.";
                        break;
                    }
                }

                if ($stockError !== '') {
                    $message = "<div class='alert alert-error'>$stockError</div>";
                } else {
                    // Compute totals
                    $total_amount         = 0.0;
                    $total_quantity       = 0;
                    $total_discount_value = 0.0;
                    $items_desc_lines     = [];

                    foreach ($lines as $line) {
                        $pid  = $line['product_id'];
                        $qty  = $line['qty'];
                        $disc = $line['discount'];

                        $prod = $productMap[$pid];
                        $unitPrice     = (float)$prod['selling_price'];
                        $effectiveUnit = $unitPrice - $disc;
                        if ($effectiveUnit < 0) $effectiveUnit = 0;

                        $lineAmount = $effectiveUnit * $qty;

                        $total_amount         += $lineAmount;
                        $total_quantity       += $qty;
                        $total_discount_value += ($disc * $qty);

                        $items_desc_lines[] = $prod['name'] . " x $qty @ " .
                            number_format($unitPrice, 2) .
                            ($disc > 0 ? (" less " . number_format($disc, 2) . " per unit") : "");
                    }

                    // Average discount per unit
                    $avg_discount = ($total_quantity > 0)
                        ? ($total_discount_value / $total_quantity)
                        : 0.0;

                    // Use first product as primary product reference
                    $primary_product_id = $lines[0]['product_id'] ?? 0;

                    // Combined description (all products + optional note)
                    $items_combined = implode("; ", $items_desc_lines);
                    if ($note !== '') {
                        $items_combined .= ($items_combined ? " | " : "") . "Note: " . $note;
                    }

                    // 1) Insert debt WITHOUT receipt_no first
                    $stmt = $conn->prepare("
                        INSERT INTO customer_debts 
                            (customer_name, phone, product_id, quantity, items, amount, discount)
                        VALUES (?, ?, ?, ?, ?, ?, ?)
                    ");

                    if ($stmt) {
                        $stmt->bind_param(
                            "ssiisdd",
                            $customer,
                            $phone,
                            $primary_product_id,
                            $total_quantity,
                            $items_combined,
                            $total_amount,
                            $avg_discount
                        );

                        if ($stmt->execute()) {
                            $debt_id = $stmt->insert_id;
                            $stmt->close();

                            // 2) Generate receipt number based on ID
                            // e.g. CR20260102-0005
                            $receipt_no = 'CR' . date('Ymd') . '-' . str_pad((string)$debt_id, 4, '0', STR_PAD_LEFT);

                            $upd = $conn->prepare("UPDATE customer_debts SET receipt_no = ? WHERE id = ?");
                            if ($upd) {
                                $upd->bind_param("si", $receipt_no, $debt_id);
                                $upd->execute();
                                $upd->close();
                            }

                            // 3) Update stock for each product
                            foreach ($requestedPerProduct as $pid => $reqQty) {
                                $new_stock = (int)$productMap[$pid]['quantity'] - $reqQty;
                                $updStock = $conn->prepare("UPDATE products SET quantity = ? WHERE id = ?");
                                if ($updStock) {
                                    $updStock->bind_param("ii", $new_stock, $pid);
                                    $updStock->execute();
                                    $updStock->close();
                                }
                            }

                            header("Location: customer_debts.php?added=1");
                            exit();
                        } else {
                            $message = "<div class='alert alert-error'>❌ Error saving credit sale: " . htmlspecialchars($stmt->error) . "</div>";
                            $stmt->close();
                        }
                    } else {
                        $message = "<div class='alert alert-error'>❌ Error preparing statement: " . htmlspecialchars($conn->error) . "</div>";
                    }
                }
            }
        }
    }
}

/* -------------------------------
   DELETE A CREDIT SALE RECORD
--------------------------------- */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    if ($id > 0) {
        $conn->query("DELETE FROM customer_debts WHERE id = $id");
    }
    header("Location: customer_debts.php?deleted=1");
    exit();
}

/* -------------------------------
   FETCH PAGINATED CREDIT SALES
--------------------------------- */
$sql = "
    SELECT d.*, p.name AS product_name,
           COALESCE(SUM(dp.amount_paid), 0) AS total_paid
    FROM customer_debts d
    LEFT JOIN products p ON d.product_id = p.id
    LEFT JOIN debt_payments dp ON d.id = dp.debt_id
    GROUP BY d.id
    ORDER BY d.debt_date DESC
";

if ($limit > 0) {
    $sql .= " LIMIT $limit OFFSET $offset";
}

$debts = $conn->query($sql);

// Grand total outstanding
$grand_total_query = $conn->query("
    SELECT SUM(amount - COALESCE((SELECT SUM(amount_paid) FROM debt_payments WHERE debt_id = customer_debts.id), 0)) AS grand_total
    FROM customer_debts
");
$grand_total = (float)($grand_total_query->fetch_assoc()['grand_total'] ?? 0);

// Grand total discount
$grand_discount_query = $conn->query("
    SELECT SUM(COALESCE(discount, 0) * quantity) AS grand_discount_total
    FROM customer_debts
");
$grand_discount_total = (float)($grand_discount_query->fetch_assoc()['grand_discount_total'] ?? 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        /* Layout for footer at bottom */
        html, body { height: 100%; }
        body {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .cashier-shell {
            flex: 1;
            display: flex;
        }

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

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

        .pos-card,
        .pos-table-card {
            background: linear-gradient(135deg, #064ab8 0%, #022a6b 55%, #021d53 100%);
            border-radius: 18px;
            padding: 18px 22px 22px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: #E9F5FF;
            border: 1px solid rgba(130,238,253,0.5);
            margin-bottom: 22px;
        }

        html[data-theme="light"] .pos-card,
        html[data-theme="light"] .pos-table-card {
            background: #ffffff;
            border-color: rgba(148,163,184,0.55);
            color: #0f172a;
            box-shadow: 0 12px 26px rgba(15,23,42,0.12);
        }

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

        .pos-card-header p {
            font-size: 13px;
            color: #c3d8ff;
            margin-top: 4px;
        }

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

        .debt-form {
            margin-top: 14px;
            max-width: 820px;
        }

        .debt-form label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 4px;
            color: #E9F5FF;
        }

        html[data-theme="light"] .debt-form label {
            color: #0f172a;
        }

        .debt-form input,
        .debt-form textarea,
        .debt-form select {
            width: 100%;
            padding: 9px 11px;
            border-radius: 10px;
            border: 1px solid rgba(130,238,253,0.5);
            background: #0a3d87;
            color: #E9F5FF;
            font-size: 13px;
            margin-bottom: 10px;
        }

        .debt-form textarea {
            resize: vertical;
        }

        .debt-form input::placeholder,
        .debt-form textarea::placeholder {
            color: rgba(226,232,240,0.7);
        }

        html[data-theme="light"] .debt-form input,
        html[data-theme="light"] .debt-form textarea,
        html[data-theme="light"] .debt-form select {
            background: #ffffff;
            border-color: rgba(148,163,184,0.55);
            color: #0f172a;
        }

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

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

        .btn-primary {
            padding: 10px 18px;
            border-radius: 999px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            background: var(--cash-accent-turquoise);
            color: #011b35;
            margin-top: 4px;
        }

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

        .btn-secondary-inline {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 7px 14px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.6);
            background: rgba(15,23,42,0.9);
            color: #E9F5FF;
            font-size: 12px;
            cursor: pointer;
            margin-bottom: 8px;
        }

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

        .alert {
            margin-bottom: 10px;
            padding: 8px 10px;
            border-radius: 10px;
            font-size: 13px;
            border-left-width: 4px;
            border-left-style: solid;
        }

        .alert-success {
            background: rgba(34,197,94,0.12);
            border-left-color: rgba(34,197,94,0.9);
            color: #bbf7d0;
        }

        .alert-error {
            background: rgba(239,68,68,0.14);
            border-left-color: rgba(248,113,113,0.95);
            color: #fecaca;
        }

        html[data-theme="light"] .alert-success {
            background: #dcfce7;
            border-left-color: #16a34a;
            color: #166534;
        }

        html[data-theme="light"] .alert-error {
            background: #fee2e2;
            border-left-color: #ef4444;
            color: #b91c1c;
        }

        .product-lines-header {
            font-size: 13px;
            margin-bottom: 6px;
            opacity: 0.9;
        }

        .product-line {
            display: grid;
            grid-template-columns: minmax(0,3fr) minmax(0,2fr) minmax(0,1fr) minmax(0,1fr) auto;
            gap: 8px;
            margin-bottom: 6px;
        }

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

        .product-line small {
            font-size: 11px;
            opacity: 0.8;
        }

        .remove-line-btn {
            padding: 6px 10px;
            border-radius: 999px;
            border: 1px solid rgba(239,68,68,0.7);
            background: rgba(239,68,68,0.18);
            color: #fecaca;
            font-size: 11px;
            cursor: pointer;
        }

        html[data-theme="light"] .remove-line-btn {
            background: #fee2e2;
            border-color: #f87171;
            color: #b91c1c;
        }

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

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

        .pos-table-header p {
            font-size: 12px;
            color: #c3d8ff;
            margin-top: 2px;
        }

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

        .pos-controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
            align-items: flex-end;
        }

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

        .entries-form label {
            color: #c3d8ff;
        }

        html[data-theme="light"] .entries-form label {
            color: #4b5563;
        }

        .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: #eff6ff;
            border-color: rgba(148,163,184,0.7);
            color: #0f172a;
        }

        .badge-muted {
            font-size: 11px;
            padding: 4px 9px;
            border-radius: 999px;
            background: rgba(15,23,42,0.86);
            color: #c3d8ff;
        }

        html[data-theme="light"] .badge-muted {
            background: #e5f3ff;
            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: 1100px;
        }

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

        .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); }

        .cell-left { text-align: left; }

        .empty-row {
            padding: 18px;
            color: #c3d8ff;
            text-align: center;
        }

        /* Light theme table overrides */
        html[data-theme="light"] .pos-table th,
        html[data-theme="light"] .pos-table td {
            color: #0f172a;
            border-bottom-color: rgba(148,163,184,0.35);
        }

        html[data-theme="light"] .pos-table th {
            background: #e5f3ff;
        }

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

        .record-btn,
        .delete-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 5px 10px;
            font-size: 12px;
            border-radius: 999px;
            text-decoration: none;
            border: 1px solid transparent;
            margin: 0 2px;
        }

        .record-btn {
            background: rgba(59,130,246,0.16);
            border-color: rgba(59,130,246,0.7);
            color: #bfdbfe;
        }

        .record-btn:hover {
            background: rgba(59,130,246,0.3);
        }

        .delete-btn {
            background: rgba(239,68,68,0.16);
            border-color: rgba(239,68,68,0.8);
            color: #fecaca;
        }

        .delete-btn:hover {
            background: rgba(239,68,68,0.3);
        }

        html[data-theme="light"] .record-btn {
            background: #e0f2fe;
            border-color: #60a5fa;
            color: #1d4ed8;
        }

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

        html[data-theme="light"] .delete-btn {
            background: #fee2e2;
            border-color: #f87171;
            color: #b91c1c;
        }

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

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

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

        .pagination {
            margin-top: 14px;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;
        }

        .page-btn {
            padding: 7px 12px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.7);
            background: rgba(0,26,80,0.4);
            color: #E9F5FF;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
        }

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

        .page-btn.active {
            background: var(--cash-accent-turquoise);
            border-color: var(--cash-accent-turquoise);
            color: #011b35;
            font-weight: 700;
        }

        html[data-theme="light"] .page-btn {
            background: #eff6ff;
            border-color: rgba(148,163,184,0.7);
            color: #0f172a;
        }

        html[data-theme="light"] .page-btn.active {
            background: #0ea5e9;
            color: #f9fafb;
        }

        .back-link {
            text-decoration: none;
            font-size: 13px;
            color: #82EEFD;
        }

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

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

        footer {
            background: transparent;
            text-align: center;
            font-size: 12px;
            color: var(--cash-text-muted);
            padding: 10px 18px;
            margin-top: auto;
        }

        @media (max-width: 900px) {
            .pos-controls {
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>

<div class="cashier-shell">
    <?php include "cashier_sidebar.php"; ?>

    <main class="cashier-main">

        <!-- Topbar -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1><?= htmlspecialchars($page_title) ?></h1>
                <small>Record credit sales and track outstanding balances per customer.</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="transaction_history.php" class="<?= ($active === 'transactions') ? 'active' : '' ?>">Transactions</a>
                    <a href="customers.php" class="<?= ($active === 'customers') ? 'active' : '' ?>">Customers</a>
                    <a href="add_expense.php" class="<?= ($active === 'expenses') ? 'active' : '' ?>">Expenses</a>
                    <a href="customer_debts.php" class="<?= ($active === 'debts') ? 'active' : '' ?>">Credit Sales</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" onclick="toggleCashierSidebar()">☰</button>
            </div>
        </div>

        <!-- Add credit sale form -->
        <section class="pos-card">
            <div class="pos-card-header">
                <h2>Record a new credit sale</h2>
                <p>Select multiple products, quantities and discounts. Stock will be reduced automatically.</p>
            </div>

            <?php if (isset($_GET['added'])): ?>
                <div class="alert alert-success">✔ Credit sale recorded successfully (stock updated).</div>
            <?php endif; ?>

            <?php if (isset($_GET['deleted'])): ?>
                <div class="alert alert-success">✔ Credit sale record deleted successfully.</div>
            <?php endif; ?>

            <?php if ($message): ?>
                <?= $message ?>
            <?php endif; ?>

            <form method="POST" class="debt-form" autocomplete="off">
                <label for="customer_name">Customer name</label>
                <input type="text" id="customer_name" name="customer_name" required>

                <label for="phone">Phone number</label>
                <input type="text" id="phone" name="phone" placeholder="Optional">

                <div style="margin-top:10px;margin-bottom:4px;" class="product-lines-header">
                    Products on credit (scan or select)
                </div>

                <button type="button" class="btn-secondary-inline" onclick="addProductLine()">
                    + Add another product
                </button>

                <div id="productLinesContainer"></div>

                <label for="items">Description / note (optional)</label>
                <textarea id="items" name="items" rows="2" placeholder="e.g. customer will pay at month end"></textarea>

                <button type="submit" name="add_debt" class="btn-primary">Record credit sale</button>
            </form>
        </section>

        <!-- Credit sales table -->
        <section class="pos-table-card">
            <div class="pos-table-header">
                <div>
                    <h3>Credit sales</h3>
                    <p>
                        <?= $totalRows ? "Showing page $page of $totalPages" : "No credit sales recorded yet." ?>
                    </p>
                </div>

                <div class="pos-controls">
                    <span class="badge-muted">
                        Grand outstanding: KES <?= number_format($grand_total, 2) ?>
                    </span>
                    <span class="badge-muted">
                        Grand discounts: KES <?= number_format($grand_discount_total, 2) ?>
                    </span>

                    <form method="GET" class="entries-form">
                        <label>Show</label>
                        <select name="limit" onchange="this.form.submit()">
                            <?php foreach ([10, 15, 25, 50, 100, 0] as $opt): ?>
                                <option value="<?= $opt ?>" <?= ($limit === $opt) ? 'selected' : '' ?>>
                                    <?= $opt === 0 ? 'All' : $opt ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <span style="color:var(--cash-text-muted);">entries</span>
                    </form>
                </div>
            </div>

            <div class="pos-table-wrapper">
                <table class="pos-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Receipt #</th>
                            <th>Customer</th>
                            <th>Phone</th>
                            <th>Products / Items</th>
                            <th>Total Qty</th>
                            <th>Outstanding (KES)</th>
                            <th>Discount total (KES)</th>
                            <th>Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $page_total          = 0;
                        $page_discount_total = 0;

                        if ($debts && $debts->num_rows > 0):
                            while($row = $debts->fetch_assoc()):
                                $unit_discount   = isset($row['discount']) ? (float)$row['discount'] : 0;
                                $total_discount  = $unit_discount * (int)$row['quantity'];
                                $outstanding     = (float)$row['amount'] - (float)$row['total_paid'];

                                $page_total          += $outstanding;
                                $page_discount_total += $total_discount;

                                $receiptNo = $row['receipt_no'] ?? '';

                                // show ALL products from items field
                                $itemsRaw  = $row['items'] ?? '';
                                // split by "; " into separate lines
                                $itemsRaw  = str_replace('; ', "\n", $itemsRaw);
                                $itemsHtml = nl2br(htmlspecialchars($itemsRaw));
                        ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>
                                <td><?= htmlspecialchars($receiptNo) ?></td>
                                <td><?= htmlspecialchars($row['customer_name']) ?></td>
                                <td><?= htmlspecialchars($row['phone']) ?></td>
                                <td class="cell-left">
                                    <?= $itemsHtml ?>
                                </td>
                                <td><?= (int)$row['quantity'] ?></td>
                                <td><?= number_format($outstanding, 2) ?></td>
                                <td><?= number_format($total_discount, 2) ?></td>
                                <td><?= htmlspecialchars($row['debt_date']) ?></td>
                                <td>
                                    <a class="record-btn" href="cashier_record_debt_payments.php?id=<?= (int)$row['id'] ?>">
                                        Record payment
                                    </a>
                                    <a class="delete-btn"
                                       onclick="return confirm('Delete this credit sale record?');"
                                       href="customer_debts.php?delete=<?= (int)$row['id'] ?>">
                                        Delete
                                    </a>
                                </td>
                            </tr>
                        <?php
                            endwhile;
                        ?>

                            <!-- Page Totals -->
                            <tr class="totals-row">
                                <td colspan="6" style="text-align:right;">Total outstanding (this page)</td>
                                <td><?= number_format($page_total, 2) ?></td>
                                <td><?= number_format($page_discount_total, 2) ?></td>
                                <td colspan="2"></td>
                            </tr>

                            <!-- Grand Totals -->
                            <tr class="totals-row">
                                <td colspan="6" style="text-align:right;">Grand total outstanding</td>
                                <td><?= number_format($grand_total, 2) ?></td>
                                <td><?= number_format($grand_discount_total, 2) ?></td>
                                <td colspan="2"></td>
                            </tr>

                        <?php else: ?>
                            <tr>
                                <td colspan="10" class="empty-row">No credit sales found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- PAGINATION -->
            <?php if($limit > 0 && $totalPages > 1): ?>
                <div class="pagination">
                    <?php for($i = 1; $i <= $totalPages; $i++): ?>
                        <a class="page-btn <?= ($i == $page) ? 'active' : '' ?>"
                           href="?page=<?= $i ?>&limit=<?= $limit ?>">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>
                </div>
            <?php endif; ?>

            <div style="margin-top:14px;">
                <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>
            </div>
        </section>

    </main>
</div>

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

<script>
function toggleCashierSidebar() {
    const sidebar = document.getElementById('cashierSidebar');
    if (sidebar) {
        sidebar.classList.toggle('is-collapsed');
    }
}

// ---- Products data for JS (for scanning + dynamic rows) ----
const productsData = <?php echo json_encode($productsData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?> || [];
const barcodeMap = {};
productsData.forEach(p => {
    if (p.barcode && p.barcode !== '') {
        barcodeMap[String(p.barcode)] = p.id;
    }
});

let productLineIndex = 0;

function createProductLineRow() {
    const container = document.createElement('div');
    container.className = 'product-line';
    container.dataset.index = productLineIndex;

    const selectOptions = ['<option value="">-- choose product --</option>']
        .concat(productsData.map(p => {
            const name  = p.name.replace(/"/g, '&quot;');
            const price = parseFloat(p.selling_price || 0).toFixed(2);
            const qty   = parseInt(p.quantity || 0, 10);
            return `<option value="${p.id}">${name} — KES ${price} (Stock: ${qty})</option>`;
        })).join('');

    container.innerHTML = `
        <div>
            <select name="product_id[]" required>
                ${selectOptions}
            </select>
            <small>Select product</small>
        </div>
        <div>
            <input type="text" name="barcode_scan[]" placeholder="Scan barcode (optional)"
                   onchange="handleBarcodeScan(this)">
            <small>Scan to auto-select product</small>
        </div>
        <div>
            <input type="number" name="quantity[]" min="1" value="1" required>
            <small>Quantity</small>
        </div>
        <div>
            <input type="number" step="0.01" name="discount[]" value="0">
            <small>Discount per unit (KES)</small>
        </div>
        <div>
            <button type="button" class="remove-line-btn" onclick="removeProductLine(this)">✕</button>
        </div>
    `;

    productLineIndex++;
    return container;
}

function addProductLine() {
    const container = document.getElementById('productLinesContainer');
    if (!container) return;
    container.appendChild(createProductLineRow());
}

function removeProductLine(btn) {
    const row = btn.closest('.product-line');
    if (!row) return;
    const container = document.getElementById('productLinesContainer');
    if (container && container.children.length > 1) {
        container.removeChild(row);
    } else if (container && container.children.length === 1) {
        // If only one row, just clear fields
        const selects = row.querySelectorAll('select');
        const inputs  = row.querySelectorAll('input');
        selects.forEach(s => s.value = '');
        inputs.forEach(i => {
            if (i.name === 'quantity[]') i.value = '1';
            else i.value = '';
        });
    }
}

function handleBarcodeScan(inputEl) {
    const code = (inputEl.value || '').trim();
    if (!code) return;
    const pid = barcodeMap[code];
    if (!pid) {
        alert('No product found for barcode: ' + code);
        return;
    }

    const row = inputEl.closest('.product-line');
    if (!row) return;
    const select = row.querySelector('select[name="product_id[]"]');
    if (select) {
        select.value = String(pid);
    }
}

// Initialize one line on page load
document.addEventListener('DOMContentLoaded', function() {
    addProductLine();
});
</script>

</body>
</html>
