<?php
$pageTitle = 'Services (Billets, Visas...)';
require_once __DIR__ . '/includes/header.php';
$db = getDB();

$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

// Types de services
$typesService = [
    'billet' => 'Billet d\'avion',
    'visa' => 'Visa',
    'assurance' => 'Assurance voyage',
    'transfert' => 'Transfert / Transport',
    'hotel' => 'Réservation d\'hôtel',
    'autre' => 'Autre service'
];

// --- Suppression d'un service ---
if ($action === 'delete' && $id) {
    $svc = $db->prepare("SELECT * FROM services WHERE id=?");
    $svc->execute([$id]);
    $service = $svc->fetch();
    if (!$service) { flash('error', 'Service introuvable.'); redirect('/services.php'); }
    
    // Check if there are payments
    $hasPaiements = $db->prepare("SELECT COUNT(*) FROM paiements WHERE service_id=?");
    $hasPaiements->execute([$id]);
    if ($hasPaiements->fetchColumn() > 0) {
        flash('error', 'Impossible de supprimer ce service car il contient des paiements. Supprimez d\'abord les paiements associés.');
        redirect('/services.php');
    }
    
    $db->prepare("DELETE FROM services WHERE id=?")->execute([$id]);
    logAction($_SESSION['user_id'], 'service_delete', "Service supprimé: {$service['titre']} (ID: $id)");
    flash('success', 'Service supprimé avec succès.');
    redirect('/services.php');
}

// --- Sauvegarde d'un service (Ajout/Modification) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($action === 'add' || $action === 'edit')) {
    $editId = intval($_POST['id'] ?? 0);
    $voyageurId = intval($_POST['voyageur_id'] ?? 0);
    $typeService = $_POST['type_service'] ?? 'autre';
    $titre = sanitize($_POST['titre'] ?? '');
    $description = sanitize($_POST['description'] ?? '');
    $prixTotal = floatval($_POST['prix_total'] ?? 0);
    $statutService = $_POST['statut_service'] ?? 'en_cours';
    $dateService = $_POST['date_service'] ?? '';
    $fournisseur = sanitize($_POST['fournisseur'] ?? '');
    $referenceFournisseur = sanitize($_POST['reference_fournisseur'] ?? '');
    $notes = sanitize($_POST['notes'] ?? '');

    if (!$voyageurId || empty($titre)) {
        flash('error', 'Veuillez remplir les champs obligatoires (Bénéficiaire et Titre).');
        redirect($editId ? "/services.php?action=edit&id=$editId" : '/services.php?action=add');
    }

    if ($editId) {
        // Update
        $db->prepare("UPDATE services SET voyageur_id=?, type_service=?, titre=?, description=?, prix_total=?, statut_service=?, date_service=?, fournisseur=?, reference_fournisseur=?, notes=?, updated_at=datetime('now') WHERE id=?")
           ->execute([$voyageurId, $typeService, $titre, $description, $prixTotal, $statutService, $dateService, $fournisseur, $referenceFournisseur, $notes, $editId]);
           
        // Re-calculer le statut de paiement
        $totalPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE service_id=?");
        $totalPaye->execute([$editId]);
        $tp = $totalPaye->fetchColumn();
        $statutPaiement = $tp >= $prixTotal ? 'paye' : ($tp > 0 ? 'partiel' : 'impaye');
        $db->prepare("UPDATE services SET statut_paiement=? WHERE id=?")->execute([$statutPaiement, $editId]);
        
        logAction($_SESSION['user_id'], 'service_update', "Service mis à jour: $titre (ID: $editId)");
        flash('success', 'Service modifié avec succès.');
        redirect('/services.php?action=view&id='.$editId);
    } else {
        // Insert
        $db->prepare("INSERT INTO services (voyageur_id, type_service, titre, description, prix_total, statut_service, date_service, fournisseur, reference_fournisseur, notes, created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?)")
           ->execute([$voyageurId, $typeService, $titre, $description, $prixTotal, $statutService, $dateService, $fournisseur, $referenceFournisseur, $notes, $_SESSION['user_id']]);
        
        $newId = $db->lastInsertId();
        logAction($_SESSION['user_id'], 'service_create', "Service créé: $titre (ID: $newId)");
        flash('success', 'Nouveau service enregistré avec succès.');
        redirect('/services.php?action=view&id='.$newId);
    }
}

// --- Formulaire Ajout / Modification ---
if ($action === 'add' || $action === 'edit') {
    $service = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM services WHERE id=?");
        $stmt->execute([$id]);
        $service = $stmt->fetch();
        if (!$service) { flash('error', 'Service introuvable.'); redirect('/services.php'); }
    }
    
    $voyageurs = $db->query("SELECT id, nom, prenom, reference, cin, telephone FROM voyageurs ORDER BY nom")->fetchAll();
    $preselectedVoyageur = intval($_GET['voyageur_id'] ?? ($service['voyageur_id'] ?? 0));
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/services.php<?= $service ? '?action=view&id='.$service['id'] : '' ?>" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour</a>
    </div>
    
    <div class="card table-card">
        <div class="card-header"><i class="bi bi-briefcase me-2"></i><?= $service ? 'Modifier le service' : 'Nouveau service' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $service['id'] ?? '' ?>">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Bénéficiaire (Voyageur / Client) *</label>
                        <select name="voyageur_id" class="form-select select2" required>
                            <option value="">-- Sélectionner un client --</option>
                            <?php foreach ($voyageurs as $v): ?>
                                <option value="<?= $v['id'] ?>" <?= $preselectedVoyageur==$v['id']?'selected':'' ?>>
                                    <?= sanitize($v['nom'].' '.$v['prenom'].' (CIN: '.($v['cin']?:'-').' | Tél: '.($v['telephone']?:'-').')') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Type de service *</label>
                        <select name="type_service" class="form-select" required>
                            <?php foreach ($typesService as $k => $v): ?>
                                <option value="<?= $k ?>" <?= ($service['type_service']??'billet')==$k?'selected':'' ?>><?= $v ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Statut *</label>
                        <select name="statut_service" class="form-select" required>
                            <option value="en_cours" <?= ($service['statut_service']??'')=='en_cours'?'selected':'' ?>>En cours</option>
                            <option value="termine" <?= ($service['statut_service']??'')=='termine'?'selected':'' ?>>Terminé / Délivré</option>
                            <option value="annule" <?= ($service['statut_service']??'')=='annule'?'selected':'' ?>>Annulé</option>
                        </select>
                    </div>
                    
                    <div class="col-md-8">
                        <label class="form-label">Titre du service (ex: Billet Casa-Paris RAM) *</label>
                        <input type="text" name="titre" class="form-control" value="<?= sanitize($service['titre'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Prix Total (MAD) *</label>
                        <input type="number" step="0.01" name="prix_total" class="form-control" value="<?= $service['prix_total'] ?? '0' ?>" required>
                    </div>
                    
                    <div class="col-md-4">
                        <label class="form-label">Date du service / Date d'expiration</label>
                        <input type="date" name="date_service" class="form-control" value="<?= $service['date_service'] ?? '' ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Fournisseur / Agence (ex: Royal Air Maroc)</label>
                        <input type="text" name="fournisseur" class="form-control" value="<?= sanitize($service['fournisseur'] ?? '') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Référence fournisseur (ex: PNR)</label>
                        <input type="text" name="reference_fournisseur" class="form-control" value="<?= sanitize($service['reference_fournisseur'] ?? '') ?>">
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">Description détaillée</label>
                        <textarea name="description" class="form-control" rows="3"><?= sanitize($service['description'] ?? '') ?></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Notes internes</label>
                        <textarea name="notes" class="form-control" rows="3"><?= sanitize($service['notes'] ?? '') ?></textarea>
                    </div>
                </div>
                
                <div class="d-flex gap-2 mt-4">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Enregistrer</button>
                    <a href="<?= APP_URL ?>/services.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// --- Vue Détails ---
if ($action === 'view' && $id) {
    $stmt = $db->prepare("SELECT s.*, v.nom, v.prenom, v.cin, v.telephone, v.email, u.full_name as createur 
                          FROM services s 
                          JOIN voyageurs v ON s.voyageur_id=v.id 
                          LEFT JOIN users u ON s.created_by=u.id 
                          WHERE s.id=?");
    $stmt->execute([$id]);
    $service = $stmt->fetch();
    
    if (!$service) { flash('error', 'Service introuvable.'); redirect('/services.php'); }
    
    // Récupérer les paiements de ce service
    $stmtPaiements = $db->prepare("SELECT * FROM paiements WHERE service_id=? ORDER BY date_paiement DESC");
    $stmtPaiements->execute([$id]);
    $paiements = $stmtPaiements->fetchAll();
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/services.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour à la liste</a>
        <div class="d-flex gap-2">
            <a href="<?= APP_URL ?>/services.php?action=edit&id=<?= $id ?>" class="btn btn-warning"><i class="bi bi-pencil me-1"></i>Modifier</a>
            <a href="<?= APP_URL ?>/paiements.php?action=add&service_id=<?= $id ?>" class="btn btn-success"><i class="bi bi-cash me-1"></i>Ajouter paiement</a>
        </div>
    </div>

    <div class="row g-4">
        <!-- Infos du service -->
        <div class="col-md-8">
            <div class="card table-card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-info-circle me-2"></i>Détails du service</span>
                    <?= getStatusBadge($service['statut_service']) ?>
                </div>
                <div class="card-body">
                    <h4 class="mb-1"><?= sanitize($service['titre']) ?></h4>
                    <span class="badge bg-secondary mb-4"><?= $typesService[$service['type_service']] ?? 'Autre' ?></span>
                    
                    <div class="row g-4">
                        <div class="col-md-4">
                            <small class="text-muted d-block">Bénéficiaire</small>
                            <strong><a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $service['voyageur_id'] ?>"><?= sanitize($service['nom'].' '.$service['prenom']) ?></a></strong>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted d-block">Contact</small>
                            <strong><?= sanitize($service['telephone'] ?: '-') ?></strong>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted d-block">CIN</small>
                            <strong><?= sanitize($service['cin'] ?: '-') ?></strong>
                        </div>
                        
                        <div class="col-md-4">
                            <small class="text-muted d-block">Fournisseur</small>
                            <strong><?= sanitize($service['fournisseur'] ?: '-') ?></strong>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted d-block">Référence (PNR...)</small>
                            <strong><?= sanitize($service['reference_fournisseur'] ?: '-') ?></strong>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted d-block">Date prévue / limite</small>
                            <strong><?= formatDate($service['date_service']) ?: '-' ?></strong>
                        </div>
                        
                        <?php if ($service['description']): ?>
                        <div class="col-12">
                            <small class="text-muted d-block">Description</small>
                            <p class="mb-0 bg-light p-2 rounded"><?= nl2br(sanitize($service['description'])) ?></p>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($service['notes']): ?>
                        <div class="col-12">
                            <small class="text-muted d-block">Notes internes</small>
                            <p class="mb-0 bg-light p-2 rounded border-start border-warning border-4"><?= nl2br(sanitize($service['notes'])) ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="card-footer text-muted small">
                    Créé par <?= sanitize($service['createur']) ?> le <?= formatDateTime($service['created_at']) ?>
                </div>
            </div>
            
            <!-- Historique des paiements -->
            <div class="card table-card">
                <div class="card-header"><i class="bi bi-cash-stack me-2"></i>Paiements liés</div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead><tr><th>Date</th><th>Montant</th><th>Mode</th><th>Référence</th><th>Actions</th></tr></thead>
                        <tbody>
                        <?php foreach ($paiements as $p): ?>
                            <tr>
                                <td><?= formatDate($p['date_paiement']) ?></td>
                                <td class="fw-bold text-success"><?= formatMoney($p['montant']) ?></td>
                                <td><?= ucfirst($p['mode_paiement']) ?></td>
                                <td><?= sanitize($p['reference_paiement'] ?: '-') ?></td>
                                <td>
                                    <a href="<?= APP_URL ?>/paiements.php?action=recu&id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-primary" target="_blank" title="Imprimer le reçu"><i class="bi bi-printer"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($paiements)): ?><tr><td colspan="5" class="text-center py-3 text-muted">Aucun paiement effectué.</td></tr><?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Panneau financier -->
        <div class="col-md-4">
            <div class="card table-card sticky-top" style="top: 80px;">
                <div class="card-header bg-light"><i class="bi bi-wallet2 me-2"></i>Situation financière</div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-3 border-bottom pb-2">
                        <span class="text-muted">Statut</span>
                        <span><?= getStatusBadge($service['statut_paiement']) ?></span>
                    </div>
                    
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Prix total</span>
                        <span class="fw-bold fs-5"><?= formatMoney($service['prix_total']) ?></span>
                    </div>
                    
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Montant payé</span>
                        <span class="text-success fw-bold"><?= formatMoney($service['montant_paye']) ?></span>
                    </div>
                    
                    <?php $reste = $service['prix_total'] - $service['montant_paye']; ?>
                    <div class="d-flex justify-content-between mt-3 pt-3 border-top">
                        <span class="fw-bold <?= $reste > 0 ? 'text-danger' : 'text-success' ?>">Reste à payer</span>
                        <span class="fw-bold fs-5 <?= $reste > 0 ? 'text-danger' : 'text-success' ?>"><?= formatMoney($reste) ?></span>
                    </div>
                    
                    <?php if ($reste > 0): ?>
                    <a href="<?= APP_URL ?>/paiements.php?action=add&service_id=<?= $id ?>" class="btn btn-success w-100 mt-4">
                        <i class="bi bi-plus-circle me-1"></i>Encaisser <?= formatMoney($reste) ?>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// --- Liste des services ---
$search = $_GET['search'] ?? '';
$typeFilter = $_GET['type'] ?? '';
$statutFilter = $_GET['statut'] ?? '';
$paiementFilter = $_GET['paiement'] ?? '';

$where = "WHERE 1=1";
$params = [];

if ($search) {
    $where .= " AND (s.titre LIKE ? OR s.fournisseur LIKE ? OR s.reference_fournisseur LIKE ? OR v.nom LIKE ? OR v.prenom LIKE ? OR v.cin LIKE ?)";
    $s = "%$search%";
    $params = array_merge($params, [$s,$s,$s,$s,$s,$s]);
}
if ($typeFilter) { $where .= " AND s.type_service = ?"; $params[] = $typeFilter; }
if ($statutFilter) { $where .= " AND s.statut_service = ?"; $params[] = $statutFilter; }
if ($paiementFilter) { $where .= " AND s.statut_paiement = ?"; $params[] = $paiementFilter; }

$page = max(1, intval($_GET['page'] ?? 1));
$total = $db->prepare("SELECT COUNT(*) FROM services s JOIN voyageurs v ON s.voyageur_id = v.id $where");
$total->execute($params);
$totalCount = $total->fetchColumn();
$pagination = paginate($totalCount, 15, $page);

$stmt = $db->prepare("SELECT s.*, v.nom, v.prenom, v.cin 
                      FROM services s 
                      JOIN voyageurs v ON s.voyageur_id = v.id 
                      $where 
                      ORDER BY s.created_at DESC 
                      LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$services = $stmt->fetchAll();

// Totaux pour statistiques
$totalQuery = $db->prepare("SELECT SUM(prix_total) as total_du, SUM(montant_paye) as total_paye FROM services s JOIN voyageurs v ON s.voyageur_id = v.id $where");
$totalQuery->execute($params);
$totals = $totalQuery->fetch();
?>

<!-- En-tête statistiques -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="stat-icon bg-primary bg-opacity-10 text-primary"><i class="bi bi-briefcase"></i></div>
                <div><small class="text-muted d-block">Total Services</small><h4 class="mb-0 fw-bold"><?= $totalCount ?></h4></div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="stat-icon bg-success bg-opacity-10 text-success"><i class="bi bi-cash-stack"></i></div>
                <div><small class="text-muted d-block">Total Encaissé</small><h5 class="mb-0 fw-bold text-success"><?= formatMoney($totals['total_paye'] ?? 0) ?></h5></div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="stat-icon bg-danger bg-opacity-10 text-danger"><i class="bi bi-graph-down-arrow"></i></div>
                <div><small class="text-muted d-block">Reste à recouvrer</small><h5 class="mb-0 fw-bold text-danger"><?= formatMoney(($totals['total_du'] ?? 0) - ($totals['total_paye'] ?? 0)) ?></h5></div>
            </div>
        </div>
    </div>
    <div class="col-md-3 d-flex align-items-center">
        <a href="<?= APP_URL ?>/services.php?action=add" class="btn btn-primary btn-lg w-100 h-100 d-flex align-items-center justify-content-center gap-2" style="border-radius:16px;">
            <i class="bi bi-plus-lg"></i> Nouveau Service
        </a>
    </div>
</div>

<!-- Filtres -->
<div class="card table-card mb-4">
    <div class="card-body py-3">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label small text-muted mb-1">Recherche</label>
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-light"><i class="bi bi-search"></i></span>
                    <input type="text" name="search" class="form-control" placeholder="Titre, client, réf..." value="<?= sanitize($search) ?>">
                </div>
            </div>
            <div class="col-md-2">
                <label class="form-label small text-muted mb-1">Type</label>
                <select name="type" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">Tous les types</option>
                    <?php foreach ($typesService as $k => $v): ?>
                        <option value="<?= $k ?>" <?= $typeFilter==$k?'selected':'' ?>><?= $v ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small text-muted mb-1">Statut du service</label>
                <select name="statut" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">Tous les statuts</option>
                    <option value="en_cours" <?= $statutFilter=='en_cours'?'selected':'' ?>>En cours</option>
                    <option value="termine" <?= $statutFilter=='termine'?'selected':'' ?>>Terminé</option>
                    <option value="annule" <?= $statutFilter=='annule'?'selected':'' ?>>Annulé</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small text-muted mb-1">Paiement</label>
                <select name="paiement" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">Tous les paiements</option>
                    <option value="paye" <?= $paiementFilter=='paye'?'selected':'' ?>>Payé</option>
                    <option value="partiel" <?= $paiementFilter=='partiel'?'selected':'' ?>>Partiel</option>
                    <option value="impaye" <?= $paiementFilter=='impaye'?'selected':'' ?>>Impayé</option>
                </select>
            </div>
            <div class="col-md-12 text-end mt-2">
                <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-funnel"></i> Filtrer</button>
                <a href="<?= APP_URL ?>/services.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-x"></i></a>
            </div>
        </form>
    </div>
</div>

<!-- Tableau des services -->
<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead>
                <tr>
                    <th>Date Création</th>
                    <th>Type</th>
                    <th>Service</th>
                    <th>Bénéficiaire</th>
                    <th>Prix Total</th>
                    <th>Statut Paiement</th>
                    <th>Statut Service</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($services as $s): ?>
                <tr>
                    <td class="text-muted small"><?= formatDate($s['created_at']) ?></td>
                    <td><span class="badge bg-secondary"><?= $typesService[$s['type_service']] ?? 'Autre' ?></span></td>
                    <td>
                        <strong><?= sanitize($s['titre']) ?></strong><br>
                        <small class="text-muted"><?= sanitize($s['fournisseur']) ?> <?= $s['reference_fournisseur'] ? '(Réf: '.$s['reference_fournisseur'].')' : '' ?></small>
                    </td>
                    <td>
                        <a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $s['voyageur_id'] ?>" class="text-decoration-none fw-bold">
                            <?= sanitize($s['nom'].' '.$s['prenom']) ?>
                        </a>
                    </td>
                    <td class="fw-bold"><?= formatMoney($s['prix_total']) ?></td>
                    <td>
                        <?= getStatusBadge($s['statut_paiement']) ?><br>
                        <small class="text-muted"><?= formatMoney($s['montant_paye']) ?> payé</small>
                    </td>
                    <td><?= getStatusBadge($s['statut_service']) ?></td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/services.php?action=view&id=<?= $s['id'] ?>" class="btn btn-outline-primary" title="Détails"><i class="bi bi-eye"></i></a>
                            <a href="<?= APP_URL ?>/services.php?action=edit&id=<?= $s['id'] ?>" class="btn btn-outline-warning" title="Modifier"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/services.php?action=delete&id=<?= $s['id'] ?>" class="btn btn-outline-danger" title="Supprimer" onclick="return confirmDelete()"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if (empty($services)): ?>
                <tr><td colspan="8" class="text-center py-5 text-muted"><i class="bi bi-inbox fs-1 d-block mb-2"></i>Aucun service trouvé</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($pagination['total_pages'] > 1): ?>
    <div class="card-footer border-0 bg-white pt-3 pb-2">
        <?= renderPagination($pagination, APP_URL.'/services.php?search='.urlencode($search).'&type='.urlencode($typeFilter).'&statut='.urlencode($statutFilter).'&paiement='.urlencode($paiementFilter)) ?>
    </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
