<?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) ---
$selected_date = $_GET['date'] ?? date('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $selected_date)) {
    $selected_date = date('Y-m-d');
}

/*
 |--------------------------------------------------------------
 | FETCH CASH SESSIONS + NORMAL PAYMENTS + CREDIT PAYMENTS + EXPENSES
 | For the selected date (DATE(cs.opened_at) = ?)
 |
 | - Normal payments from payments table (by cash_session_id)
 | - Credit payments from debt_payments table (by cash_session_id)
 | - Expenses from expenses table (by cash_session_id)
 |
 | We aggregate in subqueries to avoid row multiplication.
 |--------------------------------------------------------------
*/

$sql = "
    SELECT
        cs.id,
        cs.cashier,
        cs.opened_at,
        cs.closed_at,
        cs.is_open,
        cs.opening_float,
        cs.closing_cash_expected,
        cs.closing_cash_counted,
        cs.variance,
        cs.closing_note,

        -- Normal payments (from payments)
        COALESCE(p.total_amount_due, 0)           AS total_amount_due,
        COALESCE(p.total_paid, 0)                 AS total_paid,
        COALESCE(p.total_change, 0)               AS total_change,
        COALESCE(p.cash_paid, 0)                  AS normal_cash_paid,
        COALESCE(p.mpesa_paid, 0)                 AS normal_mpesa_paid,
        COALESCE(p.bank_paid, 0)                  AS normal_bank_paid,
        COALESCE(p.receipt_count, 0)              AS normal_receipt_count,

        -- Credit payments (from debt_payments)
        COALESCE(dp.cash_paid, 0)                 AS dp_cash_paid,
        COALESCE(dp.mpesa_paid, 0)                AS dp_mpesa_paid,
        COALESCE(dp.bank_paid, 0)                 AS dp_bank_paid,
        COALESCE(dp.receipt_count, 0)             AS dp_receipt_count,

        -- Expenses (from expenses)
        COALESCE(e.total_expenses, 0)             AS total_expenses

    FROM cash_sessions cs

    -- Normal payments summary
    LEFT JOIN (
        SELECT
            cash_session_id,
            SUM(amount_due)                                         AS total_amount_due,
            SUM(paid_at)                                            AS total_paid,
            SUM(change_amount)                                      AS total_change,
            SUM(CASE WHEN payment_method = 'cash'  THEN paid_at END) AS cash_paid,
            SUM(CASE WHEN payment_method = 'mpesa' THEN paid_at END) AS mpesa_paid,
            SUM(CASE WHEN payment_method = 'bank'  THEN paid_at END) AS bank_paid,
            COUNT(DISTINCT receipt_id)                              AS receipt_count
        FROM payments
        GROUP BY cash_session_id
    ) p ON p.cash_session_id = cs.id

    -- Credit payments summary
    LEFT JOIN (
        SELECT
            cash_session_id,
            SUM(CASE WHEN payment_method = 'cash'  THEN amount_paid END) AS cash_paid,
            SUM(CASE WHEN payment_method = 'mpesa' THEN amount_paid END) AS mpesa_paid,
            SUM(CASE WHEN payment_method = 'bank'  THEN amount_paid END) AS bank_paid,
            COUNT(DISTINCT receipt_id)                                  AS receipt_count
        FROM debt_payments
        GROUP BY cash_session_id
    ) dp ON dp.cash_session_id = cs.id

    -- Expenses summary
    LEFT JOIN (
        SELECT
            cash_session_id,
            SUM(amount) AS total_expenses
        FROM expenses
        GROUP BY cash_session_id
    ) e ON e.cash_session_id = cs.id

    WHERE DATE(cs.opened_at) = ?
    ORDER BY cs.opened_at DESC
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $selected_date);
$stmt->execute();
$sessions = $stmt->get_result();
$stmt->close();

// Totals across all sessions (for summary box)
$grand_expected = 0;
$grand_counted  = 0;
$grand_variance = 0;

$page_title = "Cash Sessions – " . $selected_date;

// head.php will output <!DOCTYPE html>, <html>, <head> with this title
include("head.php");
?>

<body>

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

<!-- MAIN PAGE WRAPPER (aligned with other admin pages) -->
<div class="content-wrapper" id="content-wrapper">

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

    <!-- PAGE CONTENT -->
    <div class="page-content">

        <div class="page-header">
            <div class="page-header-main">
                <div class="page-title">Cash Sessions</div>
                <div class="page-subtitle">
                    Opened on <?= htmlspecialchars($selected_date) ?>
                </div>
            </div>
        </div>

        <div class="page-card">
            <div class="page-card-title-row">
                <div class="page-card-title">
                    Cash sessions for <?= htmlspecialchars($selected_date) ?>
                </div>

                <form method="get" class="filter-form">
                    <label for="date">Filter by date:</label>
                    <input
                        type="date"
                        id="date"
                        name="date"
                        value="<?= htmlspecialchars($selected_date) ?>"
                        required
                    >
                    <button type="submit" class="filter-btn">View</button>
                </form>
            </div>

            <div class="table-wrapper">
                <table>
                    <thead>
                    <tr>
                        <th>Session ID</th>
                        <th>Cashier</th>
                        <th>Opened at</th>
                        <th>Closed at</th>
                        <th>Status</th>

                        <th>Opening float (cash)</th>

                        <th>Cash received</th>
                        <th>M-Pesa received</th>
                        <th>Bank received</th>
                        <th>Change given</th>
                        <th>Expenses</th>

                        <th>Expected cash</th>
                        <th>Counted cash</th>
                        <th>Variance</th>

                        <th>Note</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if ($sessions->num_rows === 0): ?>
                        <tr>
                            <td colspan="15">No cash sessions found for this date.</td>
                        </tr>
                    <?php else: ?>
                        <?php while ($row = $sessions->fetch_assoc()): ?>
                            <?php
                            // Opening float
                            $openingFloat = isset($row['opening_float']) ? (float)$row['opening_float'] : 0.0;

                            // Normal + credit payment totals
                            $normalCash   = (float)$row['normal_cash_paid'];
                            $normalMpesa  = (float)$row['normal_mpesa_paid'];
                            $normalBank   = (float)$row['normal_bank_paid'];

                            $dpCash       = (float)$row['dp_cash_paid'];
                            $dpMpesa      = (float)$row['dp_mpesa_paid'];
                            $dpBank       = (float)$row['dp_bank_paid'];

                            $totalCash    = $normalCash + $dpCash;
                            $totalMpesa   = $normalMpesa + $dpMpesa;
                            $totalBank    = $normalBank + $dpBank;

                            $totalChange  = (float)$row['total_change'];
                            $expenses     = (float)$row['total_expenses'];

                            // Fallback expected if not stored
                            $fallbackExpected = $openingFloat + $totalCash - $totalChange - $expenses;
                            if ($fallbackExpected < 0) {
                                $fallbackExpected = 0.0;
                            }

                            // Use stored closing_cash_expected if available
                            $expected = isset($row['closing_cash_expected']) && $row['closing_cash_expected'] !== null
                                ? (float)$row['closing_cash_expected']
                                : $fallbackExpected;

                            // Counted cash from cash_sessions
                            $counted = isset($row['closing_cash_counted']) && $row['closing_cash_counted'] !== null
                                ? (float)$row['closing_cash_counted']
                                : 0.0;

                            // Variance from DB if present, otherwise compute
                            $variance = isset($row['variance']) && $row['variance'] !== null
                                ? (float)$row['variance']
                                : ($counted - $expected);

                            $grand_expected += $expected;
                            $grand_counted  += $counted;
                            $grand_variance += $variance;

                            $isOpen      = (int)($row['is_open'] ?? 0);
                            $statusLabel = $isOpen ? 'OPEN' : 'CLOSED';

                            $openedAt = $row['opened_at'] ?? '';
                            $closedAt = $row['closed_at'] ?? '';

                            $note = $row['closing_note'] ?? '';
                            ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>
                                <td><?= htmlspecialchars($row['cashier']) ?></td>
                                <td><?= htmlspecialchars($openedAt) ?></td>
                                <td><?= htmlspecialchars($closedAt) ?></td>
                                <td>
                                    <span class="status-pill <?= $isOpen ? 'status-open' : 'status-closed' ?>">
                                        <?= $statusLabel ?>
                                    </span>
                                </td>

                                <td class="numeric"><?= number_format($openingFloat, 2) ?></td>

                                <td class="numeric"><?= number_format($totalCash, 2) ?></td>
                                <td class="numeric"><?= number_format($totalMpesa, 2) ?></td>
                                <td class="numeric"><?= number_format($totalBank, 2) ?></td>
                                <td class="numeric"><?= number_format($totalChange, 2) ?></td>
                                <td class="numeric"><?= number_format($expenses, 2) ?></td>

                                <td class="numeric"><?= number_format($expected, 2) ?></td>
                                <td class="numeric"><?= number_format($counted, 2) ?></td>
                                <td class="numeric"><?= number_format($variance, 2) ?></td>

                                <td class="note-cell"><?= nl2br(htmlspecialchars($note)) ?></td>
                            </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="totals-box">
            <p>
                <span class="label">Total expected cash (all sessions): </span>
                <span class="value">KES <?= number_format($grand_expected, 2) ?></span>
            </p>
            <p>
                <span class="label">Total counted cash (all sessions): </span>
                <span class="value">KES <?= number_format($grand_counted, 2) ?></span>
            </p>
            <p>
                <span class="label">Total variance: </span>
                <span class="value">KES <?= number_format($grand_variance, 2) ?></span>
            </p>
        </div>

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

    </div> <!-- /.page-content -->

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

<style>
    /* ------------ LAYOUT & TOPBAR (UNIFORM ACROSS PAGES) ------------ */
    .content-wrapper {
        margin-left: 250px;
        padding: 24px 26px;
        background: var(--bg-main);
        min-height: 100vh;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        transition: margin-left 0.3s ease, background 0.3s ease;
    }

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

    .page-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 18px;
    }

    /* hide sidebar when .hidden is toggled via JS */
    .sidebar.hidden {
        display: none;
    }

    .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 ------------ */
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 10px;
    }

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

    .page-subtitle {
        font-size: 13px;
        color: #f4b400;
        margin-top: 4px;
    }

    /* ------------ CARD & TABLE ------------ */
    .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: 10px;
    }

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

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

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

    .filter-form input[type="date"]:focus {
        outline: none;
        background: #014b94;
        border-color: #f4b400;
    }

    body[data-theme="light"] .filter-form input[type="date"] {
        background: #ffffff;
        color: #111827;
        border-color: #cbd5f5;
    }

    body[data-theme="light"] .filter-form input[type="date"]:focus {
        background: #f9fafb;
        border-color: #facc15;
    }

    .filter-btn {
        padding: 7px 12px;
        border-radius: 6px;
        border: none;
        background: #f4b400;
        color: #111827;
        font-weight: 600;
        cursor: pointer;
        font-size: 13px;
    }

    .filter-btn:hover {
        background: #facc15;
    }

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

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

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

    th, td {
        padding: 8px 10px;
        border: 1px solid rgba(255,255,255,0.15);
        text-align: center;
        font-size: 12px;
        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;
    }

    .status-pill {
        padding: 3px 9px;
        border-radius: 999px;
        font-size: 11px;
        font-weight: 600;
        display: inline-block;
    }

    .status-open {
        background: rgba(16,185,129,0.18);
        color: #6ee7b7;
    }

    .status-closed {
        background: rgba(239,68,68,0.18);
        color: #fecaca;
    }

    body[data-theme="light"] .status-open {
        background: #dcfce7;
        color: #166534;
    }

    body[data-theme="light"] .status-closed {
        background: #fee2e2;
        color: #b91c1c;
    }

    .note-cell {
        max-width: 220px;
        white-space: normal;
    }

    /* ------------ TOTALS BOX & FOOTER ------------ */
    .totals-box {
        margin-top: 10px;
        margin-bottom: 10px;
        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);
        max-width: 700px;
        margin-inline: auto;
    }

    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,
    footer.footer {
        background: transparent !important;
        color: #D4AF37 !important;
        border-top: 2px solid #B8860B !important;
        text-align: center;
        margin-top: 16px;
        padding-top: 10px;
    }
</style>

<script>
// Sidebar toggle: hide sidebar completely and stretch content
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>
