<?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'; // still used for nav highlight

$message = "";

/* -------------------------------
   PAGINATION + SHOW X ENTRIES
   (0 = All)
--------------------------------- */
$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;

/* -------------------------------
   ADD NEW CREDIT SALE
--------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_debt'])) {
    $customer   = trim($_POST['customer_name'] ?? '');
    $phone      = trim($_POST['phone'] ?? '');
    $product_id = intval($_POST['product_id'] ?? 0);
    $qty        = intval($_POST['quantity'] ?? 0);
    $desc       = trim($_POST['items'] ?? '');
    $discount   = isset($_POST['discount']) ? floatval($_POST['discount']) : 0; // discount per unit

    if ($customer === '' || $product_id <= 0 || $qty <= 0) {
        $message = "<div class='alert alert-error'>❌ Please fill all required fields correctly.</div>";
    } else {
        $productRes = $conn->query("SELECT * FROM products WHERE id = $product_id");
        $product    = $productRes ? $productRes->fetch_assoc() : null;

        if (!$product) {
            $message = "<div class='alert alert-error'>❌ Product not found.</div>";
        } elseif ($qty > $product['quantity']) {
            $message = "<div class='alert alert-error'>❌ Not enough stock available.</div>";
        } else {
            $selling_price   = (float)$product['selling_price'];
            $effective_price = $selling_price - $discount;
            if ($effective_price < 0) $effective_price = 0;

            $total_amount = $effective_price * $qty;

            $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,
                    $product_id,
                    $qty,
                    $desc,
                    $total_amount,
                    $discount
                );
                if ($stmt->execute()) {
                    $stmt->close();

                    $new_stock = (int)$product['quantity'] - $qty;
                    $conn->query("UPDATE products SET quantity = $new_stock WHERE id = $product_id");

                    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 for all credit sales (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);

// Products for dropdown
$products = $conn->query("SELECT id, name, quantity, selling_price FROM products WHERE quantity > 0 ORDER BY name ASC");
?>
<!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: 620px;
        }

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

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

        .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: 1050px;
        }

        .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 pinned bottom */
        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>
                    <!-- Label changed here -->
                    <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 a product, quantity, and optional discount per unit. 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">
                <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">

                <label for="product_id">Select product</label>
                <select id="product_id" name="product_id" required>
                    <option value="">-- choose product --</option>
                    <?php if ($products && $products->num_rows > 0): ?>
                        <?php while ($p = $products->fetch_assoc()): ?>
                            <option value="<?= (int)$p['id'] ?>">
                                <?= htmlspecialchars($p['name']) ?> — KES <?= number_format((float)$p['selling_price'], 2) ?>
                                (Stock: <?= (int)$p['quantity'] ?>)
                            </option>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </select>

                <label for="quantity">Quantity</label>
                <input type="number" id="quantity" name="quantity" min="1" required>

                <label for="discount">Discount per unit (KES)</label>
                <input type="number" step="0.01" id="discount" name="discount" value="0">

                <label for="items">Description (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>Customer</th>
                            <th>Phone</th>
                            <th>Product</th>
                            <th>Qty</th>
                            <th>Outstanding (KES)</th>
                            <th>Discount total (KES)</th>
                            <th>Description</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;
                        ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>
                                <td><?= htmlspecialchars($row['customer_name']) ?></td>
                                <td><?= htmlspecialchars($row['phone']) ?></td>
                                <td class="cell-left"><?= htmlspecialchars($row['product_name']) ?></td>
                                <td><?= (int)$row['quantity'] ?></td>
                                <td><?= number_format($outstanding, 2) ?></td>
                                <td><?= number_format($total_discount, 2) ?></td>
                                <td class="cell-left"><?= htmlspecialchars($row['items']) ?></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="5" 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="3"></td>
                            </tr>

                            <!-- Grand Totals -->
                            <tr class="totals-row">
                                <td colspan="5" 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="3"></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');
    }
}
</script>

</body>
</html>
