<!-- Filtres -->
<div class="card shadow-sm mb-4">
    <div class="card-body py-2">
        <?= form_open('requests', ['method' => 'get', 'class' => 'row g-2 align-items-end']); ?>
            <div class="col-md-2">
                <label class="form-label small mb-1">Statut</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">Tous</option>
                    <option value="pending"  <?= ($filters['status'] ?? '') == 'pending'  ? 'selected' : ''; ?>>En attente</option>
                    <option value="approved" <?= ($filters['status'] ?? '') == 'approved' ? 'selected' : ''; ?>>Approuvée</option>
                    <option value="rejected" <?= ($filters['status'] ?? '') == 'rejected' ? 'selected' : ''; ?>>Rejetée</option>
                    <option value="paid"     <?= ($filters['status'] ?? '') == 'paid'     ? 'selected' : ''; ?>>Payée</option>
                    <option value="closed"   <?= ($filters['status'] ?? '') == 'closed'   ? 'selected' : ''; ?>>Clôturée</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small mb-1">Localisation</label>
                <select name="location_id" class="form-select form-select-sm">
                    <option value="">Toutes</option>
                    <?php foreach ($locations as $loc): ?>
                    <option value="<?= $loc->id; ?>" <?= ($filters['location_id'] ?? '') == $loc->id ? 'selected' : ''; ?>>
                        <?= $loc->name; ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4 d-flex gap-2 align-items-end">
                <button class="btn btn-sm btn-primary"><i class="bi bi-search"></i> Filtrer</button>
                <a href="<?= site_url('requests'); ?>" class="btn btn-sm btn-outline-secondary">Reset</a>
                <?php if ($this->auth_lib->has_permission('request_create')): ?>
                <a href="<?= site_url('requests/create'); ?>" class="btn btn-sm btn-success ms-auto">
                    <i class="bi bi-plus-lg"></i> Nouvelle demande
                </a>
                <?php endif; ?>
            </div>
        <?= form_close(); ?>
    </div>
</div>

<!-- Filtres rapides de suivi -->
<?php if ($this->auth_lib->is_manager_or_admin()): ?>
<div class="d-flex gap-2 mb-3">
    <a href="<?= site_url('requests?missing_expense=1'); ?>" 
       class="btn btn-sm <?= !empty($filters['missing_expense']) ? 'btn-warning' : 'btn-outline-warning'; ?>">
        <i class="bi bi-exclamation-triangle"></i> Approuvées sans dépense
    </a>
    <a href="<?= site_url('requests?missing_invoice=1'); ?>" 
       class="btn btn-sm <?= !empty($filters['missing_invoice']) ? 'btn-danger' : 'btn-outline-danger'; ?>">
        <i class="bi bi-paperclip"></i> Sans justificatif
    </a>
</div>
<?php endif; ?>

<!-- Tableau -->
<div class="card shadow-sm">
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th>Référence</th>
                    <th>Date</th>
                    <th>Catégorie</th>
                    <th>Description</th>
                    <th>Lieu</th>
                    <th class="text-end">Montant estimé</th>
                    <th>Statut</th>
                    <th>Dépense</th>
                    <th>Facture</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($requests)): ?>
                <tr><td colspan="10" class="text-center text-muted py-4">Aucune demande trouvée.</td></tr>
                <?php else: ?>
                <?php foreach ($requests as $r): ?>
                <?php
                    $status_map = [
                        'pending'  => ['warning',   'text-dark', 'hourglass-split', 'En attente'],
                        'approved' => ['success',   '',          'check-circle',    'Approuvée'],
                        'rejected' => ['danger',    '',          'x-circle',        'Rejetée'],
                        'paid'     => ['info',      '',          'credit-card',     'Payée'],
                        'closed'   => ['secondary', '',          'lock',            'Clôturée'],
                    ];
                    $s = $status_map[$r->status] ?? ['secondary', '', 'circle', $r->status];
                ?>
                <tr>
                    <td>
                        <a href="<?= site_url('requests/view/' . $r->id); ?>" class="text-decoration-none">
                            <code><?= $r->reference; ?></code>
                        </a>
                    </td>
                    <td class="small"><?= date('d/m/Y', strtotime($r->request_date)); ?></td>
                    <td><span class="badge bg-light text-dark"><?= $r->category_label; ?></span></td>
                    <td class="small"><?= character_limiter(htmlspecialchars($r->description), 30); ?></td>
                    <td><span class="badge bg-light text-dark"><i class="bi bi-geo-alt"></i> <?= $r->location_name; ?></span></td>
                    <td class="text-end fw-semibold"><?= number_format($r->estimated_amount, 0, ',', ' '); ?></td>
                    <td>
                        <span class="badge bg-<?= $s[0]; ?> <?= $s[1]; ?>">
                            <i class="bi bi-<?= $s[2]; ?>"></i> <?= $s[3]; ?>
                        </span>
                    </td>
                    <!-- Colonne Dépense -->
                    <td>
                        <?php if ($r->expense_ref): ?>
                            <a href="<?= site_url('expenses/view/' . $r->expense_pk); ?>" class="text-decoration-none">
                                <code class="small"><?= $r->expense_ref; ?></code>
                            </a>
                            <?php
                                $exp_status_colors = ['pending' => 'warning', 'validated' => 'success', 'batched' => 'info', 'rejected' => 'danger'];
                                $exp_color = $exp_status_colors[$r->expense_status] ?? 'secondary';
                            ?>
                            <span class="badge bg-<?= $exp_color; ?> bg-opacity-10 text-<?= $exp_color; ?> ms-1" style="font-size:.65rem">
                                <?= $r->expense_status; ?>
                            </span>
                        <?php elseif ($r->status === 'approved'): ?>
                            <span class="text-warning" title="Aucune dépense créée">
                                <i class="bi bi-exclamation-triangle"></i> Manquante
                            </span>
                        <?php else: ?>
                            <span class="text-muted">—</span>
                        <?php endif; ?>
                    </td>
                    <!-- Colonne Facture -->
                    <td>
                        <?php if ($r->expense_ref): ?>
                            <?php if ( ! empty($r->expense_invoice_path)): ?>
                                <a href="<?= base_url($r->expense_invoice_path); ?>" target="_blank" 
                                   class="text-success" title="Justificatif joint">
                                    <i class="bi bi-check-circle-fill"></i>
                                </a>
                            <?php else: ?>
                                <span class="text-danger" title="Justificatif manquant">
                                    <i class="bi bi-x-circle-fill"></i>
                                </span>
                            <?php endif; ?>
                        <?php else: ?>
                            <span class="text-muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="text-end">
                        <a href="<?= site_url('requests/view/' . $r->id); ?>" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-eye"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($total > $limit): ?>
    <div class="card-footer bg-white d-flex justify-content-between align-items-center">
        <small class="text-muted"><?= $total; ?> demande(s)</small>
        <nav>
            <ul class="pagination pagination-sm mb-0">
                <?php for ($i = 1; $i <= ceil($total / $limit); $i++): ?>
                <li class="page-item <?= $i == $page ? 'active' : ''; ?>">
                    <a class="page-link" href="<?= site_url('requests?' . http_build_query(array_merge($filters, ['page' => $i]))); ?>"><?= $i; ?></a>
                </li>
                <?php endfor; ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>
