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

        /* MAIN WRAPPER NEXT TO SIDEBAR */
        .content-wrapper {
            margin-left: 250px;
            padding: 25px 30px;
            background: var(--bg-main);
            min-height: 100vh;
            box-sizing: border-box;
            transition: margin-left 0.3s ease;
        }

        /* when sidebar is hidden by toggle */
        .content-wrapper.fullwidth {
            margin-left: 0;
        }

        /* inner container (centers content a bit) */
        .content-area {
            max-width: 1600px;
            margin: 0 auto;
        }

        /* completely hide sidebar when .hidden is applied */
        .sidebar.hidden {
            display: none;
        }

        /* TOP BAR (UNIFORM ACROSS PAGES) */
        .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;
        }

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

            .topbar {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
        }

        .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-wrapper" id="content-wrapper">

    <!-- TOP BAR (SHARED) -->
    <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-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>

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

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

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