<?php
$pageTitle = 'Paiements';
require_once __DIR__ . '/includes/header.php';
$db = getDB();

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

// Delete payment
if ($action === 'delete' && $id) {
    $paiement = $db->prepare("SELECT * FROM paiements WHERE id=?");
    $paiement->execute([$id]);
    $paiement = $paiement->fetch();
    if (!$paiement) { flash('error', 'Paiement introuvable.'); redirect('/paiements.php'); }
    
    $inscriptionId = $paiement['inscription_id'];
    
    // Delete payment
    $db->prepare("DELETE FROM paiements WHERE id=?")->execute([$id]);
    
    // Recalculate inscription payment status
    $ins = $db->prepare("SELECT * FROM inscriptions WHERE id=?");
    $ins->execute([$inscriptionId]);
    $ins = $ins->fetch();
    
    if ($ins) {
        $totalPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE inscription_id=?");
        $totalPaye->execute([$inscriptionId]);
        $tp = $totalPaye->fetchColumn();
        $statutPaiement = $tp >= $ins['prix_total'] ? 'paye' : ($tp > 0 ? 'partiel' : 'impaye');
        $db->prepare("UPDATE inscriptions SET montant_paye=?, statut_paiement=? WHERE id=?")->execute([$tp, $statutPaiement, $inscriptionId]);
    }
    
    logAction($_SESSION['user_id'], 'paiement_delete', "Suppression paiement #{$id}");
    flash('success', 'Paiement supprimé.');
    redirect('/paiements.php');
}

// Save payment
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $editId = intval($_POST['id'] ?? 0);
    $typePaiement = $_POST['type_paiement'] ?? 'inscription'; // 'inscription' or 'service'
    $inscriptionId = intval($_POST['inscription_id'] ?? 0);
    $serviceId = intval($_POST['service_id'] ?? 0);
    $montant = floatval($_POST['montant'] ?? 0);
    $mode = $_POST['mode_paiement'] ?? 'especes';
    $reference = sanitize($_POST['reference_paiement'] ?? '');
    $date = $_POST['date_paiement'] ?? date('Y-m-d');
    $notes = sanitize($_POST['notes'] ?? '');

    if ($montant <= 0) {
        flash('error', 'Le montant doit être supérieur à 0.');
        redirect('/paiements.php');
    }

    if ($typePaiement === 'inscription') {
        if (!$inscriptionId) { flash('error', 'Veuillez sélectionner une inscription.'); redirect('/paiements.php'); }
        $ins = $db->prepare("SELECT * FROM inscriptions WHERE id=?");
        $ins->execute([$inscriptionId]);
        $ins = $ins->fetch();
        if (!$ins) { flash('error', 'Inscription introuvable.'); redirect('/paiements.php'); }
        $voyageurId = $ins['voyageur_id'];
        $serviceId = null;
    } else {
        if (!$serviceId) { flash('error', 'Veuillez sélectionner un service.'); redirect('/paiements.php'); }
        $svc = $db->prepare("SELECT * FROM services WHERE id=?");
        $svc->execute([$serviceId]);
        $svc = $svc->fetch();
        if (!$svc) { flash('error', 'Service introuvable.'); redirect('/paiements.php'); }
        $voyageurId = $svc['voyageur_id'];
        $inscriptionId = null;
    }

    try {
        if ($editId) {
            $db->prepare("UPDATE paiements SET inscription_id=?, service_id=?, voyageur_id=?, montant=?, mode_paiement=?, reference_paiement=?, date_paiement=?, notes=? WHERE id=?")
                ->execute([$inscriptionId, $serviceId, $voyageurId, $montant, $mode, $reference, $date, $notes, $editId]);
            logAction($_SESSION['user_id'], 'paiement_update', "Modification paiement #{$editId}");
            flash('success', 'Paiement modifié avec succès.');
        } else {
            $db->prepare("INSERT INTO paiements (inscription_id, service_id, voyageur_id, montant, mode_paiement, reference_paiement, date_paiement, notes, created_by) VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$inscriptionId, $serviceId, $voyageurId, $montant, $mode, $reference, $date, $notes, $_SESSION['user_id']]);
            logAction($_SESSION['user_id'], 'paiement_create', "Nouveau paiement de $montant MAD");
            flash('success', 'Paiement enregistré avec succès.');
        }

        // Update parent status (inscription or service)
        if ($inscriptionId) {
            $totalPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE inscription_id=?");
            $totalPaye->execute([$inscriptionId]);
            $tp = $totalPaye->fetchColumn();
            $statut = $tp >= $ins['prix_total'] ? 'paye' : ($tp > 0 ? 'partiel' : 'impaye');
            $db->prepare("UPDATE inscriptions SET montant_paye=?, statut_paiement=? WHERE id=?")->execute([$tp, $statut, $inscriptionId]);
        } elseif ($serviceId) {
            $totalPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE service_id=?");
            $totalPaye->execute([$serviceId]);
            $tp = $totalPaye->fetchColumn();
            $statut = $tp >= $svc['prix_total'] ? 'paye' : ($tp > 0 ? 'partiel' : 'impaye');
            $db->prepare("UPDATE services SET montant_paye=?, statut_paiement=? WHERE id=?")->execute([$tp, $statut, $serviceId]);
        }
    } catch (Exception $e) {
        flash('error', 'Erreur lors de l\'enregistrement: ' . $e->getMessage());
    }

    redirect('/paiements.php');
}

// Receipt
if ($action === 'recu' && $id) {
    $p = $db->prepare("SELECT pa.*, v.nom, v.prenom, v.cin, v.telephone, v.adresse, v.ville, 
                       i.num_dossier, i.formule, i.prix_total as ins_prix, i.montant_paye as ins_paye, 
                       pr.nom as programme_nom, pr.type as programme_type,
                       s.titre as service_titre, s.type_service, s.prix_total as svc_prix, s.montant_paye as svc_paye
                       FROM paiements pa 
                       JOIN voyageurs v ON pa.voyageur_id=v.id 
                       LEFT JOIN inscriptions i ON pa.inscription_id=i.id 
                       LEFT JOIN programmes pr ON i.programme_id=pr.id 
                       LEFT JOIN services s ON pa.service_id=s.id
                       WHERE pa.id=?");
    $p->execute([$id]);
    $p = $p->fetch();
    if (!$p) { flash('error', 'Paiement introuvable.'); redirect('/paiements.php'); }
    $ag = getAgencyInfo();
    
    $isService = !empty($p['service_id']);
    $prixTotal = $isService ? $p['svc_prix'] : $p['ins_prix'];
    $montantPaye = $isService ? $p['svc_paye'] : $p['ins_paye'];
    $libelle = $isService ? "Service: " . sanitize($p['service_titre']) : "Programme: " . sanitize($p['programme_nom']);
    $details = $isService ? "Type: " . ucfirst($p['type_service']) : "Dossier: " . sanitize($p['num_dossier']) . "<br>Chambre: " . ucfirst($p['formule']);

?>
<!DOCTYPE html>
<html lang="fr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reçu de paiement - <?= sanitize($ag['agence_nom'] ?? APP_NAME) ?></title>
<link href="<?= APP_URL ?>/assets/css/bootstrap.min.css" rel="stylesheet">
<link href="<?= APP_URL ?>/assets/css/bootstrap-icons.min.css" rel="stylesheet">
<style>
    body { background: #f8f9fa; }
    .receipt { max-width: 800px; margin: 20px auto; background: white; padding: 40px; border: 2px solid #dee2e6; }
    .receipt-header { border-bottom: 3px solid #065f46; padding-bottom: 20px; margin-bottom: 20px; }
    @media print { body { background: white; } .receipt { border: none; margin: 0; } .no-print { display: none; } }
</style>
</head><body>
<div class="no-print text-center py-3">
    <button onclick="window.print()" class="btn btn-primary"><i class="bi bi-printer me-2"></i>Imprimer</button>
    <a href="<?= APP_URL ?>/paiements.php" class="btn btn-outline-secondary ms-2">Retour</a>
</div>
<div class="receipt">
    <div class="receipt-header">
        <div class="row align-items-center">
            <div class="col-8">
                <?php if (!empty($ag['agence_logo'])): ?>
                    <img src="<?= APP_URL ?>/uploads/<?= sanitize($ag['agence_logo']) ?>" alt="Logo" style="max-height:60px;" class="mb-1">
                <?php endif; ?>
                <h3 class="text-success mb-1"><?= sanitize($ag['agence_nom'] ?? 'UpTours') ?></h3>
                <p class="text-muted mb-0"><?= sanitize($ag['agence_slogan'] ?? '') ?></p>
                <p class="small text-muted mb-0"><?= sanitize($ag['agence_adresse'] ?? '') ?> – <?= sanitize($ag['agence_ville'] ?? '') ?></p>
                <p class="small text-muted mb-0">Tél: <?= sanitize($ag['agence_telephone'] ?? '') ?> <?= !empty($ag['agence_fax']) ? '| Fax: '.sanitize($ag['agence_fax']) : '' ?></p>
                <p class="small text-muted mb-0"><?= !empty($ag['agence_email']) ? sanitize($ag['agence_email']) : '' ?> <?= !empty($ag['agence_site_web']) ? '| '.sanitize($ag['agence_site_web']) : '' ?></p>
                <?php if (!empty($ag['agence_ice'])): ?><p class="small text-muted mb-0">ICE: <?= sanitize($ag['agence_ice']) ?> | IF: <?= sanitize($ag['agence_if'] ?? '') ?> | RC: <?= sanitize($ag['agence_rc'] ?? '') ?></p><?php endif; ?>
            </div>
            <div class="col-4 text-end">
                <h5 class="mb-1">REÇU DE PAIEMENT</h5>
                <p class="text-muted mb-0">N° <?= str_pad($p['id'], 6, '0', STR_PAD_LEFT) ?></p>
            </div>
        </div>
    </div>
    <div class="row mb-4">
        <div class="col-6">
            <strong>Client:</strong><br>
            <?= sanitize($p['prenom'].' '.$p['nom']) ?><br>
            CIN: <?= sanitize($p['cin'] ?: '-') ?><br>
            Tél: <?= sanitize($p['telephone'] ?: '-') ?><br>
            <?= sanitize($p['ville'] ?: '') ?>
        </div>
        <div class="col-6 text-end">
            <strong>Date:</strong> <?= formatDate($p['date_paiement']) ?><br>
            <strong><?= $libelle ?></strong><br>
            <?= $details ?>
        </div>
    </div>
    <table class="table table-bordered">
        <thead class="table-light"><tr><th>Description</th><th class="text-end">Montant</th></tr></thead>
        <tbody>
            <tr><td>Paiement - <?= ucfirst($p['mode_paiement']) ?> <?= $p['reference_paiement'] ? '(Réf: '.$p['reference_paiement'].')' : '' ?></td><td class="text-end fw-bold"><?= formatMoney($p['montant']) ?></td></tr>
        </tbody>
        <tfoot>
            <tr><td class="text-end">Prix total:</td><td class="text-end"><?= formatMoney($prixTotal) ?></td></tr>
            <tr><td class="text-end">Total payé à ce jour:</td><td class="text-end text-success fw-bold"><?= formatMoney($montantPaye) ?></td></tr>
            <tr><td class="text-end">Reste à payer:</td><td class="text-end text-danger fw-bold"><?= formatMoney($prixTotal - $montantPaye) ?></td></tr>
        </tfoot>
    </table>
    <?php if ($p['notes']): ?><p><strong>Notes:</strong> <?= sanitize($p['notes']) ?></p><?php endif; ?>
    <?php if (!empty($ag['agence_banque_nom'])): ?>
    <div class="border rounded p-2 mb-3 small">
        <strong>Coordonnées bancaires:</strong> <?= sanitize($ag['agence_banque_nom']) ?> – <?= sanitize($ag['agence_banque_agence'] ?? '') ?><br>
        RIB: <span class="font-monospace"><?= sanitize($ag['agence_banque_rib'] ?? '') ?></span>
        <?php if (!empty($ag['agence_banque_iban'])): ?> | IBAN: <span class="font-monospace"><?= sanitize($ag['agence_banque_iban']) ?></span><?php endif; ?>
    </div>
    <?php endif; ?>
    <div class="row mt-5">
        <div class="col-6"><p class="border-top pt-2">Signature du client</p></div>
        <div class="col-6 text-end"><p class="border-top pt-2">Cachet et signature de l'agence</p></div>
    </div>
    <p class="text-center text-muted small mt-4"><?= sanitize($ag['agence_nom'] ?? APP_NAME) ?> | <?= sanitize($ag['agence_telephone'] ?? '') ?> | <?= sanitize($ag['agence_email'] ?? '') ?> – Reçu généré le <?= date('d/m/Y H:i') ?></p>
</div>
</body></html>
<?php
    exit;
}

// Form
if ($action === 'add' || $action === 'edit') {
    $paiement = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM paiements WHERE id=?");
        $stmt->execute([$id]);
        $paiement = $stmt->fetch();
        if (!$paiement) { flash('error', 'Paiement introuvable.'); redirect('/paiements.php'); }
    }
    
    $preselectedInscription = $paiement ? $paiement['inscription_id'] : intval($_GET['inscription_id'] ?? 0);
    $preselectedService = $paiement ? $paiement['service_id'] : intval($_GET['service_id'] ?? 0);
    
    $typePaiement = $preselectedService ? 'service' : 'inscription';
    if ($paiement && $paiement['service_id']) $typePaiement = 'service';
    
    $inscriptions = $db->query("SELECT i.*, v.nom, v.prenom, p.nom as programme_nom FROM inscriptions i JOIN voyageurs v ON i.voyageur_id=v.id JOIN programmes p ON i.programme_id=p.id WHERE i.status != 'annule' ORDER BY i.created_at DESC")->fetchAll();
    
    $services = $db->query("SELECT s.*, v.nom, v.prenom FROM services s JOIN voyageurs v ON s.voyageur_id=v.id WHERE s.statut_service != 'annule' ORDER BY s.created_at DESC")->fetchAll();
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/paiements.php" 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-cash-coin me-2"></i><?= $paiement ? 'Modifier le paiement' : 'Nouveau paiement' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $paiement['id'] ?? '' ?>">
                
                <!-- Toggle entre Inscription et Service -->
                <div class="mb-4">
                    <label class="form-label d-block text-muted">Ce paiement concerne :</label>
                    <div class="btn-group" role="group">
                        <input type="radio" class="btn-check" name="type_paiement" id="type_ins" value="inscription" <?= $typePaiement=='inscription'?'checked':'' ?> onchange="toggleTypePaiement()">
                        <label class="btn btn-outline-primary" for="type_ins"><i class="bi bi-journal-check me-2"></i>Programme / Inscription</label>

                        <input type="radio" class="btn-check" name="type_paiement" id="type_svc" value="service" <?= $typePaiement=='service'?'checked':'' ?> onchange="toggleTypePaiement()">
                        <label class="btn btn-outline-primary" for="type_svc"><i class="bi bi-briefcase me-2"></i>Service (Billet, Visa...)</label>
                    </div>
                </div>

                <div class="row g-3">
                    <div class="col-md-12" id="block_inscription" style="<?= $typePaiement=='inscription' ? '' : 'display:none;' ?>">
                        <label class="form-label">Inscription *</label>
                        <select name="inscription_id" class="form-select select2" id="select_inscription">
                            <option value="">-- Sélectionner --</option>
                            <?php foreach ($inscriptions as $ins): ?>
                                <option value="<?= $ins['id'] ?>" <?= $preselectedInscription==$ins['id']?'selected':'' ?>>
                                    <?= sanitize($ins['num_dossier'].' - '.$ins['prenom'].' '.$ins['nom'].' | '.$ins['programme_nom'].' | Reste: '.formatMoney($ins['prix_total']-$ins['montant_paye'])) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-12" id="block_service" style="<?= $typePaiement=='service' ? '' : 'display:none;' ?>">
                        <label class="form-label">Service *</label>
                        <select name="service_id" class="form-select select2" id="select_service">
                            <option value="">-- Sélectionner --</option>
                            <?php foreach ($services as $svc): ?>
                                <option value="<?= $svc['id'] ?>" <?= $preselectedService==$svc['id']?'selected':'' ?>>
                                    <?= sanitize($svc['prenom'].' '.$svc['nom'].' | '.$svc['titre'].' | Reste: '.formatMoney($svc['prix_total']-$svc['montant_paye'])) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Montant (MAD) *</label>
                        <input type="number" step="0.01" name="montant" class="form-control" value="<?= $paiement['montant'] ?? '' ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Mode de paiement</label>
                        <select name="mode_paiement" class="form-select">
                            <option value="especes" <?= ($paiement['mode_paiement']??'')=='especes'?'selected':'' ?>>Espèces</option>
                            <option value="virement" <?= ($paiement['mode_paiement']??'')=='virement'?'selected':'' ?>>Virement bancaire</option>
                            <option value="cheque" <?= ($paiement['mode_paiement']??'')=='cheque'?'selected':'' ?>>Chèque</option>
                            <option value="carte" <?= ($paiement['mode_paiement']??'')=='carte'?'selected':'' ?>>Carte bancaire</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Date</label>
                        <input type="date" name="date_paiement" class="form-control" value="<?= $paiement['date_paiement'] ?? date('Y-m-d') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Référence</label>
                        <input type="text" name="reference_paiement" class="form-control" placeholder="N° chèque, virement, etc." value="<?= sanitize($paiement['reference_paiement'] ?? '') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Notes</label>
                        <input type="text" name="notes" class="form-control" value="<?= sanitize($paiement['notes'] ?? '') ?>">
                    </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 ?>/paiements.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// List
$search = $_GET['search'] ?? '';
$modeFilter = $_GET['mode'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (v.nom LIKE ? OR v.prenom LIKE ? OR pa.reference_paiement LIKE ? OR i.num_dossier LIKE ? OR s.titre LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s,$s,$s]; }
if ($modeFilter) { $where .= " AND pa.mode_paiement=?"; $params[] = $modeFilter; }

$total = $db->prepare("SELECT COUNT(*) FROM paiements pa JOIN voyageurs v ON pa.voyageur_id=v.id LEFT JOIN inscriptions i ON pa.inscription_id=i.id LEFT JOIN services s ON pa.service_id=s.id $where");
$total->execute($params);
$pagination = paginate($total->fetchColumn(), 15, $page);

$stmt = $db->prepare("SELECT pa.*, v.nom, v.prenom, 
                      i.num_dossier, p.nom as programme_nom, p.type as programme_type,
                      s.titre as service_titre, s.type_service
                      FROM paiements pa 
                      JOIN voyageurs v ON pa.voyageur_id=v.id 
                      LEFT JOIN inscriptions i ON pa.inscription_id=i.id 
                      LEFT JOIN programmes p ON i.programme_id=p.id 
                      LEFT JOIN services s ON pa.service_id=s.id
                      $where ORDER BY pa.created_at DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$paiements = $stmt->fetchAll();

$totalMontant = $db->prepare("SELECT COALESCE(SUM(pa.montant),0) FROM paiements pa JOIN voyageurs v ON pa.voyageur_id=v.id LEFT JOIN inscriptions i ON pa.inscription_id=i.id LEFT JOIN services s ON pa.service_id=s.id $where");
$totalMontant->execute($params);
$totalMontant = $totalMontant->fetchColumn();
?>

<div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
    <form class="d-flex gap-2 flex-wrap" method="GET">
        <div class="input-group" style="width:250px;">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control" placeholder="Rechercher..." value="<?= sanitize($search) ?>">
        </div>
        <select name="mode" class="form-select" style="width:160px;">
            <option value="">Tous modes</option>
            <option value="especes" <?= $modeFilter=='especes'?'selected':'' ?>>Espèces</option>
            <option value="virement" <?= $modeFilter=='virement'?'selected':'' ?>>Virement</option>
            <option value="cheque" <?= $modeFilter=='cheque'?'selected':'' ?>>Chèque</option>
            <option value="carte" <?= $modeFilter=='carte'?'selected':'' ?>>Carte</option>
        </select>
        <button class="btn btn-outline-primary">Filtrer</button>
    </form>
    <div class="d-flex gap-2 align-items-center">
        <span class="badge bg-success fs-6 py-2 px-3">Total: <?= formatMoney($totalMontant) ?></span>
        <a href="<?= APP_URL ?>/paiements.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouveau paiement</a>
    </div>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr>
                <th>Date</th><th>Type</th><th>Dossier / Service</th><th>Voyageur</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>
                        <?php if ($p['service_id']): ?>
                            <span class="badge bg-secondary"><i class="bi bi-briefcase me-1"></i>Service</span>
                        <?php else: ?>
                            <span class="badge bg-primary"><i class="bi bi-journal-check me-1"></i>Programme</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($p['service_id']): ?>
                            <small class="d-block fw-bold"><?= sanitize($p['service_titre']) ?></small>
                        <?php else: ?>
                            <strong><?= sanitize($p['num_dossier'] ?: '-') ?></strong><br>
                            <small class="text-muted"><?= sanitize($p['programme_nom']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $p['voyageur_id'] ?>"><?= sanitize($p['prenom'].' '.$p['nom']) ?></a></td>
                    <td class="fw-bold text-success"><?= formatMoney($p['montant']) ?></td>
                    <td><span class="badge bg-light text-dark"><?= ucfirst($p['mode_paiement']) ?></span></td>
                    <td><small><?= sanitize($p['reference_paiement'] ?: '-') ?></small></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/paiements.php?action=recu&id=<?= $p['id'] ?>" class="btn btn-outline-primary" title="Reçu" target="_blank"><i class="bi bi-printer"></i></a>
                            <a href="<?= APP_URL ?>/paiements.php?action=edit&id=<?= $p['id'] ?>" class="btn btn-outline-warning" title="Modifier"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/paiements.php?action=delete&id=<?= $p['id'] ?>" class="btn btn-outline-danger" title="Supprimer" onclick="return confirmDelete('Supprimer ce paiement ?')"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($paiements)): ?><tr><td colspan="8" class="text-center text-muted py-4">Aucun paiement</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
        <div class="card-footer">
        <?= renderPagination($pagination, APP_URL.'/paiements.php?search='.urlencode($search).'&mode='.urlencode($modeFilter)) ?>
    </div>
</div>

<script>
function toggleTypePaiement() {
    const isService = document.getElementById('type_svc').checked;
    
    document.getElementById('block_inscription').style.display = isService ? 'none' : 'block';
    document.getElementById('block_service').style.display = isService ? 'block' : 'none';
    
    // Disable elements instead of just hiding them so they don't block form submission or send empty values
    document.getElementById('select_inscription').disabled = isService;
    document.getElementById('select_service').disabled = !isService;
}

// Initial setup
document.addEventListener('DOMContentLoaded', toggleTypePaiement);
</script>

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