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

<?php
$tabs = [
    'all'         => 'All',
    'open'        => 'Open',
    'in_progress' => 'In Progress',
    'overdue'     => 'Overdue',
    'completed'   => 'Completed',
];
?>

<div class="d-flex justify-content-end mb-3">
    <a href="<?= site_url('maintenance/new') ?>" class="btn btn-primary btn-sm"><i class="bi bi-plus-lg me-1"></i>New Work Order</a>
</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">Open Work Orders</div>
            <div class="fs-3 fw-bold"><?= $stats['open'] ?></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">In Progress</div>
            <div class="fs-3 fw-bold text-warning"><?= $stats['inProgress'] ?></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">Completed Today</div>
            <div class="fs-3 fw-bold text-success"><?= $stats['completedToday'] ?></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">Overdue</div>
            <div class="fs-3 fw-bold text-danger"><?= $stats['overdue'] ?></div>
        </div></div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-8">
        <div class="card mb-3">
            <div class="card-header p-0">
                <ul class="nav nav-tabs border-0 px-2 pt-2">
                    <?php foreach ($tabs as $key => $label): ?>
                        <li class="nav-item"><a class="nav-link <?= $tab === $key ? 'active' : '' ?>" href="<?= site_url('maintenance?tab=' . $key) ?>"><?= esc($label) ?></a></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle small">
                    <thead><tr><th>WO#</th><th>Title</th><th>Asset</th><th>Priority</th><th>Status</th><th>Due</th><th></th></tr></thead>
                    <tbody>
                    <?php if (empty($orders)): ?>
                        <tr><td colspan="7" class="text-center text-muted py-4">No work orders in this view.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($orders as $wo):
                        $prio = $lookups->taskPriorities[$wo->priority] ?? ['label' => ucfirst($wo->priority), 'badge' => 'secondary'];
                        $isOverdue = in_array($wo->status, ['open', 'in_progress'], true) && $wo->due_date !== null && $wo->due_date < date('Y-m-d');
                        $status = $isOverdue ? ['label' => 'Overdue', 'badge' => 'danger'] : ($lookups->workOrderStatuses[$wo->status] ?? ['label' => ucfirst($wo->status), 'badge' => 'secondary']);
                    ?>
                        <tr>
                            <td class="fw-semibold">WO-<?= sprintf('%04d', $wo->id) ?></td>
                            <td><?= esc($wo->title) ?></td>
                            <td class="text-muted"><?= esc($wo->asset ?: ($wo->room_number ? 'Room ' . $wo->room_number : '—')) ?></td>
                            <td><span class="badge bg-<?= $prio['badge'] ?>"><?= esc($prio['label']) ?></span></td>
                            <td><span class="badge bg-<?= $status['badge'] ?>"><?= esc($status['label']) ?></span></td>
                            <td class="text-muted"><?= $wo->due_date ? esc(date('d M Y', strtotime($wo->due_date))) : '—' ?></td>
                            <td class="text-end">
                                <a href="<?= site_url('maintenance/' . $wo->id) ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-eye"></i></a>
                                <?php if ($wo->status === 'open'): ?>
                                    <form action="<?= site_url('maintenance/' . $wo->id . '/start') ?>" method="post" class="d-inline">
                                        <?= csrf_field() ?>
                                        <button type="submit" class="btn btn-sm btn-outline-secondary">Start</button>
                                    </form>
                                <?php elseif ($wo->status === 'in_progress'): ?>
                                    <form action="<?= site_url('maintenance/' . $wo->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">Maintenance 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="priorityChart" width="130" height="130"></canvas>
                    <div class="position-absolute top-50 start-50 translate-middle text-center">
                        <div class="fw-bold fs-5"><?= $stats['open'] + $stats['inProgress'] ?></div>
                        <div class="text-muted" style="font-size: 0.6rem;">Open</div>
                    </div>
                </div>
                <ul class="list-unstyled small mb-0">
                    <li class="d-flex align-items-center gap-2 mb-1"><span style="width:8px;height:8px;border-radius:50%;background:#ef4444;display:inline-block;"></span>High: <span class="fw-semibold"><?= $stats['byPriority']['high'] ?></span></li>
                    <li class="d-flex align-items-center gap-2 mb-1"><span style="width:8px;height:8px;border-radius:50%;background:#f59e0b;display:inline-block;"></span>Medium: <span class="fw-semibold"><?= $stats['byPriority']['medium'] ?></span></li>
                    <li class="d-flex align-items-center gap-2 mb-1"><span style="width:8px;height:8px;border-radius:50%;background:#9ca3af;display:inline-block;"></span>Low: <span class="fw-semibold"><?= $stats['byPriority']['low'] ?></span></li>
                </ul>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header">Upcoming (by due date)</div>
            <ul class="list-group list-group-flush">
                <?php if (empty($upcoming)): ?>
                    <li class="list-group-item text-center text-muted py-3 small">Nothing due.</li>
                <?php endif; ?>
                <?php foreach ($upcoming as $wo): ?>
                    <li class="list-group-item d-flex justify-content-between small">
                        <span><?= esc($wo->title) ?></span>
                        <span class="text-muted"><?= esc(date('d M', strtotime($wo->due_date))) ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>

        <div class="card">
            <div class="card-header">Quick Actions</div>
            <div class="card-body">
                <a href="<?= site_url('maintenance/new') ?>" class="btn btn-outline-primary btn-sm w-100"><i class="bi bi-plus-lg me-1"></i>Create Work Order</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('priorityChart'), {
    type: 'doughnut',
    data: {
        labels: ['High', 'Medium', 'Low'],
        datasets: [{
            data: [<?= (int) $stats['byPriority']['high'] ?>, <?= (int) $stats['byPriority']['medium'] ?>, <?= (int) $stats['byPriority']['low'] ?>],
            backgroundColor: ['#ef4444', '#f59e0b', '#9ca3af'],
            borderWidth: 0,
        }],
    },
    options: { cutout: '70%', plugins: { legend: { display: false } } },
});
</script>
<?= $this->endSection() ?>
