<?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');

$username   = $_SESSION['username'];
$page_title = "Credit Payments | Admin POS";

/* -----------------------------------------
   FILTERS & PAGINATION
-------------------------------------------*/

$limit_options = [10, 15, 25, 50, 100, 0]; // 0 = All
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 15;
if (!in_array($limit, $limit_options, true)) {
    $limit = 15;
}
$page   = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($limit > 0) ? ($page - 1) * $limit : 0;

// filters
$from   = $_GET['from']   ?? '';
$to     = $_GET['to']     ?? '';
$method = $_GET['method'] ?? '';
$search = trim($_GET['search'] ?? '');

$whereParts = [];

// Date range
if ($from && preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) {
    $whereParts[] = "DATE(dp.payment_date) >= '" . $conn->real_escape_string($from) . "'";
}
if ($to && preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
    $whereParts[] = "DATE(dp.payment_date) <= '" . $conn->real_escape_string($to) . "'";
}

// Payment method
$valid_methods = ['cash', 'mpesa', 'bank'];
if ($method && in_array($method, $valid_methods, true)) {
    $whereParts[] = "dp.payment_method = '" . $conn->real_escape_string($method) . "'";
}

// Search (receipt / customer / phone)
if ($search !== '') {
    $esc = $conn->real_escape_string($search);
    $whereParts[] = "(dp.receipt_id LIKE '%$esc%' OR d.customer_name LIKE '%$esc%' OR d.phone LIKE '%$esc%')";
}

$whereSql = $whereParts ? ('WHERE ' . implode(' AND ', $whereParts)) : '';

/* -----------------------------------------
   COUNT ROWS
-------------------------------------------*/
$countSql = "
    SELECT COUNT(*) AS total
    FROM debt_payments dp
    LEFT JOIN customer_debts d ON dp.debt_id = d.id
    $whereSql
";
$countRes  = $conn->query($countSql);
$totalRows = (int)($countRes->fetch_assoc()['total'] ?? 0);

$totalPages = ($limit > 0 && $totalRows > 0)
    ? max(1, (int)ceil($totalRows / $limit))
    : 1;

if ($limit === 0) {
    $page   = 1;
    $offset = 0;
}

/* -----------------------------------------
   FETCH CREDIT PAYMENTS
-------------------------------------------*/
$sql = "
    SELECT
        dp.*,
        d.customer_name,
        d.phone,
        d.amount      AS debt_amount,
        d.items       AS items_summary,
        p.name        AS product_name,
        (
            SELECT COALESCE(SUM(dp2.amount_paid), 0)
            FROM debt_payments dp2
            WHERE dp2.debt_id = d.id
        ) AS total_paid_for_debt
    FROM debt_payments dp
    LEFT JOIN customer_debts d ON dp.debt_id = d.id
    LEFT JOIN products p       ON d.product_id = p.id
    $whereSql
    ORDER BY dp.payment_date DESC
";
if ($limit > 0) {
    $sql .= " LIMIT $limit OFFSET $offset";
}
$payments = $conn->query($sql);

// totals (page + grand)
$page_total = 0.0;

$grandSql = "
    SELECT SUM(dp.amount_paid) AS grand_total
    FROM debt_payments dp
    LEFT JOIN customer_debts d ON dp.debt_id = d.id
    $whereSql
";
$grandRes    = $conn->query($grandSql);
$grand_total = (float)($grandRes->fetch_assoc()['grand_total'] ?? 0.0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include 'head.php'; ?>
    <style>
        body {
            margin: 0;
            font-family: 'Poppins', system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            background: var(--bg-main, #001f3f);
            color: var(--text-main);
        }

        /* ============= LAYOUT + TOPBAR (UNIFORM) ============= */
        .content-wrapper {
            margin-left: 260px; /* space for admin sidebar */
            padding: 24px 26px 32px;
            min-height: 100vh;
            box-sizing: border-box;
            background:
                radial-gradient(circle at top left, rgba(0,255,239,0.08), transparent 55%),
                var(--bg-main, #001f3f);
            transition: margin-left 0.3s ease, background 0.3s ease;
        }

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

        .content-inner {
            max-width: 1600px;
            margin: 0 auto;
        }

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

        /* Sidebar hide on toggle */
        #sidebar.hidden {
            transform: translateX(-260px);
        }

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

        @media (max-width: 768px){
            .content-wrapper {
                padding: 18px 14px 24px;
            }
        }

        /* ============= PAGE CONTENT STYLES ============= */
        .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(--text-muted);
            margin-top: 3px;
        }

        .metric-row {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 14px;
            margin-bottom: 18px;
        }
        @media (max-width: 992px) {
            .metric-row {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }
        }
        @media (max-width: 600px) {
            .metric-row {
                grid-template-columns: minmax(0, 1fr);
            }
        }

        .metric-card {
            background: var(--bg-card);
            border-radius: 12px;
            padding: 10px 14px;
            border: 1px solid rgba(15,23,42,0.45);
            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.7;
            margin-bottom: 4px;
        }
        .metric-value {
            font-size: 18px;
            font-weight: 600;
        }
        .metric-subtext {
            font-size: 11px;
            opacity: 0.8;
            margin-top: 2px;
        }

        .card {
            background: var(--bg-card);
            border-radius: 14px;
            padding: 18px 20px 22px;
            border: 1px solid rgba(15,23,42,0.5);
            box-shadow: 0 4px 16px rgba(0,0,0,0.30);
            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-header-row {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 12px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        .card-title {
            font-size: 18px;
            font-weight: 500;
            color: var(--text-heading);
        }
        .card-subtitle {
            font-size: 13px;
            color: var(--text-muted);
        }

        .filter-form {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            align-items: center;
            justify-content: flex-end;
            font-size: 12px;
        }
        .filter-form input,
        .filter-form select {
            padding: 6px 9px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.6);
            background: var(--bg-table-head);
            color: var(--text-main);
            font-size: 12px;
        }
        body[data-theme="light"] .filter-form input,
        body[data-theme="light"] .filter-form select {
            background: #eff6ff;
        }
        .filter-form button {
            padding: 6px 12px;
            border-radius: 999px;
            border: none;
            font-size: 12px;
            cursor: pointer;
            background: var(--accent-gold);
            color: var(--bg-main);
            font-weight: 600;
        }

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

        table.credit-table {
            width: 100%;
            min-width: 1100px;
            border-collapse: collapse;
            border-radius: 10px;
            overflow: hidden;
            background: var(--bg-card);
            box-shadow: 0 4px 14px rgba(0,0,0,0.28);
        }

        thead tr {
            background: var(--bg-table-head);
        }
        th, td {
            padding: 9px 8px;
            font-size: 13px;
            border-bottom: 1px solid rgba(255,255,255,0.08);
            text-align: center;
            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;
        }
        td {
            color: var(--text-main);
        }

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

        .col-products {
            text-align: left;
            white-space: normal !important;
            max-width: 340px;
            overflow-wrap: anywhere;
        }

        .numeric {
            text-align: right;
        }

        .status-pill {
            display: inline-block;
            padding: 3px 10px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 500;
        }
        .status-paid {
            background: rgba(34,197,94,0.16);
            color: #bbf7d0;
            border: 1px solid rgba(34,197,94,0.9);
        }
        .status-partial {
            background: rgba(234,179,8,0.14);
            color: #facc15;
            border: 1px solid rgba(250,204,21,0.9);
        }
        .status-unpaid {
            background: rgba(239,68,68,0.16);
            color: #fecaca;
            border: 1px solid rgba(248,113,113,0.95);
        }
        body[data-theme="light"] .status-paid {
            background:#dcfce7; color:#166534; border-color:#22c55e;
        }
        body[data-theme="light"] .status-partial {
            background:#fef3c7; color:#92400e; border-color:#facc15;
        }
        body[data-theme="light"] .status-unpaid {
            background:#fee2e2; color:#b91c1c; border-color:#f87171;
        }

        .totals-row {
            background: var(--bg-table-head);
            font-weight: 600;
        }

        .pagination {
            text-align: center;
            margin-top: 14px;
        }
        .page-btn {
            display: inline-block;
            padding: 7px 12px;
            margin: 0 3px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.6);
            background: var(--bg-card);
            color: var(--text-main);
            font-size: 13px;
            text-decoration: none;
        }
        .page-btn.active {
            background: #5a47f5;
            color: #ffffff;
            font-weight: 700;
            border-color: #5a47f5;
        }
        .page-btn:hover {
            background: var(--bg-table-hover);
        }

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

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

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

    <!-- TOP BAR (same logic as other admin 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="content-inner">

        <div class="page-header">
            <div>
                <div class="page-title">Credit Payments</div>
                <div class="page-subtitle">Track all payments made against customer credit sales.</div>
            </div>
        </div>

        <div class="metric-row">
            <div class="metric-card">
                <div class="metric-label">Total Records</div>
                <div class="metric-value"><?= number_format($totalRows) ?></div>
                <div class="metric-subtext">Payments matching current filters</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">Grand Total Paid</div>
                <div class="metric-value">KES <?= number_format($grand_total, 2) ?></div>
                <div class="metric-subtext">Sum of all filtered credit payments</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">Page Size</div>
                <div class="metric-value"><?= $limit === 0 ? 'All' : $limit ?></div>
                <div class="metric-subtext">Records per page</div>
            </div>
        </div>

        <div class="card">
            <div class="card-header-row">
                <div>
                    <div class="card-title">Credit payment history</div>
                    <div class="card-subtitle">
                        <?= $totalRows ? "Showing page $page of $totalPages" : "No credit payments recorded yet." ?>
                    </div>
                </div>

                <form method="GET" class="filter-form">
                    <input type="date" name="from" value="<?= htmlspecialchars($from) ?>" title="From date">
                    <input type="date" name="to"   value="<?= htmlspecialchars($to)   ?>" title="To date">

                    <select name="method">
                        <option value="">All methods</option>
                        <option value="cash"  <?= $method === 'cash'  ? 'selected' : '' ?>>Cash</option>
                        <option value="mpesa" <?= $method === 'mpesa' ? 'selected' : '' ?>>M-Pesa</option>
                        <option value="bank"  <?= $method === 'bank'  ? 'selected' : '' ?>>Bank</option>
                    </select>

                    <input type="text"
                           name="search"
                           value="<?= htmlspecialchars($search) ?>"
                           placeholder="Receipt / customer / phone">

                    <select name="limit">
                        <?php foreach ($limit_options as $opt): ?>
                            <option value="<?= $opt ?>" <?= ($limit === $opt) ? 'selected' : '' ?>>
                                <?= $opt === 0 ? 'All' : $opt ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <button type="submit">Filter</button>
                </form>
            </div>

            <div class="table-wrapper">
                <table class="credit-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Receipt #</th>
                            <th>Customer</th>
                            <th>Phone</th>
                            <th class="col-products">Products</th>
                            <th>Amount paid (KES)</th>
                            <th>Method</th>
                            <th>Payment date</th>
                            <th>Cashier</th>
                            <th>Balance (KES)</th>
                            <th>Debt status</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if ($payments && $payments->num_rows > 0): ?>
                        <?php
                        $i = $offset + 1;
                        while ($row = $payments->fetch_assoc()):
                            $page_total += (float)$row['amount_paid'];

                            $debt_amount         = (float)($row['debt_amount'] ?? 0);
                            $total_paid_for_debt = (float)($row['total_paid_for_debt'] ?? 0);
                            $remaining_for_debt  = $debt_amount - $total_paid_for_debt;
                            if ($remaining_for_debt < 0) {
                                $remaining_for_debt = 0.0;
                            }

                            if ($total_paid_for_debt <= 0.00001) {
                                $status_label = 'Not paid';
                                $status_class = 'status-unpaid';
                            } elseif ($remaining_for_debt <= 0.00001) {
                                $status_label = 'Fully paid';
                                $status_class = 'status-paid';
                            } else {
                                $status_label = 'Partially paid';
                                $status_class = 'status-partial';
                            }

                            $products_text = trim((string)($row['items_summary'] ?? ''));
                            if ($products_text === '') {
                                $products_text = $row['product_name'] ?? '';
                            }
                            // Strip any "| Note..." part
                            $posNote = stripos($products_text, '| note');
                            if ($posNote !== false) {
                                $products_text = trim(substr($products_text, 0, $posNote));
                            }
                        ?>
                            <tr>
                                <td><?= $i++ ?></td>
                                <td><?= htmlspecialchars($row['receipt_id'] ?? '') ?></td>
                                <td><?= htmlspecialchars($row['customer_name'] ?? '') ?></td>
                                <td><?= htmlspecialchars($row['phone'] ?? '') ?></td>
                                <td class="col-products"><?= htmlspecialchars($products_text) ?></td>
                                <td class="numeric"><?= number_format((float)$row['amount_paid'], 2) ?></td>
                                <td><?= htmlspecialchars($row['payment_method'] ?? '') ?></td>
                                <td><?= htmlspecialchars($row['payment_date']) ?></td>
                                <td><?= htmlspecialchars($row['cashier']) ?></td>
                                <td class="numeric"><?= number_format($remaining_for_debt, 2) ?></td>
                                <td>
                                    <span class="status-pill <?= $status_class ?>">
                                        <?= htmlspecialchars($status_label) ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endwhile; ?>

                        <tr class="totals-row">
                            <td colspan="5" style="text-align:right;">Total paid (this page)</td>
                            <td class="numeric"><?= number_format($page_total, 2) ?></td>
                            <td colspan="5"></td>
                        </tr>

                        <tr class="totals-row">
                            <td colspan="5" style="text-align:right;">Grand total (all filtered results)</td>
                            <td class="numeric"><?= number_format($grand_total, 2) ?></td>
                            <td colspan="5"></td>
                        </tr>
                    <?php else: ?>
                        <tr>
                            <td colspan="11" style="padding:16px;">No credit payments found for the selected filters.</td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($limit > 0 && $totalPages > 1): ?>
                <div class="pagination">
                    <?php
                    $baseParams = $_GET;
                    foreach (range(1, $totalPages) as $p) {
                        $baseParams['page'] = $p;
                        $query = http_build_query($baseParams);
                        ?>
                        <a href="?<?= htmlspecialchars($query) ?>"
                           class="page-btn <?= ($p == $page) ? 'active' : '' ?>">
                            <?= $p ?>
                        </a>
                    <?php } ?>
                </div>
            <?php endif; ?>

        </div>

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

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

<script>
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');
    }
}
</script>

</body>
</html>
