<div class="page-header">
    <div>
        <h1><i class="bi bi-cash-stack me-2"></i>Cash Summary</h1>
        <p>Collections breakdown by payment mode.</p>
    </div>
    <a href="<?= url('cashier') ?>" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-cash-coin me-1"></i> Cashier Window
    </a>
</div>

<!-- Date filter -->
<form method="GET" class="card p-3 mb-4 d-flex flex-row flex-wrap gap-3 align-items-end">
    <div>
        <label class="form-label mb-1" style="font-size:.78rem;">From</label>
        <input type="date" name="from" class="form-control form-control-sm" value="<?= e($from) ?>">
    </div>
    <div>
        <label class="form-label mb-1" style="font-size:.78rem;">To</label>
        <input type="date" name="to" class="form-control form-control-sm" value="<?= e($to) ?>">
    </div>
    <button type="submit" class="btn btn-accent btn-sm">Filter</button>
    <a href="?" class="btn btn-outline-secondary btn-sm">This Month</a>
</form>

<?php
$grandTotal  = array_sum(array_column($byMode, 'total'));
$grandOrders = array_sum(array_column($byMode, 'orders'));
$modeColors  = ['#f97316','#3b82f6','#16a34a','#8b5cf6','#e11d48','#0891b2','#d97706'];
?>

<!-- Stat cards: one per mode + unpaid -->
<div class="row g-3 mb-4">
    <?php foreach ($byMode as $i => $row): ?>
    <div class="col-6 col-md-3">
        <div class="card p-3 h-100" style="border-left:4px solid <?= $modeColors[$i % count($modeColors)] ?>;">
            <div class="text-secondary mb-1" style="font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;">
                <?= e($row['mode']) ?>
            </div>
            <div class="fw-700 fs-5" style="color:<?= $modeColors[$i % count($modeColors)] ?>;">
                <?= money((float)$row['total']) ?>
            </div>
            <div class="text-secondary mt-1" style="font-size:.75rem;">
                <?= (int)$row['orders'] ?> order<?= (int)$row['orders'] !== 1 ? 's' : '' ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

    <!-- Unpaid card -->
    <?php if ((float)($unpaid['total'] ?? 0) > 0): ?>
    <div class="col-6 col-md-3">
        <div class="card p-3 h-100" style="border-left:4px solid #ef4444;">
            <div class="text-secondary mb-1" style="font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;">
                Unpaid
            </div>
            <div class="fw-700 fs-5 text-danger">
                <?= money((float)$unpaid['total']) ?>
            </div>
            <div class="text-secondary mt-1" style="font-size:.75rem;">
                <?= (int)$unpaid['orders'] ?> order<?= (int)$unpaid['orders'] !== 1 ? 's' : '' ?>
                &mdash; <a href="<?= url('cashier') ?>">Collect</a>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Summary table -->
<div class="card mb-4 p-0 overflow-hidden">
    <div class="card-header d-flex align-items-center justify-content-between">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-table text-accent"></i>
            <h6 class="card-title mb-0">Collection Breakdown</h6>
        </div>
        <span class="badge bg-light text-dark border">
            <?= date('d M Y', strtotime($from)) ?> — <?= date('d M Y', strtotime($to)) ?>
        </span>
    </div>
    <?php if (empty($byMode)): ?>
    <div class="text-center py-5 text-secondary">
        <i class="bi bi-inbox fs-2"></i>
        <p class="mt-2">No paid orders in this period.</p>
    </div>
    <?php else: ?>
    <table class="table table-hover mb-0">
        <thead class="table-light">
            <tr>
                <th>Payment Mode</th>
                <th class="text-center">Orders</th>
                <th class="text-end">Total Collected</th>
                <th class="text-end">Share</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($byMode as $i => $row): ?>
        <tr>
            <td>
                <span style="display:inline-block;width:10px;height:10px;border-radius:50%;
                             background:<?= $modeColors[$i % count($modeColors)] ?>;margin-right:6px;"></span>
                <strong><?= e($row['mode']) ?></strong>
            </td>
            <td class="text-center"><?= (int)$row['orders'] ?></td>
            <td class="text-end fw-700"><?= money((float)$row['total']) ?></td>
            <td class="text-end">
                <?php $pct = $grandTotal > 0 ? round(($row['total'] / $grandTotal) * 100, 1) : 0; ?>
                <div class="d-flex align-items-center justify-content-end gap-2">
                    <div style="width:80px;background:#f1f5f9;border-radius:4px;height:6px;overflow:hidden;">
                        <div style="width:<?= $pct ?>%;background:<?= $modeColors[$i % count($modeColors)] ?>;height:100%;border-radius:4px;"></div>
                    </div>
                    <span style="font-size:.8rem;min-width:38px;text-align:right;"><?= $pct ?>%</span>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot class="table-light fw-700">
            <tr>
                <td>Total</td>
                <td class="text-center"><?= $grandOrders ?></td>
                <td class="text-end"><?= money($grandTotal) ?></td>
                <td class="text-end">100%</td>
            </tr>
        </tfoot>
    </table>
    <?php endif; ?>
</div>

<?php if (!empty($daily)): ?>
<!-- Daily chart -->
<div class="card p-3">
    <div class="card-header border-0 p-0 mb-3">
        <h6 class="mb-0"><i class="bi bi-bar-chart-line text-accent me-2"></i>Daily Collections by Mode</h6>
    </div>
    <canvas id="cashChart" height="90"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
(function () {
    const raw    = <?= json_encode($daily) ?>;
    const colors = <?= json_encode($modeColors) ?>;

    const days  = [...new Set(raw.map(r => r.day))].sort();
    const modes = [...new Set(raw.map(r => r.mode))];

    const datasets = modes.map((mode, i) => ({
        label:           mode,
        data:            days.map(d => {
            const row = raw.find(r => r.day === d && r.mode === mode);
            return row ? parseFloat(row.total) : 0;
        }),
        backgroundColor: colors[i % colors.length] + 'cc',
        borderColor:     colors[i % colors.length],
        borderWidth:     1,
    }));

    new Chart(document.getElementById('cashChart'), {
        type: 'bar',
        data: { labels: days, datasets },
        options: {
            responsive: true,
            plugins: { legend: { position: 'bottom' } },
            scales: {
                x: { stacked: true },
                y: { stacked: true, beginAtZero: true },
            },
        },
    });
})();
</script>
<?php endif; ?>
