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

<div class="d-flex justify-content-end mb-3">
    <a href="<?= site_url('housekeeping/new') ?>" class="btn btn-primary btn-sm"><i class="bi bi-plus-lg me-1"></i>Create Task</a>
</div>

<div class="row g-3 mb-3">
    <div class="col-6 col-lg">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Rooms to Clean</div>
            <div class="fs-3 fw-bold"><?= $roomsToClean ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Cleaned Today</div>
            <div class="fs-3 fw-bold text-success"><?= $cleanedToday ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">In Progress</div>
            <div class="fs-3 fw-bold text-warning"><?= $inProgress ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Inspected</div>
            <div class="fs-3 fw-bold"><?= $inspected ?></div>
        </div></div>
    </div>
    <div class="col-6 col-lg">
        <div class="card h-100"><div class="card-body">
            <div class="text-muted small mb-1">Out of Service</div>
            <div class="fs-3 fw-bold text-danger"><?= $outOfService ?></div>
        </div></div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-8">
        <div class="card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                Live Tasks
                <a href="<?= site_url('rooms/board') ?>" class="small text-decoration-none">View All Rooms</a>
            </div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle small">
                    <thead><tr><th>Room</th><th>Task</th><th>Priority</th><th>Assigned To</th><th>Start Time</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                    <?php if (empty($liveTasks)): ?>
                        <tr><td colspan="7" class="text-center text-muted py-4">No active housekeeping tasks.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($liveTasks as $task):
                        $prio = $lookups->taskPriorities[$task->priority] ?? ['label' => ucfirst($task->priority), 'badge' => 'secondary'];
                        $status = $lookups->housekeepingTaskStatuses[$task->status] ?? ['label' => ucfirst($task->status), 'badge' => 'secondary'];
                    ?>
                        <tr>
                            <td class="fw-semibold"><?= esc($task->room_number) ?></td>
                            <td><?= esc($lookups->housekeepingTaskTypes[$task->task_type]['label'] ?? $task->task_type) ?></td>
                            <td><span class="badge bg-<?= $prio['badge'] ?>"><?= esc($prio['label']) ?></span></td>
                            <td class="text-muted"><?= esc($task->assigned_to_name ?: 'Unassigned') ?></td>
                            <td class="text-muted"><?= $task->start_time ? esc(date('g:i a', strtotime($task->start_time))) : '—' ?></td>
                            <td><span class="badge bg-<?= $status['badge'] ?>"><?= esc($status['label']) ?></span></td>
                            <td class="text-end">
                                <a href="<?= site_url('housekeeping/' . $task->id) ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-eye"></i></a>
                                <?php if ($task->status === 'not_started'): ?>
                                    <form action="<?= site_url('housekeeping/' . $task->id . '/start') ?>" method="post" class="d-inline">
                                        <?= csrf_field() ?>
                                        <button type="submit" class="btn btn-sm btn-outline-secondary">Start</button>
                                    </form>
                                <?php elseif ($task->status === 'in_progress'): ?>
                                    <form action="<?= site_url('housekeeping/' . $task->id . '/complete') ?>" method="post" class="d-inline">
                                        <?= csrf_field() ?>
                                        <button type="submit" class="btn btn-sm btn-outline-success">Complete</button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card mb-3">
            <div class="card-header">Room Status Overview</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="roomStatusChart" width="130" height="130"></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.6rem;">Total Rooms</div>
                    </div>
                </div>
                <ul class="list-unstyled small mb-0">
                    <?php $colors = ['clean' => '#22c55e', 'dirty' => '#f59e0b', 'occupied' => '#4f46e5', 'out_of_service' => '#ef4444']; ?>
                    <?php foreach ($lookups->roomStatuses as $key => $meta): ?>
                        <li class="d-flex align-items-center gap-2 mb-1">
                            <span style="width:8px;height:8px;border-radius:50%;background:<?= $colors[$key] ?>;display:inline-block;"></span>
                            <?= esc($meta['label']) ?>: <span class="fw-semibold"><?= $roomStatusCounts[$key] ?? 0 ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header">Tasks Completed (7 days)</div>
            <div class="card-body"><canvas id="trendChart" height="90"></canvas></div>
        </div>

        <div class="card">
            <div class="card-header">Quick Actions</div>
            <div class="card-body d-flex flex-column gap-2">
                <a href="<?= site_url('housekeeping/new') ?>" class="btn btn-outline-primary btn-sm"><i class="bi bi-plus-lg me-1"></i>Create Housekeeping Task</a>
                <a href="<?= site_url('rooms/board') ?>" class="btn btn-outline-secondary btn-sm"><i class="bi bi-door-closed me-1"></i>View Room Assignments</a>
            </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>
new Chart(document.getElementById('roomStatusChart'), {
    type: 'doughnut',
    data: {
        labels: ['Clean', 'Dirty', 'Occupied', 'Out of Service'],
        datasets: [{
            data: [<?= (int) ($roomStatusCounts['clean'] ?? 0) ?>, <?= (int) ($roomStatusCounts['dirty'] ?? 0) ?>, <?= (int) ($roomStatusCounts['occupied'] ?? 0) ?>, <?= (int) ($roomStatusCounts['out_of_service'] ?? 0) ?>],
            backgroundColor: ['#22c55e', '#f59e0b', '#4f46e5', '#ef4444'],
            borderWidth: 0,
        }],
    },
    options: { cutout: '70%', plugins: { legend: { display: false } } },
});

new Chart(document.getElementById('trendChart'), {
    type: 'line',
    data: {
        labels: [<?= implode(',', array_map(static fn ($d) => json_encode(date('D', strtotime($d))), array_keys($completedTrend))) ?>],
        datasets: [{
            data: [<?= implode(',', array_values($completedTrend)) ?>],
            borderColor: getComputedStyle(document.documentElement).getPropertyValue('--brand').trim() || '#4f46e5',
            fill: false, tension: 0.3, pointRadius: 2,
        }],
    },
    options: { plugins: { legend: { display: false } } },
});
</script>
<?= $this->endSection() ?>
