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

$username   = $_SESSION['username'];
$page_title = "Credit Payments | Cashier POS";
$active     = 'credit_payments'; // for nav highlight

/* -----------------------------------------
   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 'cashier_head.php'; ?>
    <style>
        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-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-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-table-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 14px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }
        .pos-table-header h2 {
            font-size: 19px;
            font-weight: 600;
        }
        .pos-table-header p {
            font-size: 13px;
            color: #c3d8ff;
            margin-top: 4px;
        }
        html[data-theme="light"] .pos-table-header p {
            color: #4b5563;
        }

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

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

        .filter-form {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            justify-content: flex-end;
            font-size: 12px;
        }
        .filter-form input,
        .filter-form select {
            padding: 6px 9px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.6);
            background: #063d8c;
            color: #E9F5FF;
            font-size: 12px;
        }
        html[data-theme="light"] .filter-form input,
        html[data-theme="light"] .filter-form select {
            background: #eff6ff;
            border-color: rgba(148,163,184,0.7);
            color: #0f172a;
        }
        .filter-form button {
            padding: 6px 12px;
            border-radius: 999px;
            border: none;
            background: #00FFE5;
            color: #011b35;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
        }

        .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;
            white-space: nowrap; /* default: keep columns compact */
        }
        .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); }

        /* Products column: allow wrapping & better width */
        .col-products {
            text-align: left;
            white-space: normal !important;
            max-width: 350px;
            overflow-wrap: anywhere;
        }

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

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

        .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: #00FFE5;
            border-color: #00FFE5;
            color: #011b35;
            font-weight: 700;
        }
        html[data-theme="light"] .page-btn {
            background:#eff6ff; border-color:rgba(148,163,184,0.7); color:#0f172a;
        }
        html[data-theme="light"] .page-btn.active {
            background:#0ea5e9; color:#f9fafb;
        }

        .back-link {
            text-decoration: none;
            font-size: 13px;
            color: #82EEFD;
        }
        .back-link:hover { text-decoration: underline; }
        html[data-theme="light"] .back-link { color:#0369a1; }

        footer {
            background: transparent;
            text-align: center;
            font-size: 12px;
            color: var(--cash-text-muted);
            padding: 10px 18px;
            margin-top: auto;
        }
    </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>Review all credit payments and see remaining balances.</small>
            </div>

            <div class="cashier-topbar-right">
                <nav class="cashier-topnav">
                    <a href="cashier_dashboard.php" class="<?= ($active === 'dashboard') ? 'active' : '' ?>">Dashboard</a>
                    <a href="record_sales.php" class="<?= ($active === 'sales') ? 'active' : '' ?>">Sales</a>
                    <a href="cashier_view_daily_sales.php" class="<?= ($active === 'daily_sales') ? 'active' : '' ?>">Today’s Sales</a>
                    <a href="transaction_history.php" class="<?= ($active === 'transactions') ? 'active' : '' ?>">Transactions</a>
                    <a href="customers.php" class="<?= ($active === 'customers') ? 'active' : '' ?>">Customers</a>
                    <a href="add_expense.php" class="<?= ($active === 'expenses') ? 'active' : '' ?>">Expenses</a>
                    <a href="customer_debts.php" class="<?= ($active === 'debts') ? 'active' : '' ?>">Credit sales</a>
                    <a href="cashier_credit_payments.php" class="<?= ($active === 'credit_payments') ? 'active' : '' ?>">Credit payments</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" type="button" onclick="toggleCashierSidebar()">
                    ☰
                </button>
            </div>
        </div>

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

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

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

            <div class="pos-table-wrapper">
                <table class="pos-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;
                            }

                            // compute status
                            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 list: from customer_debts.items
                            $products_text = trim((string)($row['items_summary'] ?? ''));

                            if ($products_text === '') {
                                $products_text = $row['product_name'] ?? '';
                            }

                            // 🔹 remove "| Note: ..." or "| note ..." from products text
                            $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><?= 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><?= number_format($remaining_for_debt, 2) ?></td>
                                <td>
                                    <span class="status-pill <?= $status_class ?>">
                                        <?= htmlspecialchars($status_label) ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endwhile; ?>

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

                        <!-- Grand total -->
                        <tr class="totals-row">
                            <td colspan="5" style="text-align:right;">Grand total (all filtered results)</td>
                            <td><?= number_format($grand_total, 2) ?></td>
                            <td colspan="5"></td>
                        </tr>

                    <?php else: ?>
                        <tr>
                            <td colspan="11" style="padding:16px; color:#c3d8ff; text-align:center;">
                                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 style="margin-top: 14px;">
                <a href="customer_debts.php" class="back-link">← Back to credit sales</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>
