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

require 'db_connect.php';

$message = "";

/* ------------------------------- 
   PAGINATION + SHOW X ENTRIES
--------------------------------- */
$limit  = isset($_GET['limit']) ? intval($_GET['limit']) : 15;
$allowed_limits = [10, 15, 25, 50, 100, 0]; // 0 = All

if (!in_array($limit, $allowed_limits, true)) {
    $limit = 15;
}

$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($limit > 0) ? (($page - 1) * $limit) : 0;

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

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

    $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 <= 0) {
        $message = "<div class='alert alert-error'>❌ Quantity must be at least 1.</div>";
    } elseif ($qty > $product['quantity']) {
        $message = "<div class='alert alert-error'>❌ Not enough stock available for this product.</div>";
    } else {
        $selling_price = (float)$product['selling_price'];
        $effective_price = max(0, $selling_price - $discount);
        $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);
            $stmt->execute();
            $stmt->close();

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

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

/* ------------------------------- 
   DELETE DEBT
--------------------------------- */
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 DEBTS (with total paid)
--------------------------------- */
$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 TOTALS (all debts)
--------------------------------- */
$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_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);

$page_title = "Customer Debts";
?>
<!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);
        }

        .content-area {
            margin-left: 260px;
            padding: 24px 30px 32px;
            background: var(--bg-main);
        }

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

        /* 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;
        }

        /* Layout: form + table */
        .layout-grid {
            display: grid;
            grid-template-columns: minmax(0, 360px) minmax(0, 1fr);
            gap: 20px;
            align-items: flex-start;
        }

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

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

        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 */
        .form-group {
            margin-top: 8px;
        }

        label {
            display: block;
            margin-bottom: 4px;
            font-weight: 500;
            font-size: 13px;
            color: var(--text-main);
        }

        input,
        textarea,
        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;
        }

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

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

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

        .btn-primary {
            display: inline-block;
            width: 100%;
            margin-top: 14px;
            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);
        }

        /* Controls: show X entries */
        .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-card {
            margin-top: 0;
        }

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

        table {
            width: 100%;
            min-width: 1150px;
            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,
        td.desc-cell {
            text-align: left;
        }

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

        /* 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 in table */
        .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"); ?>
<?php include("topbar.php"); ?>

<div class="content-area">

    <div class="page-header">
        <div>
            <div class="page-title">Customer Debts</div>
            <div class="page-subtitle">
                Record, review, and track outstanding balances.
            </div>
        </div>
    </div>

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

    <!-- Top metrics bar -->
    <div class="metrics-row">
        <div class="metric-card">
            <div class="metric-label">Total Debts</div>
            <div class="metric-value"><?= number_format($totalRows) ?></div>
            <div class="metric-subtext">Number of debt 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 debts</div>
        </div>
    </div>

    <div class="layout-grid">

        <!-- ADD DEBT FORM CARD -->
        <div class="card">
            <div class="card-title-row">
                <div class="card-title">Record New Customer Debt</div>
                <div class="card-subtitle">Attach a product and quantity to create a debt.</div>
            </div>

            <form method="POST">
                <div class="form-group">
                    <label for="customer_name">Customer Name</label>
                    <input id="customer_name" type="text" name="customer_name" required>
                </div>

                <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <input id="phone" type="text" name="phone" placeholder="e.g. 0712 345 678">
                </div>

                <div class="form-group">
                    <label for="product_id">Select Product</label>
                    <select id="product_id" name="product_id" required>
                        <option value="" disabled selected>-- choose product --</option>
                        <?php
                        $products = $conn->query("SELECT * FROM products WHERE quantity > 0 ORDER BY name ASC");
                        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; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label for="quantity">Quantity</label>
                    <input id="quantity" type="number" name="quantity" min="1" required>
                </div>

                <div class="form-group">
                    <label for="discount">Discount per Unit (KES)</label>
                    <input id="discount" type="number" step="0.01" name="discount" value="0">
                </div>

                <div class="form-group">
                    <label for="items">Description (optional)</label>
                    <textarea id="items" name="items" placeholder="e.g. Items on credit, expected payment date, notes..."></textarea>
                </div>

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

        <!-- DEBTS TABLE CARD -->
        <div class="card table-card">
            <div class="card-title-row">
                <div class="card-title">Outstanding Debts</div>
                <div class="card-subtitle">
                    <?= $totalRows ? "Page $page of $totalPages · $totalRows records" : "No debts recorded yet." ?>
                </div>
            </div>

            <!-- SHOW X ENTRIES -->
            <div class="table-controls">
                <form method="GET">
                    <span>Show</span>
                    <select name="limit" onchange="this.form.submit()">
                        <option value="10"  <?= $limit == 10  ? 'selected' : '' ?>>10</option>
                        <option value="15"  <?= $limit == 15  ? 'selected' : '' ?>>15</option>
                        <option value="25"  <?= $limit == 25  ? 'selected' : '' ?>>25</option>
                        <option value="50"  <?= $limit == 50  ? 'selected' : '' ?>>50</option>
                        <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100</option>
                        <option value="0"   <?= $limit == 0   ? 'selected' : '' ?>>All</option>
                    </select>
                    <span>entries</span>
                </form>
            </div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Customer</th>
                            <th>Phone</th>
                            <th>Product</th>
                            <th>Qty</th>
                            <th>Outstanding (KES)</th>
                            <th>Total Discount (KES)</th>
                            <th>Description</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()):
                            $unit_discount  = (float)$row['discount'];
                            $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 class="customer-cell"><?= htmlspecialchars($row['customer_name']) ?></td>
                            <td class="phone-cell"><?= htmlspecialchars($row['phone']) ?></td>
                            <td class="product-cell"><?= htmlspecialchars($row['product_name']) ?></td>
                            <td class="numeric"><?= (int)$row['quantity'] ?></td>
                            <td class="numeric"><?= number_format($outstanding, 2) ?></td>
                            <td class="numeric"><?= number_format($total_discount, 2) ?></td>
                            <td class="desc-cell"><?= htmlspecialchars($row['items']) ?></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 debt?');">
                                    Delete
                                </a>
                            </td>
                        </tr>
                    <?php 
                        endwhile;
                    else: ?>
                        <tr>
                            <td colspan="10">No debts recorded.</td>
                        </tr>
                    <?php endif; ?>

                    <!-- Page totals -->
                    <tr class="totals-row">
                        <td colspan="5">Total Outstanding (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="5">Grand Total Outstanding (All Debts)</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>
    </div>

</div>

<?php include 'footer.php'; ?>
</body>
</html>
