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

require 'db_connect.php';
date_default_timezone_set('Africa/Nairobi');

$message    = "";
$page_title = "Credit Sales | Admin POS";

/* -------------------------------
   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)
            ");
            if (!$stmtProd) {
                $message = "<div class='alert alert-error'>❌ Error preparing product lookup: " . htmlspecialchars($conn->error) . "</div>";
            } else {
                $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 (same pattern as cashier)
                                $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: admin_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 insert: " . 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: admin_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>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include('head.php'); ?>

    <style>
        body {
            font-family: 'Poppins', Arial, sans-serif;
            background: var(--bg-main);
            margin: 0;
            color: var(--text-main);
        }

        /* MAIN WRAPPER (matches other pages) */
        .content-wrapper {
            margin-left: 260px;
            padding: 24px 30px 32px;
            background: var(--bg-main);
            min-height: 100vh;
            box-sizing: border-box;
            transition: margin-left 0.3s ease;
        }

        .content-wrapper.fullwidth {
            margin-left: 0;
        }

        @media (max-width: 768px) {
            .content-wrapper {
                margin-left: 0;
                padding: 18px 18px 26px;
            }
        }

        /* SIDEBAR HIDE CLASS */
        #sidebar.hidden {
            display: none;
        }

        /* TOP BAR (shared style) */
        .topbar {
            background: var(--bg-sidebar);
            padding: 14px 18px;
            margin-bottom: 20px;
            border-radius: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid #B8860B;
            box-shadow: 0 6px 18px rgba(0,0,0,0.5);
            color: brown;
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 13px;
        }

        .topbar-title {
            font-weight: 600;
            font-size: 15px;
            letter-spacing: 0.03em;
        }

        .menu-btn {
            font-size: 22px;
            cursor: pointer;
            color: var(--accent-gold, #f4b400);
            transition: 0.3s;
            line-height: 1;
        }

        .menu-btn:hover {
            color: #e6c34b;
        }

        .theme-toggle {
            border-radius: 999px;
            border: 1px solid rgba(184,134,11,0.7);
            padding: 6px 12px;
            background: rgba(0,0,0,0.4);
            color: #f9f9f9;
            font-size: 12px;
            cursor: pointer;
        }

        .theme-toggle:hover {
            background: rgba(0,0,0,0.65);
        }

        .topbar-user strong {
            font-weight: 600;
        }

        @media (max-width: 900px) {
            .topbar {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
        }

        /* Page header */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 18px;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            color: var(--text-heading);
        }

        .page-subtitle {
            font-size: 13px;
            color: var(--accent-gold);
            margin-top: 3px;
        }

        /* Metrics bar */
        .metrics-row {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 14px;
            margin-bottom: 18px;
        }

        @media (max-width: 992px) {
            .metrics-row {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }
        }

        @media (max-width: 600px) {
            .metrics-row {
                grid-template-columns: minmax(0, 1fr);
            }
        }

        .metric-card {
            background: var(--bg-card);
            border-radius: 12px;
            padding: 10px 14px;
            border: 1px solid #0a4a85;
            box-shadow: 0 4px 12px rgba(0,0,0,0.28);
        }

        body[data-theme="light"] .metric-card {
            border-color: rgba(148,163,184,0.6);
            box-shadow: 0 8px 20px rgba(15,23,42,0.06);
        }

        .metric-label {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            opacity: 0.75;
            margin-bottom: 4px;
        }

        .metric-value {
            font-size: 17px;
            font-weight: 600;
        }

        .metric-subtext {
            font-size: 11px;
            opacity: 0.8;
            margin-top: 2px;
        }

        /* Cards */
        .card {
            background: var(--bg-card);
            border-radius: 14px;
            padding: 18px 20px 22px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.35);
            border: 1px solid #0a4a85;
            color: var(--text-main);
            margin-bottom: 20px;
        }

        body[data-theme="light"] .card {
            border-color: rgba(148,163,184,0.6);
            box-shadow: 0 10px 24px rgba(15,23,42,0.08);
        }

        .card-title-row {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            gap: 8px;
            margin-bottom: 12px;
        }

        .card-title {
            font-size: 16px;
            font-weight: 500;
            color: var(--text-heading);
        }

        .card-subtitle {
            font-size: 12px;
            opacity: 0.8;
        }

        /* Alerts */
        .alert {
            padding: 9px 11px;
            border-radius: 8px;
            margin-bottom: 10px;
            font-size: 13px;
            border-left: 4px solid transparent;
        }

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

        .alert-error {
            background: rgba(239,68,68,0.12);
            border-left-color: #ef4444;
            color: #fecaca;
        }

        body[data-theme="light"] .alert-success {
            background: #dcfce7;
            color: #166534;
        }

        body[data-theme="light"] .alert-error {
            background: #fee2e2;
            color: #991b1b;
        }

        /* Form styling (multi product) */
        .debt-form label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 4px;
            color: var(--text-main);
        }

        .debt-form input,
        .debt-form textarea,
        .debt-form select {
            width: 100%;
            padding: 8px 10px;
            border-radius: 8px;
            border: 1px solid #0a4a85;
            background: var(--bg-table-head);
            color: var(--text-main);
            font-size: 13px;
            margin-bottom: 8px;
        }

        body[data-theme="light"] .debt-form input,
        body[data-theme="light"] .debt-form textarea,
        body[data-theme="light"] .debt-form select {
            border-color: #cbd5f5;
            background: #ffffff;
        }

        .debt-form textarea {
            min-height: 70px;
            resize: vertical;
        }

        .debt-form input:focus,
        .debt-form textarea:focus,
        .debt-form select:focus {
            outline: none;
            background: var(--bg-table-hover);
            border-color: var(--accent-gold);
        }

        .btn-primary {
            display: inline-block;
            width: 100%;
            margin-top: 8px;
            padding: 10px;
            background: var(--accent-gold);
            color: var(--bg-main);
            border: none;
            border-radius: 999px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            text-align: center;
            text-decoration: none;
        }

        .btn-primary:hover {
            background: var(--accent-gold-soft);
        }

        .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: 4px 0 10px 0;
        }

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

        .product-lines-header {
            font-size: 13px;
            margin-top: 8px;
            margin-bottom: 4px;
            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;
        }

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

        /* Table controls */
        .table-controls {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 6px;
            margin-bottom: 8px;
            font-size: 13px;
            color: var(--text-main);
        }

        .table-controls select {
            width: auto;
            min-width: 80px;
        }

        /* Table container */
        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 8px;
        }

        table {
            width: 100%;
            min-width: 1200px;
            border-collapse: collapse;
            background: var(--bg-card);
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.35);
            color: var(--text-main);
        }

        thead tr {
            background: var(--bg-table-head);
        }

        th,
        td {
            padding: 9px 10px;
            font-size: 13px;
            border-bottom: 1px solid rgba(255,255,255,0.12);
            white-space: nowrap;
        }

        body[data-theme="light"] th,
        body[data-theme="light"] td {
            border-bottom-color: rgba(0,0,0,0.06);
        }

        th {
            color: var(--text-heading);
            font-weight: 600;
            text-align: center;
        }

        td {
            text-align: center;
        }

        td.customer-cell,
        td.phone-cell,
        td.product-cell {
            text-align: left;
        }

        /* WRAP LONG ITEMS (ALL PRODUCTS) */
        td.items-cell {
            text-align: left;
            white-space: normal;
            word-wrap: break-word;
            overflow-wrap: anywhere;
            max-width: 320px;
        }

        tbody tr {
            background: var(--bg-table-row);
        }

        tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        tbody tr:hover {
            background: var(--bg-table-hover);
        }

        .numeric {
            text-align: right;
        }

        /* Status badge */
        .status-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 3px 10px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 500;
            letter-spacing: 0.04em;
            text-transform: uppercase;
        }

        .status-unpaid {
            background: rgba(239,68,68,0.12);
            color: #fecaca;
            border: 1px solid rgba(248,113,113,0.7);
        }

        .status-partial {
            background: rgba(234,179,8,0.12);
            color: #facc15;
            border: 1px solid rgba(250,204,21,0.7);
        }

        .status-paid {
            background: rgba(34,197,94,0.14);
            color: #bbf7d0;
            border: 1px solid rgba(34,197,94,0.8);
        }

        body[data-theme="light"] .status-unpaid {
            background:#fee2e2; color:#b91c1c; border-color:#f87171;
        }
        body[data-theme="light"] .status-partial {
            background:#fef3c7; color:#92400e; border-color:#facc15;
        }
        body[data-theme="light"] .status-paid {
            background:#dcfce7; color:#166534; border-color:#22c55e;
        }

        /* Totals rows */
        .totals-row {
            background: #001f3f;
            font-weight: 600;
        }

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

        .totals-row td {
            border-top: 1px solid rgba(255,255,255,0.25);
        }

        body[data-theme="light"] .totals-row td {
            border-top-color: rgba(0,0,0,0.08);
        }

        /* Action buttons */
        .action-btn {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 500;
            text-decoration: none;
            border: none;
            cursor: pointer;
            margin: 2px 0;
        }

        .action-primary {
            background: var(--accent-gold);
            color: var(--bg-main);
        }

        .action-primary:hover {
            background: var(--accent-gold-soft);
        }

        .action-danger {
            background: #e74c3c;
            color: #ffffff;
        }

        .action-danger:hover {
            background: #c0392b;
        }

        /* Pagination */
        .pagination {
            text-align: center;
            margin-top: 16px;
        }

        .page-btn {
            display: inline-block;
            padding: 7px 12px;
            margin: 0 3px;
            background: var(--bg-card);
            color: var(--text-main);
            border-radius: 999px;
            font-size: 13px;
            text-decoration: none;
            border: 1px solid #0a4a85;
        }

        body[data-theme="light"] .page-btn {
            border-color: rgba(148,163,184,0.6);
        }

        .page-btn.active {
            background: #5a47f5;
            font-weight: 700;
            border-color: #5a47f5;
            color: #ffffff;
        }

        .page-btn:hover {
            background: var(--bg-table-hover);
            border-color: var(--bg-table-hover);
        }

        footer {
            background: transparent !important;
        }
    </style>
</head>

<body>

<?php include("sidebar.php"); ?>

<div class="content-wrapper" id="content-wrapper">

    <!-- TOP BAR (same style as other pages) -->
    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as
                <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
            </span>
        </div>
    </div>

    <div class="page-header">
        <div>
            <div class="page-title">Credit Sales</div>
            <div class="page-subtitle">
                Record credit sales with multiple products and track outstanding balances (same logic as cashier).
            </div>
        </div>
    </div>

    <!-- Flash / validation messages -->
    <?php
    if (isset($_GET['added'])) {
        echo "<div class='alert alert-success'>✔ Credit sale recorded successfully.</div>";
    }
    if (isset($_GET['deleted'])) {
        echo "<div class='alert alert-success'>✔ Credit sale deleted successfully.</div>";
    }
    if (!empty($message)) {
        echo $message;
    }
    ?>

    <!-- Top metrics bar -->
    <div class="metrics-row">
        <div class="metric-card">
            <div class="metric-label">Total Credit Sales</div>
            <div class="metric-value"><?= number_format($totalRows) ?></div>
            <div class="metric-subtext">Number of credit sale records</div>
        </div>
        <div class="metric-card">
            <div class="metric-label">Grand Outstanding</div>
            <div class="metric-value">KES <?= number_format($grand_total, 2) ?></div>
            <div class="metric-subtext">All customers combined</div>
        </div>
        <div class="metric-card">
            <div class="metric-label">Total Discount</div>
            <div class="metric-value">KES <?= number_format($grand_discount_total, 2) ?></div>
            <div class="metric-subtext">Discount value on all credit sales</div>
        </div>
    </div>

    <!-- RECORD NEW CREDIT SALE (FORM CARD) -->
    <div class="card">
        <div class="card-title-row">
            <div class="card-title">Record a new credit sale</div>
            <div class="card-subtitle">
                Select multiple products, quantities and discounts. Stock will be reduced automatically.
            </div>
        </div>

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

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

            <div class="product-lines-header">
                Products on credit (scan barcode or select from list)
            </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" placeholder="e.g. customer will pay at month end"></textarea>

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

    <!-- CREDIT SALES TABLE CARD -->
    <div class="card table-card">
        <div class="card-title-row">
            <div class="card-title">Credit sales</div>
            <div class="card-subtitle">
                <?= $totalRows ? "Showing page $page of $totalPages · $totalRows records" : "No credit sales recorded yet." ?>
            </div>
        </div>

        <!-- SHOW X ENTRIES -->
        <div class="table-controls">
            <form method="GET">
                <span>Show</span>
                <select name="limit" onchange="this.form.submit()">
                    <?php foreach ($limit_options as $opt): ?>
                        <option value="<?= $opt ?>" <?= ($limit === $opt) ? 'selected' : '' ?>>
                            <?= $opt === 0 ? 'All' : $opt ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <span>entries</span>
            </form>
        </div>

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

                if ($debts && $debts->num_rows > 0):
                    while($row = $debts->fetch_assoc()):
                        $original_amount = (float)$row['amount'];
                        $total_paid      = (float)$row['total_paid'];
                        $remaining       = $original_amount - $total_paid;

                        if ($remaining < 0) {
                            $remaining = 0;
                        }

                        $unit_discount  = (float)$row['discount'];
                        $total_discount = $unit_discount * (int)$row['quantity'];

                        $page_total          += $remaining;
                        $page_discount_total += $total_discount;

                        // status logic
                        if ($total_paid <= 0.00001) {
                            $status_label = "Not paid";
                            $status_class = "status-badge status-unpaid";
                        } elseif ($remaining <= 0.00001) {
                            $status_label = "Fully paid";
                            $status_class = "status-badge status-paid";
                        } else {
                            $status_label = "Partially paid";
                            $status_class = "status-badge status-partial";
                        }

                        // show ALL products nicely wrapped
                        $itemsRaw   = $row['items'] ?? '';
                        $parts      = explode(';', $itemsRaw);
                        $itemsLines = [];
                        foreach ($parts as $part) {
                            $trimmed = trim($part);
                            if ($trimmed !== '') {
                                $itemsLines[] = $trimmed;
                            }
                        }
                        $itemsHtml = nl2br(htmlspecialchars(implode("\n", $itemsLines)));

                        $receiptNo = $row['receipt_no'] ?? '';
                ?>
                    <tr>
                        <td><?= (int)$row['id'] ?></td>
                        <td><?= htmlspecialchars($receiptNo) ?></td>
                        <td class="customer-cell"><?= htmlspecialchars($row['customer_name']) ?></td>
                        <td class="phone-cell"><?= htmlspecialchars($row['phone']) ?></td>
                        <td class="items-cell"><?= $itemsHtml ?></td>
                        <td class="numeric"><?= (int)$row['quantity'] ?></td>
                        <td class="numeric"><?= number_format($original_amount, 2) ?></td>
                        <td class="numeric"><?= number_format($total_paid, 2) ?></td>
                        <td class="numeric"><?= number_format($remaining, 2) ?></td>
                        <td class="numeric"><?= number_format($total_discount, 2) ?></td>
                        <td><span class="<?= $status_class ?>"><?= htmlspecialchars($status_label) ?></span></td>
                        <td><?= htmlspecialchars($row['debt_date']) ?></td>
                        <td>
                            <a class="action-btn action-primary" href="admin_record_debt_payments.php?id=<?= (int)$row['id'] ?>">
                                Record payment
                            </a>
                            <a class="action-btn action-danger"
                               href="?delete=<?= (int)$row['id'] ?>"
                               onclick="return confirm('Delete this credit sale?');">
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php 
                    endwhile;
                else: ?>
                    <tr>
                        <td colspan="13">No credit sales recorded.</td>
                    </tr>
                <?php endif; ?>

                <!-- Page totals -->
                <tr class="totals-row">
                    <td colspan="8">Total remaining (this page)</td>
                    <td class="numeric"><?= number_format($page_total, 2) ?></td>
                    <td class="numeric"><?= number_format($page_discount_total, 2) ?></td>
                    <td colspan="3"></td>
                </tr>

                <!-- Grand totals -->
                <tr class="totals-row">
                    <td colspan="8">Grand total outstanding (all credit sales)</td>
                    <td class="numeric"><?= number_format($grand_total, 2) ?></td>
                    <td class="numeric"><?= number_format($grand_discount_total, 2) ?></td>
                    <td colspan="3"></td>
                </tr>
                </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>

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

</div> <!-- end content-wrapper -->

<script>
// ---- THEME INIT ----
(function () {
    const saved = localStorage.getItem('adminTheme');
    const theme = (saved === 'light' || saved === 'dark') ? saved : 'dark';
    document.body.setAttribute('data-theme', theme);
})();

function toggleAdminTheme() {
    const current = document.body.getAttribute('data-theme') || 'dark';
    const next = current === 'dark' ? 'light' : 'dark';
    document.body.setAttribute('data-theme', next);
    localStorage.setItem('adminTheme', next);
}

// ---- SIDEBAR TOGGLE (hide sidebar + stretch content) ----
function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const wrapper = document.getElementById('content-wrapper');
    if (!sidebar || !wrapper) return;

    const isHidden = sidebar.classList.toggle('hidden');
    if (isHidden) {
        wrapper.classList.add('fullwidth');
    } else {
        wrapper.classList.remove('fullwidth');
    }
}

// ---- 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 product line on page load
document.addEventListener('DOMContentLoaded', function() {
    addProductLine();
});
</script>

</body>
</html>
