<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <form action="<?= site_url('reports') ?>" method="get" class="d-flex align-items-center gap-2">
        <input type="date" class="form-control form-control-sm" name="date_from" value="<?= esc($dateFrom) ?>">
        <span class="text-muted small">to</span>
        <input type="date" class="form-control form-control-sm" name="date_to" value="<?= esc($dateTo) ?>">
        <button type="submit" class="btn btn-sm btn-outline-primary"><i class="bi bi-funnel me-1"></i>Filters</button>
    </form>
    <div class="d-flex gap-2">
        <button type="button" class="btn btn-sm btn-primary" id="narrateBtn"><i class="bi bi-stars me-1"></i>Summarize this</button>
        <a href="<?= site_url('reports/profit-loss?date_from=' . $dateFrom . '&date_to=' . $dateTo) ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-graph-up-arrow me-1"></i>Profit &amp; Loss</a>
        <a href="<?= site_url('reports/export.csv?date_from=' . $dateFrom . '&date_to=' . $dateTo) ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-filetype-csv me-1"></i>Export CSV</a>
        <a href="<?= site_url('reports/export.pdf?date_from=' . $dateFrom . '&date_to=' . $dateTo) ?>" class="btn btn-sm btn-outline-secondary" target="_blank"><i class="bi bi-file-earmark-pdf me-1"></i>Export PDF</a>
    </div>
</div>

<div class="card shadow-sm mb-3 d-none" id="narrationCard">
    <div class="card-body d-flex gap-3 align-items-start">
        <div class="rounded-3 bg-primary-subtle text-primary d-flex align-items-center justify-content-center flex-shrink-0" style="width: 40px; height: 40px;"><i class="bi bi-stars"></i></div>
        <div class="flex-grow-1">
            <div class="fw-semibold small mb-1">AI Summary <span class="text-muted fw-normal">— narrates the real figures above, never its own numbers</span></div>
            <div id="narrationText" class="small"></div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Occupancy</div>
            <div class="fs-3 fw-bold"><?= $kpis['occupancy'] ?>%</div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">ADR <span class="text-muted" style="font-size:0.65rem;">(Avg Daily Rate)</span></div>
            <div class="fs-3 fw-bold"><?= format_money($kpis['adr']) ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">RevPAR <span class="text-muted" style="font-size:0.65rem;">(Rev/Available Room)</span></div>
            <div class="fs-3 fw-bold"><?= format_money($kpis['revpar']) ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Revenue</div>
            <div class="fs-3 fw-bold"><?= format_money($kpis['revenue']) ?></div>
        </div></div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Repeat Guest Rate <span class="text-muted" style="font-size:0.65rem;">(all-time)</span></div>
            <div class="fs-3 fw-bold"><?= $kpis['repeatGuestRate'] ?>%</div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Avg Spend / Guest <span class="text-muted" style="font-size:0.65rem;">(all-time)</span></div>
            <div class="fs-3 fw-bold"><?= format_money($kpis['avgSpendPerGuest']) ?></div>
        </div></div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-lg-6">
        <div class="card h-100">
            <div class="card-header">Occupancy Trend</div>
            <div class="card-body"><canvas id="occChart" height="140"></canvas></div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card h-100">
            <div class="card-header">Revenue Trend</div>
            <div class="card-body"><canvas id="revChart" height="140"></canvas></div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">Top Room Types by Booked Revenue</div>
            <div class="card-body">
                <?php if (empty($roomTypeRevenue)): ?>
                    <p class="text-muted small mb-0">No bookings in this range.</p>
                <?php endif; ?>
                <?php $max = $roomTypeRevenue ? max($roomTypeRevenue) : 1; ?>
                <?php foreach ($roomTypeRevenue as $type => $amount): ?>
                    <div class="d-flex justify-content-between small mb-1">
                        <span><?= esc($type) ?></span>
                        <span class="fw-semibold"><?= format_money($amount) ?></span>
                    </div>
                    <div class="progress mb-2" style="height: 6px;">
                        <div class="progress-bar" style="width: <?= (float) $max > 0 ? round((float) $amount / (float) $max * 100) : 0 ?>%; background: var(--brand);"></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">Revenue by Category</div>
            <div class="card-body d-flex align-items-center gap-3">
                <div class="position-relative" style="width: 130px; height: 130px; flex-shrink: 0;">
                    <canvas id="catChart" width="130" height="130"></canvas>
                </div>
                <ul class="list-unstyled small mb-0 flex-grow-1">
                    <?php
                    $catMeta = [
                        'room_charge' => ['label' => 'Rooms', 'color' => '#4f46e5'],
                        'restaurant'  => ['label' => 'F&B', 'color' => '#22c55e'],
                        'event'       => ['label' => 'Events', 'color' => '#f59e0b'],
                        'other'       => ['label' => 'Other', 'color' => '#9ca3af'],
                    ];
                    foreach ($catMeta as $key => $meta): ?>
                        <li class="d-flex align-items-center justify-content-between mb-2">
                            <span class="d-flex align-items-center gap-2">
                                <span style="width:9px;height:9px;border-radius:50%;background:<?= $meta['color'] ?>;display:inline-block;"></span>
                                <?= esc($meta['label']) ?>
                            </span>
                            <span class="fw-semibold"><?= format_money($categoryTotals[$key] ?? '0.00') ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<script>
const brand = getComputedStyle(document.documentElement).getPropertyValue('--brand').trim() || '#4f46e5';

new Chart(document.getElementById('occChart'), {
    type: 'line',
    data: {
        labels: [<?= implode(',', array_map(static fn ($d) => json_encode(date('j M', strtotime($d))), array_keys($occupancyTrend))) ?>],
        datasets: [{ data: [<?= implode(',', $occupancyTrend) ?>], borderColor: brand, backgroundColor: brand + '22', fill: true, tension: 0.3, pointRadius: 2 }],
    },
    options: { plugins: { legend: { display: false } }, scales: { y: { min: 0, max: 100, ticks: { callback: (v) => v + '%' } } } },
});

new Chart(document.getElementById('revChart'), {
    type: 'bar',
    data: {
        labels: [<?= implode(',', array_map(static fn ($d) => json_encode(date('j M', strtotime($d))), array_keys($revenueTrend))) ?>],
        datasets: [{ data: [<?= implode(',', $revenueTrend) ?>], backgroundColor: brand, borderRadius: 4 }],
    },
    options: { plugins: { legend: { display: false } } },
});

new Chart(document.getElementById('catChart'), {
    type: 'doughnut',
    data: {
        labels: <?= json_encode(array_column($catMeta ?? [], 'label')) ?>,
        datasets: [{
            data: [<?= (float) ($categoryTotals['room_charge'] ?? 0) ?>, <?= (float) ($categoryTotals['restaurant'] ?? 0) ?>, <?= (float) ($categoryTotals['event'] ?? 0) ?>, <?= (float) ($categoryTotals['other'] ?? 0) ?>],
            backgroundColor: ['#4f46e5', '#22c55e', '#f59e0b', '#9ca3af'],
            borderWidth: 0,
        }],
    },
    options: { cutout: '65%', plugins: { legend: { display: false } } },
});

document.getElementById('narrateBtn').addEventListener('click', function () {
    const btn = this;
    const card = document.getElementById('narrationCard');
    const textEl = document.getElementById('narrationText');

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Summarizing...';
    card.classList.remove('d-none');
    textEl.textContent = 'Asking Claude to summarize the figures above...';

    window.maxyieldsPost('<?= site_url('reports/narrate-kpis') ?>?date_from=<?= esc($dateFrom) ?>&date_to=<?= esc($dateTo) ?>', {})
        .then(function (data) {
            textEl.textContent = data.success ? data.text : ('Could not generate a summary: ' + data.error);
        })
        .catch(function () {
            textEl.textContent = 'Could not reach the server — please try again.';
        })
        .finally(function () {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-stars me-1"></i>Summarize this';
        });
});
</script>
<?= $this->endSection() ?>
