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

<?php if ($openAlertsCount > 0): ?>
<a href="<?= site_url('ai/alerts') ?>" class="text-decoration-none">
<div class="alert alert-warning d-flex align-items-center gap-2 py-2 mb-3">
    <i class="bi bi-exclamation-triangle-fill"></i>
    <span class="text-dark"><?= $openAlertsCount ?> AI-flagged anomal<?= $openAlertsCount === 1 ? 'y' : 'ies' ?> awaiting review.</span>
</div>
</a>
<?php endif; ?>

<?php if ($dailyBriefingEnabled): ?>
<div class="card shadow-sm mb-3" id="briefingCard">
    <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="d-flex justify-content-between align-items-start">
                <div class="fw-semibold small mb-1">AI Morning Briefing <span class="text-muted fw-normal">— <?= esc(date('d M Y')) ?>, narrates real numbers only</span></div>
                <?php if ($dailyBriefing): ?>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="regenerateBriefingBtn" title="Regenerate with the latest data"><i class="bi bi-arrow-clockwise"></i></button>
                <?php endif; ?>
            </div>
            <div id="briefingText" class="small">
                <?php if ($dailyBriefing): ?>
                    <?= nl2br(esc($dailyBriefing->summary_text)) ?>
                <?php else: ?>
                    <span class="text-muted">Not generated yet today.</span>
                    <button type="button" class="btn btn-sm btn-primary ms-2" id="generateBriefingBtn"><i class="bi bi-stars me-1"></i>Generate Briefing</button>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row g-3 mb-3">
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div class="text-muted small">Occupancy Today</div>
                <div class="stat-icon-sm" style="background: color-mix(in srgb, var(--brand) 12%, white); color: var(--brand);"><i class="bi bi-door-open"></i></div>
            </div>
            <div class="fs-3 fw-bold"><?= $occupancyToday ?>%</div>
            <div class="text-muted small mb-1"><?= $occupiedToday ?> / <?= $totalRooms ?> Rooms</div>
            <div class="small <?= $occupancyChangePct >= 0 ? 'text-success' : 'text-danger' ?>">
                <i class="bi bi-arrow-<?= $occupancyChangePct >= 0 ? 'up' : 'down' ?>"></i> <?= abs($occupancyChangePct) ?>% vs yesterday
            </div>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div class="text-muted small">Arrivals Today</div>
                <div class="stat-icon-sm" style="background: #dcfce7; color: #16a34a;"><i class="bi bi-box-arrow-in-right"></i></div>
            </div>
            <div class="fs-3 fw-bold"><?= count($arrivalsToday) ?></div>
            <div class="text-muted small mb-1">Reservations</div>
            <a href="<?= site_url('checkin') ?>" class="small text-decoration-none">View arrivals <i class="bi bi-arrow-right"></i></a>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div class="text-muted small">Departures Today</div>
                <div class="stat-icon-sm" style="background: #fef3c7; color: #d97706;"><i class="bi bi-box-arrow-right"></i></div>
            </div>
            <div class="fs-3 fw-bold"><?= count($departuresToday) ?></div>
            <div class="text-muted small mb-1">Reservations</div>
            <a href="<?= site_url('checkout') ?>" class="small text-decoration-none">View departures <i class="bi bi-arrow-right"></i></a>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div class="text-muted small">In House Guests</div>
                <div class="stat-icon-sm" style="background: #e0e7ff; color: #4f46e5;"><i class="bi bi-people"></i></div>
            </div>
            <div class="fs-3 fw-bold"><?= $inHouseGuests ?></div>
            <div class="text-muted small mb-1">Guests</div>
            <a href="<?= site_url('guests') ?>" class="small text-decoration-none">View guests <i class="bi bi-arrow-right"></i></a>
        </div></div>
    </div>
    <div class="col-6 col-xl">
        <div class="card h-100"><div class="card-body">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div class="text-muted small">Revenue Today</div>
                <div class="stat-icon-sm" style="background: #dcfce7; color: #16a34a;"><i class="bi bi-currency-exchange"></i></div>
            </div>
            <div class="fs-3 fw-bold"><?= format_money($revenueToday) ?></div>
            <div class="text-muted small mb-1">Generated</div>
            <div class="small <?= $revenueChangePct >= 0 ? 'text-success' : 'text-danger' ?>">
                <i class="bi bi-arrow-<?= $revenueChangePct >= 0 ? 'up' : 'down' ?>"></i> <?= abs($revenueChangePct) ?>% vs yesterday
            </div>
        </div></div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-lg-7">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                Occupancy Overview
                <span class="badge bg-light text-dark border">7 Days</span>
            </div>
            <div class="card-body"><canvas id="occupancyChart" height="110"></canvas></div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="card h-100">
            <div class="card-header">Room Status</div>
            <div class="card-body d-flex align-items-center gap-3">
                <div class="position-relative" style="width: 150px; height: 150px; flex-shrink: 0;">
                    <canvas id="roomStatusChart" width="150" height="150"></canvas>
                    <div class="position-absolute top-50 start-50 translate-middle text-center">
                        <div class="fw-bold fs-5"><?= $totalRooms ?></div>
                        <div class="text-muted" style="font-size: 0.65rem;">Total Rooms</div>
                    </div>
                </div>
                <ul class="list-unstyled small mb-0 flex-grow-1">
                    <?php
                    $statusMeta = [
                        'occupied'       => ['label' => 'Occupied', 'color' => '#4f46e5'],
                        'clean'          => ['label' => 'Vacant Clean', 'color' => '#22c55e'],
                        'dirty'          => ['label' => 'Vacant Dirty', 'color' => '#f59e0b'],
                        'out_of_service' => ['label' => 'Out of Order', 'color' => '#ef4444'],
                    ];
                    foreach ($statusMeta 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"><?= $roomStatusCounts[$key] ?? 0 ?> (<?= $totalRooms > 0 ? round((($roomStatusCounts[$key] ?? 0) / $totalRooms) * 100) : 0 ?>%)</span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <div class="card-footer bg-white border-0 pt-0">
                <a href="<?= site_url('rooms/board') ?>" class="small text-decoration-none">View room overview <i class="bi bi-arrow-right"></i></a>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-lg-4">
        <div class="card h-100">
            <div class="card-header">Today's Revenue Summary</div>
            <div class="card-body">
                <div class="fs-4 fw-bold"><?= format_money($revenueToday) ?></div>
                <div class="small <?= $revenueChangePct >= 0 ? 'text-success' : 'text-danger' ?> mb-3">
                    <i class="bi bi-arrow-<?= $revenueChangePct >= 0 ? 'up' : 'down' ?>"></i> <?= abs($revenueChangePct) ?>% vs yesterday
                </div>
                <?php
                $revenueBreakdown = [
                    'Room Revenue'   => $roomRevenue,
                    'F&B Revenue'    => $fnbRevenue,
                    'Other Services' => $otherRevenue,
                ];
                foreach ($revenueBreakdown as $label => $amount):
                    $pct = (float) $revenueToday > 0 ? round(((float) $amount / (float) $revenueToday) * 100, 1) : 0;
                ?>
                    <div class="d-flex justify-content-between small mb-1">
                        <span class="text-muted"><?= esc($label) ?></span>
                        <span class="fw-semibold"><?= format_money($amount) ?> <span class="text-muted"><?= $pct ?>%</span></span>
                    </div>
                    <div class="progress mb-2" style="height: 5px;">
                        <div class="progress-bar" style="width: <?= $pct ?>%; background: var(--brand);"></div>
                    </div>
                <?php endforeach; ?>
                <a href="<?= site_url('billing-finance') ?>" class="small text-decoration-none">View full report <i class="bi bi-arrow-right"></i></a>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                Reservations Overview
                <span class="badge bg-light text-dark border">This Month</span>
            </div>
            <div class="card-body">
                <div class="row g-2 text-center">
                    <div class="col-6">
                        <div class="text-muted small">Total Reservations</div>
                        <div class="fs-4 fw-bold"><?= $reservations['total'] ?></div>
                    </div>
                    <div class="col-6">
                        <div class="text-success small">Confirmed</div>
                        <div class="fs-4 fw-bold text-success"><?= $reservations['confirmed'] ?></div>
                    </div>
                    <div class="col-6 mt-2">
                        <div class="text-danger small">Cancelled</div>
                        <div class="fs-5 fw-bold text-danger"><?= $reservations['cancelled'] ?></div>
                    </div>
                    <div class="col-6 mt-2">
                        <div class="text-warning small">No Show</div>
                        <div class="fs-5 fw-bold text-warning"><?= $reservations['no_show'] ?></div>
                    </div>
                </div>
                <a href="<?= site_url('bookings/calendar') ?>" class="small text-decoration-none d-inline-block mt-3">View all reservations <i class="bi bi-arrow-right"></i></a>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card h-100">
            <div class="card-header">Top Room Types (Occupancy)</div>
            <div class="card-body">
                <?php if (empty($roomTypeOccupancy)): ?>
                    <p class="text-muted small mb-0">No room types yet.</p>
                <?php endif; ?>
                <?php foreach ($roomTypeOccupancy as $rt): ?>
                    <div class="d-flex justify-content-between small mb-1">
                        <span><?= esc($rt->name) ?></span>
                        <span class="fw-semibold"><?= $rt->pct ?>%</span>
                    </div>
                    <div class="progress mb-2" style="height: 6px;">
                        <div class="progress-bar" style="width: <?= $rt->pct ?>%; background: var(--brand);"></div>
                    </div>
                <?php endforeach; ?>
                <a href="<?= site_url('room-types') ?>" class="small text-decoration-none">View report <i class="bi bi-arrow-right"></i></a>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-lg-7">
        <div class="card h-100">
            <div class="card-header">Tasks &amp; Alerts</div>
            <div class="list-group list-group-flush">
                <?php if (($roomStatusCounts['dirty'] ?? 0) > 0): ?>
                <div class="list-group-item d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center gap-3">
                        <span class="text-warning fs-5"><i class="bi bi-exclamation-triangle-fill"></i></span>
                        <div>
                            <div class="fw-semibold small"><?= $roomStatusCounts['dirty'] ?> room(s) are dirty</div>
                            <div class="text-muted small">Need to be cleaned</div>
                        </div>
                    </div>
                    <a href="<?= site_url('rooms/board') ?>" class="btn btn-sm btn-outline-secondary">View Rooms</a>
                </div>
                <?php endif; ?>
                <?php if ($eventsToday > 0): ?>
                <div class="list-group-item d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center gap-3">
                        <span style="color: var(--brand);" class="fs-5"><i class="bi bi-calendar-event-fill"></i></span>
                        <div>
                            <div class="fw-semibold small"><?= $eventsToday ?> event(s) today</div>
                            <div class="text-muted small">Check event schedule</div>
                        </div>
                    </div>
                    <a href="<?= site_url('events') ?>" class="btn btn-sm btn-outline-secondary">View Events</a>
                </div>
                <?php endif; ?>
                <div class="list-group-item d-flex align-items-center justify-content-between text-muted">
                    <div class="d-flex align-items-center gap-3">
                        <span class="fs-5"><i class="bi bi-tools"></i></span>
                        <div>
                            <div class="fw-semibold small">Maintenance Requests</div>
                            <div class="small">Coming in a future update</div>
                        </div>
                    </div>
                    <span class="soon-badge">Soon</span>
                </div>
                <div class="list-group-item d-flex align-items-center justify-content-between text-muted">
                    <div class="d-flex align-items-center gap-3">
                        <span class="fs-5"><i class="bi bi-box-seam"></i></span>
                        <div>
                            <div class="fw-semibold small">Low Inventory Alert</div>
                            <div class="small">Coming in a future update</div>
                        </div>
                    </div>
                    <span class="soon-badge">Soon</span>
                </div>
                <?php if (($roomStatusCounts['dirty'] ?? 0) === 0 && $eventsToday === 0): ?>
                <div class="list-group-item text-center text-muted small py-3">Nothing else needs attention right now.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="card h-100">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="arrDepTabs">
                    <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#arrTab" type="button">Arrivals (<?= count($arrivalsToday) ?>)</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#depTab" type="button">Departures (<?= count($departuresToday) ?>)</button></li>
                </ul>
            </div>
            <div class="tab-content">
                <div class="tab-pane fade show active" id="arrTab">
                    <div class="list-group list-group-flush">
                        <?php if (empty($arrivalsToday)): ?>
                            <div class="list-group-item text-center text-muted small py-4">No arrivals today.</div>
                        <?php endif; ?>
                        <?php foreach ($arrivalsToday as $b): ?>
                            <a href="<?= site_url('bookings/' . $b->id) ?>" class="list-group-item d-flex align-items-center gap-2 text-decoration-none text-dark">
                                <div class="user-avatar" style="width:32px;height:32px;font-size:0.7rem;"><?= esc(strtoupper(substr($b->guest_name, 0, 1))) ?></div>
                                <div class="flex-grow-1">
                                    <div class="small fw-semibold"><?= esc($b->guest_name) ?></div>
                                    <div class="text-muted" style="font-size: 0.72rem;"><?= esc($b->room_type_name) ?></div>
                                </div>
                                <span class="badge bg-light text-dark border"><?= esc($b->room_number) ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="tab-pane fade" id="depTab">
                    <div class="list-group list-group-flush">
                        <?php if (empty($departuresToday)): ?>
                            <div class="list-group-item text-center text-muted small py-4">No departures today.</div>
                        <?php endif; ?>
                        <?php foreach ($departuresToday as $b): ?>
                            <a href="<?= site_url('bookings/' . $b->id) ?>" class="list-group-item d-flex align-items-center gap-2 text-decoration-none text-dark">
                                <div class="user-avatar" style="width:32px;height:32px;font-size:0.7rem;"><?= esc(strtoupper(substr($b->guest_name, 0, 1))) ?></div>
                                <div class="flex-grow-1">
                                    <div class="small fw-semibold"><?= esc($b->guest_name) ?></div>
                                    <div class="text-muted" style="font-size: 0.72rem;"><?= esc($b->room_type_name) ?></div>
                                </div>
                                <span class="badge bg-light text-dark border"><?= esc($b->room_number) ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="card-footer bg-white border-0">
                <a href="<?= site_url('bookings/calendar') ?>" class="small text-decoration-none">View all bookings <i class="bi bi-arrow-right"></i></a>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        Recent Activity
        <a href="<?= site_url('activity-log') ?>" class="small text-decoration-none">View all activity <i class="bi bi-arrow-right"></i></a>
    </div>
    <ul class="list-group list-group-flush">
        <?php if (empty($recentActivity)): ?>
            <li class="list-group-item text-center text-muted py-4">No activity recorded yet.</li>
        <?php endif; ?>
        <?php foreach ($recentActivity as $entry): ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
                <div class="small">
                    <span class="fw-semibold"><?= esc($entry->user_name ?? 'System') ?></span>
                    &mdash; <?= esc($entry->action) ?>
                </div>
                <div class="text-muted small text-nowrap ms-3"><?= esc(date('d M, g:i a', strtotime($entry->created_at))) ?></div>
            </li>
        <?php endforeach; ?>
    </ul>
</div>

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

<?= $this->section('styles') ?>
.stat-icon-sm { width: 34px; height: 34px; border-radius: 9px; display: flex; align-items: center; justify-content: center; font-size: 1rem; }
<?= $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('occupancyChart'), {
    type: 'line',
    data: {
        labels: <?= json_encode(array_map(static fn ($d) => date('M j', strtotime($d['date'])), $occupancyTrend)) ?>,
        datasets: [{
            label: 'Occupancy %',
            data: <?= json_encode(array_map(static fn ($d) => $d['pct'], $occupancyTrend)) ?>,
            borderColor: brand,
            backgroundColor: brand + '22',
            fill: true,
            tension: 0.35,
            pointBackgroundColor: brand,
            pointRadius: 3,
        }],
    },
    options: {
        plugins: { legend: { display: false } },
        scales: { y: { min: 0, max: 100, ticks: { callback: (v) => v + '%' } } },
    },
});

new Chart(document.getElementById('roomStatusChart'), {
    type: 'doughnut',
    data: {
        labels: ['Occupied', 'Vacant Clean', 'Vacant Dirty', 'Out of Order'],
        datasets: [{
            data: [
                <?= (int) ($roomStatusCounts['occupied'] ?? 0) ?>,
                <?= (int) ($roomStatusCounts['clean'] ?? 0) ?>,
                <?= (int) ($roomStatusCounts['dirty'] ?? 0) ?>,
                <?= (int) ($roomStatusCounts['out_of_service'] ?? 0) ?>,
            ],
            backgroundColor: ['#4f46e5', '#22c55e', '#f59e0b', '#ef4444'],
            borderWidth: 0,
        }],
    },
    options: {
        cutout: '72%',
        plugins: { legend: { display: false } },
    },
});

<?php if ($dailyBriefingEnabled): ?>
function requestBriefing(regenerate) {
    const textEl = document.getElementById('briefingText');
    textEl.textContent = '';
    const spinner = document.createElement('span');
    spinner.className = 'text-muted';
    spinner.textContent = 'Generating this morning\'s briefing...';
    textEl.appendChild(spinner);

    window.maxyieldsPost('<?= site_url('dashboard/generate-briefing') ?>', regenerate ? { regenerate: '1' } : {})
        .then(function (data) {
            textEl.textContent = '';

            if (! data.success) {
                const err = document.createElement('span');
                err.className = 'text-danger';
                err.textContent = data.error;
                textEl.appendChild(err);
                return;
            }

            // textContent + <br> via innerText-safe split, not innerHTML —
            // this is Claude's own generated prose, never inserted as raw HTML.
            data.text.split('\n').forEach(function (line, i) {
                if (i > 0) { textEl.appendChild(document.createElement('br')); }
                textEl.appendChild(document.createTextNode(line));
            });
        })
        .catch(function () {
            textEl.textContent = 'Could not reach the server — please try again.';
        });
}

const generateBtn = document.getElementById('generateBriefingBtn');
if (generateBtn) { generateBtn.addEventListener('click', function () { requestBriefing(false); }); }

const regenerateBtn = document.getElementById('regenerateBriefingBtn');
if (regenerateBtn) { regenerateBtn.addEventListener('click', function () { requestBriefing(true); }); }
<?php endif; ?>
</script>
<?= $this->endSection() ?>
