<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="fw-bold mb-0"><i class="fas fa-clipboard-check me-2 text-primary"></i>Work Orders</h5>
    <div class="d-flex gap-2">
        <a class="btn btn-sm btn-outline-success" href="<?= url('/WorkOrders/export') . '?' . http_build_query(array_filter(['q' => $filters['q'] ?? null, 'wo_type' => $filters['wo_type'] ?? null, 'priority' => $filters['priority'] ?? null, 'status' => $filters['status'] ?? null, 'assigned_to' => $filters['assigned_to'] ?? null])) ?>"><i class="fas fa-file-excel me-1"></i>Export</a>
        <a class="btn btn-sm btn-primary" href="<?= url('/WorkOrders/create') ?>"><i class="fas fa-plus me-1"></i>New Work Order</a>
    </div>
</div>

<?php if (!empty($flash)): ?><div class="alert alert-info py-2 small"><?= e($flash) ?></div><?php endif; ?>

<form method="get" action="<?= url('/WorkOrders') ?>" class="rs-card p-2 mb-3">
    <div class="row g-2 align-items-end">
        <div class="col-md-3"><input type="search" name="q" class="form-control form-control-sm" placeholder="Search title / code…" value="<?= e($filters['q'] ?? '') ?>"></div>
        <div class="col-md-2"><select name="wo_type" class="form-select form-select-sm"><option value="">All types</option><?php foreach (['preventive','corrective','adhoc','inspection'] as $t): ?><option value="<?= $t ?>" <?= ($filters['wo_type'] ?? '') === $t ? 'selected' : '' ?>><?= $t ?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><select name="priority" class="form-select form-select-sm"><option value="">Any priority</option><?php foreach (['low','medium','high','urgent'] as $p): ?><option value="<?= $p ?>" <?= ($filters['priority'] ?? '') === $p ? 'selected' : '' ?>><?= $p ?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><select name="status" class="form-select form-select-sm"><option value="">Any status</option><?php foreach (['draft','assigned','in_progress','on_hold','completed','cancelled'] as $s): ?><option value="<?= $s ?>" <?= ($filters['status'] ?? '') === $s ? 'selected' : '' ?>><?= $s ?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><select name="assigned_to" class="form-select form-select-sm"><option value="">Anyone</option><?php foreach ($users as $u): ?><option value="<?= (int) $u['user_id'] ?>" <?= (int) ($filters['assigned_to'] ?? 0) === (int) $u['user_id'] ? 'selected' : '' ?>><?= e($u['username']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-1"><button type="submit" class="btn btn-sm btn-outline-primary w-100"><i class="fas fa-filter"></i></button></div>
    </div>
    <div class="row g-2 align-items-end mt-2">
        <div class="col-md-2"><select name="sort" class="form-select form-select-sm" onchange="this.form.submit()"><option value="newest" <?= ($sort ?? 'newest') === 'newest' ? 'selected' : '' ?>>Newest first</option><option value="oldest" <?= ($sort ?? '') === 'oldest' ? 'selected' : '' ?>>Oldest first</option><option value="due_asc" <?= ($sort ?? '') === 'due_asc' ? 'selected' : '' ?>>Due date ↑</option><option value="priority" <?= ($sort ?? '') === 'priority' ? 'selected' : '' ?>>Priority</option><option value="status_group" <?= ($sort ?? '') === 'status_group' ? 'selected' : '' ?>>Status group</option></select></div>
    </div>
</form>

<div class="rs-card p-3">
<?php if (empty($orders)): ?>
    <p class="text-muted small mb-0">No work orders found.</p>
<?php else: ?>
    <table class="table table-sm table-hover mb-2">
        <thead><tr><th>Code</th><th>Title</th><th>Type</th><th>Priority</th><th>Status</th><th>Asset</th><th>Assigned</th><th>Due</th><th class="text-end">Tasks</th></tr></thead>
        <tbody>
            <?php foreach ($orders as $w): ?>
                <tr>
                    <td class="small"><?= e($w['code'] ?? '#' . $w['work_order_id']) ?></td>
                    <td><a href="<?= url('/WorkOrders/show/' . (int) $w['work_order_id']) ?>" class="fw-semibold text-decoration-none"><?= e($w['title']) ?></a></td>
                    <td class="small"><span class="badge bg-secondary text-uppercase"><?= e($w['wo_type']) ?></span></td>
                    <td><span class="badge bg-secondary text-uppercase"><?= e($w['priority']) ?></span></td>
                    <td><span class="badge bg-secondary text-uppercase"><?= e($w['status']) ?></span></td>
                    <td class="small text-muted"><?= e($w['asset_name'] ?? '—') ?></td>
                    <td class="small text-muted"><?= e($w['assigned_username'] ?? '—') ?></td>
                    <td class="small text-muted"><?= e($w['due_at'] ?? '—') ?></td>
                    <td class="text-end"><?= (int) $w['task_done'] ?>/<?= (int) $w['task_total'] ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php
    // Preserve every active filter across page links so pagination doesn't
    // reset the caller's view.
    $qs = array_filter([
        'q'           => $filters['q']           ?? null,
        'wo_type'     => $filters['wo_type']     ?? null,
        'priority'    => $filters['priority']    ?? null,
        'status'      => $filters['status']      ?? null,
        'assigned_to' => $filters['assigned_to'] ?? null,
        'per_page'    => $pager['per_page'] !== 25 ? $pager['per_page'] : null,
        'sort'        => ($sort ?? 'newest') !== 'newest' ? $sort : null,
    ]);
    $pageUrl = function (int $n) use ($qs) {
        $qs['page'] = $n;
        return url('/WorkOrders') . '?' . http_build_query($qs);
    };

    // Windowed page numbers: current ± 2, plus first & last with "…" ellipses.
    $window = [];
    $window[] = 1;
    for ($i = max(2, $pager['page'] - 2); $i <= min($pager['last'] - 1, $pager['page'] + 2); $i++) $window[] = $i;
    if ($pager['last'] > 1) $window[] = $pager['last'];
    $window = array_values(array_unique($window));
    ?>
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 pt-1">
        <div class="small text-muted">
            Showing <strong><?= (int) $pager['from'] ?></strong>–<strong><?= (int) $pager['to'] ?></strong> of
            <strong><?= (int) $pager['total'] ?></strong>
        </div>

        <nav aria-label="Work orders pagination">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?= $pager['page'] <= 1 ? 'disabled' : '' ?>">
                    <a class="page-link" href="<?= $pager['page'] > 1 ? e($pageUrl($pager['page'] - 1)) : '#' ?>">‹</a>
                </li>
                <?php $prev = null; foreach ($window as $n):
                    if ($prev !== null && $n > $prev + 1): ?>
                        <li class="page-item disabled"><span class="page-link">…</span></li>
                    <?php endif; ?>
                    <li class="page-item <?= $n === $pager['page'] ? 'active' : '' ?>">
                        <a class="page-link" href="<?= e($pageUrl($n)) ?>"><?= $n ?></a>
                    </li>
                    <?php $prev = $n; endforeach; ?>
                <li class="page-item <?= $pager['page'] >= $pager['last'] ? 'disabled' : '' ?>">
                    <a class="page-link" href="<?= $pager['page'] < $pager['last'] ? e($pageUrl($pager['page'] + 1)) : '#' ?>">›</a>
                </li>
            </ul>
        </nav>

        <form method="get" action="<?= url('/WorkOrders') ?>" class="d-flex align-items-center gap-2 small">
            <?php foreach ($qs as $k => $v): if ($k === 'per_page' || $k === 'page') continue; ?>
                <input type="hidden" name="<?= e($k) ?>" value="<?= e((string) $v) ?>">
            <?php endforeach; ?>
            <label class="text-muted mb-0">Per page</label>
            <select name="per_page" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                <?php foreach ([10, 25, 50, 100] as $pp): ?>
                    <option value="<?= $pp ?>" <?= $pager['per_page'] === $pp ? 'selected' : '' ?>><?= $pp ?></option>
                <?php endforeach; ?>
            </select>
        </form>
    </div>
<?php endif; ?>
</div>
