<?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 + aggregated payments + expenses for that date ---
//
// Assumes:
//  - payments.cash_session_id (FK to cash_sessions.id)
//  - payments.payment_method IN ('cash','mpesa','bank')
//  - expenses.cash_session_id (FK to cash_sessions.id)
//
$sql = "
    SELECT
        cs.*,
        COALESCE(SUM(p.amount_due), 0) AS total_amount_due,
        COALESCE(SUM(p.paid_at), 0)    AS total_paid,
        COALESCE(SUM(p.change_amount), 0) AS total_change,

        COALESCE(SUM(CASE WHEN p.payment_method = 'cash'  THEN p.paid_at END), 0) AS total_cash_paid,
        COALESCE(SUM(CASE WHEN p.payment_method = 'mpesa' THEN p.paid_at END), 0) AS total_mpesa_paid,
        COALESCE(SUM(CASE WHEN p.payment_method = 'bank'  THEN p.paid_at END), 0) AS total_bank_paid,

        COALESCE(SUM(e.amount), 0) AS total_expenses
    FROM cash_sessions cs
    LEFT JOIN payments p  ON p.cash_session_id  = cs.id
    LEFT JOIN expenses e  ON e.cash_session_id  = cs.id
    WHERE DATE(cs.opened_at) = ?
    GROUP BY cs.id
    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;
?>
<!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;
        }

        .page-card-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
            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: var(--bg-main-soft);
            color: var(--text-main);
        }

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

        .filter-btn:hover {
            background: var(--accent-gold-soft);
        }

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

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

        .note-cell {
            max-width: 220px;
            white-space: normal;
        }
    </style>
</head>

<body>

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

<div class="content-area">

    <div class="page-header">
        <div class="page-title">Cash Sessions</div>
        <div class="page-subtitle">
            Opened on <?= htmlspecialchars($selected_date) ?>
        </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
                            $openingFloat = isset($row['opening_float']) ? (float)$row['opening_float'] : 0.0;

                            $totalCash   = (float)$row['total_cash_paid'];
                            $totalMpesa  = (float)$row['total_mpesa_paid'];
                            $totalBank   = (float)$row['total_bank_paid'];
                            $totalChange = (float)$row['total_change'];
                            $expenses    = (float)$row['total_expenses'];

                            // Same logic as close_cash_session: expected cash = opening + cash - change - expenses
                            $expected = $openingFloat + $totalCash - $totalChange - $expenses;
                            if ($expected < 0) $expected = 0.0;

                            $counted  = isset($row['closing_cash']) ? (float)$row['closing_cash'] : 0.0;
                            $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> <!-- end content-area -->

</body>
</html>
