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

include("db_connect.php");

date_default_timezone_set('Africa/Nairobi');

// --- Date filter (defaults to today) ---
$today = date('Y-m-d');
$selected_date = isset($_GET['date']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['date'])
    ? $_GET['date']
    : $today;

// NOTE: this assumes your payments table has a `created_at` DATETIME column.
// If your datetime column has a different name, change `created_at` below.
$listStmt = $conn->prepare("
    SELECT *
    FROM payments
    WHERE DATE(created_at) = ?
    ORDER BY created_at DESC, id DESC
");
$listStmt->bind_param("s", $selected_date);
$listStmt->execute();
$result = $listStmt->get_result();
$listStmt->close();

// Totals for the selected day
$totalsStmt = $conn->prepare("
    SELECT
        COALESCE(SUM(amount_due), 0)                         AS total_due,
        COALESCE(SUM(paid_at), 0)                            AS total_paid,
        COALESCE(SUM(change_amount), 0)                      AS total_change,
        COALESCE(SUM(CASE WHEN payment_method='cash'  THEN paid_at END), 0) AS total_cash,
        COALESCE(SUM(CASE WHEN payment_method='mpesa' THEN paid_at END), 0) AS total_mpesa,
        COALESCE(SUM(CASE WHEN payment_method='bank'  THEN paid_at END), 0) AS total_bank,
        COUNT(*) AS payment_count
    FROM payments
    WHERE DATE(created_at) = ?
");
$totalsStmt->bind_param("s", $selected_date);
$totalsStmt->execute();
$totalsRes = $totalsStmt->get_result();
$totals    = $totalsRes->fetch_assoc();
$totalsStmt->close();

$page_title = "Payments Summary";
?>
<!DOCTYPE html>
<html>
<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: 25px 30px;
        }

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

        .page-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 6px;
            margin-bottom: 18px;
        }

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

        .page-subtitle {
            font-size: 13px;
            color: #f4b400;
            text-align: center;
        }

        .link-row {
            text-align: center;
            margin-bottom: 18px;
        }

        .styled-link {
            padding: 9px 18px;
            background: var(--accent-gold);
            color: var(--bg-main);
            text-decoration: none;
            border-radius: 6px;
            font-weight: 600;
            font-size: 13px;
            display: inline-block;
            border: none;
        }

        .styled-link:hover {
            background: var(--accent-gold-soft);
        }

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

        body[data-theme="light"] .page-card {
            box-shadow: 0 12px 30px rgba(15,23,42,0.12);
            border-color: rgba(148,163,184,0.55);
        }

        .page-card-title-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 8px;
        }

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

        .date-filter-form {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
        }

        .date-filter-form input[type="date"] {
            padding: 7px 10px;
            border-radius: 6px;
            border: 1px solid rgba(148,163,184,0.7);
            background: var(--bg-main);
            color: var(--text-main);
            font-size: 13px;
        }

        .date-filter-form button {
            padding: 7px 12px;
            border-radius: 6px;
            border: none;
            background: var(--accent-gold);
            color: var(--bg-main);
            font-weight: 600;
            cursor: pointer;
            font-size: 12px;
        }

        .date-filter-form button:hover {
            background: var(--accent-gold-soft);
        }

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

        table {
            width: 100%;
            min-width: 1100px;
            border-collapse: collapse;
            background: var(--bg-card);
            color: var(--text-main);
            border-radius: 10px;
        }

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

        th,
        td {
            padding: 10px 12px;
            border: 1px solid rgba(255,255,255,0.15);
            text-align: center;
            font-size: 13px;
            white-space: nowrap;
        }

        th {
            color: #ffffff;
            font-weight: 600;
        }

        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);
            color: #ffffff;
        }

        body[data-theme="light"] th {
            color: #111827;
            border-color: rgba(148,163,184,0.5);
        }

        body[data-theme="light"] td {
            border-color: rgba(148,163,184,0.35);
        }

        body[data-theme="light"] tbody tr {
            background: var(--bg-table-row);
        }

        body[data-theme="light"] tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        body[data-theme="light"] tbody tr:hover {
            background: var(--bg-table-hover);
            color: #111827;
        }

        .numeric {
            text-align: right;
        }

        .totals-box {
            margin-top: 20px;
            padding: 14px 18px;
            background: var(--bg-card);
            border-left: 6px solid #f4b400;
            border-radius: 10px;
            text-align: center;
            font-weight: 600;
            font-size: 14px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.3);
            color: var(--text-main);
        }

        body[data-theme="light"] .totals-box {
            box-shadow: 0 10px 24px rgba(15,23,42,0.12);
            border-left-color: #facc15;
        }

        .totals-box p {
            margin: 4px 0;
        }

        .totals-box span.label {
            color: var(--text-main);
        }

        .totals-box span.value {
            color: #f4b400;
        }

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

<body>

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

<div class="content-area">

    <div class="page-header">
        <div class="page-title">Payments Summary</div>
        <div class="page-subtitle">
            Payments for <?= htmlspecialchars($selected_date) ?>
        </div>
    </div>

    

    <div class="page-card">
        <div class="page-card-title-row">
            <div class="page-card-title">
                Payments on <?= htmlspecialchars($selected_date) ?>
            </div>

            <form method="get" class="date-filter-form">
                <label for="date">Choose date:</label>
                <input
                    type="date"
                    id="date"
                    name="date"
                    value="<?= htmlspecialchars($selected_date) ?>"
                    max="<?= htmlspecialchars($today) ?>"
                >
                <button type="submit">Go</button>
            </form>
        </div>

        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>Date &amp; Time</th>
                        <th>Receipt</th>
                        <th>Cashier</th>
                        <th>Payment Method</th>
                        <th>Amount Due (KES)</th>
                        <th>Paid (KES)</th>
                        <th>Change (KES)</th>
                        <th>M-Pesa Code</th>
                        <th>Bank Ref</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['created_at']) ?></td>
                            <td><?= htmlspecialchars($row['receipt_id']) ?></td>
                            <td><?= htmlspecialchars($row['cashier']) ?></td>
                            <td><?= htmlspecialchars(strtoupper($row['payment_method'])) ?></td>
                            <td class="numeric"><?= number_format((float)$row['amount_due'], 2) ?></td>
                            <td class="numeric"><?= number_format((float)$row['paid_at'], 2) ?></td>
                            <td class="numeric"><?= number_format((float)$row['change_amount'], 2) ?></td>
                            <td><?= htmlspecialchars($row['mpesa_code']) ?></td>
                            <td><?= htmlspecialchars($row['bank_ref']) ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9">No payments found for this date.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="totals-box">
        <p>
            <span class="label">Number of payments:</span>
            <span class="value"><?= (int)$totals['payment_count'] ?></span>
        </p>
        <p>
            <span class="label">Total Due:</span>
            <span class="value">KES <?= number_format((float)$totals['total_due'], 2) ?></span>
        </p>
        <p>
            <span class="label">Total Paid:</span>
            <span class="value">KES <?= number_format((float)$totals['total_paid'], 2) ?></span>
        </p>
        <p>
            <span class="label">Total Change:</span>
            <span class="value">KES <?= number_format((float)$totals['total_change'], 2) ?></span>
        </p>
        <p>
            <span class="label">By Method – Cash:</span>
            <span class="value">KES <?= number_format((float)$totals['total_cash'], 2) ?></span>
            &nbsp; | &nbsp;
            <span class="label">M-Pesa:</span>
            <span class="value">KES <?= number_format((float)$totals['total_mpesa'], 2) ?></span>
            &nbsp; | &nbsp;
            <span class="label">Bank:</span>
            <span class="value">KES <?= number_format((float)$totals['total_bank'], 2) ?></span>
        </p>
    </div>

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

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

</body>
</html>
