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

// Load filter options
$programmes = $db->query("SELECT id, nom, type, reference FROM programmes ORDER BY date_depart DESC")->fetchAll();
$groupes = $db->query("SELECT id, nom, type, programme_id FROM groupes WHERE status='actif' ORDER BY nom")->fetchAll();
$vols = $db->query("SELECT id, compagnie, numero_vol, aeroport_depart, aeroport_arrivee, date_depart, programme_id FROM vols WHERE status='actif' ORDER BY date_depart")->fetchAll();
$hotels = $db->query("SELECT id, nom, ville FROM hotels WHERE status='actif' ORDER BY nom")->fetchAll();
$villes = $db->query("SELECT DISTINCT ville FROM voyageurs WHERE ville IS NOT NULL AND ville != '' ORDER BY ville")->fetchAll(PDO::FETCH_COLUMN);

// Get filters from GET
$f = [
    'programme_id'    => $_GET['programme_id'] ?? '',
    'type'            => $_GET['type'] ?? '',
    'vol_id'          => $_GET['vol_id'] ?? '',
    'groupe_id'       => $_GET['groupe_id'] ?? '',
    'hotel_id'        => $_GET['hotel_id'] ?? '',
    'formule'         => $_GET['formule'] ?? '',
    'statut_visa'     => $_GET['statut_visa'] ?? '',
    'statut_paiement' => $_GET['statut_paiement'] ?? '',
    'vaccination'     => $_GET['vaccination'] ?? '',
    'sexe'            => $_GET['sexe'] ?? '',
    'ville'           => $_GET['ville'] ?? '',
    'status'          => $_GET['status'] ?? '',
    'search'          => $_GET['search'] ?? '',
    'sort'            => $_GET['sort'] ?? 'nom',
    'order'           => $_GET['order'] ?? 'asc',
    'mode'            => $_GET['mode'] ?? 'complet',
];

// Columns visibility
$defaultCols = ['num_dossier','nom_complet','sexe','cin','passeport','telephone','ville','programme','formule','statut_visa','vaccination','paiement'];
$cols = isset($_GET['cols']) ? (array)$_GET['cols'] : $defaultCols;

// Build query
$where = "WHERE 1=1";
$params = [];

if ($f['programme_id']) { $where .= " AND i.programme_id = ?"; $params[] = $f['programme_id']; }
if ($f['type']) { $where .= " AND p.type = ?"; $params[] = $f['type']; }
if ($f['vol_id']) { $where .= " AND (i.vol_aller_id = ? OR i.vol_retour_id = ?)"; $params[] = $f['vol_id']; $params[] = $f['vol_id']; }
if ($f['groupe_id']) { $where .= " AND i.groupe_id = ?"; $params[] = $f['groupe_id']; }
if ($f['hotel_id']) { $where .= " AND i.hotel_id = ?"; $params[] = $f['hotel_id']; }
if ($f['formule']) { $where .= " AND i.formule = ?"; $params[] = $f['formule']; }
if ($f['statut_visa']) { $where .= " AND i.statut_visa = ?"; $params[] = $f['statut_visa']; }
if ($f['statut_paiement']) { $where .= " AND i.statut_paiement = ?"; $params[] = $f['statut_paiement']; }
if ($f['vaccination']) { $where .= " AND i.vaccination = ?"; $params[] = $f['vaccination']; }
if ($f['sexe']) { $where .= " AND v.sexe = ?"; $params[] = $f['sexe']; }
if ($f['ville']) { $where .= " AND v.ville = ?"; $params[] = $f['ville']; }
if ($f['status']) { $where .= " AND i.status = ?"; $params[] = $f['status']; }
if ($f['search']) { $where .= " AND (v.nom LIKE ? OR v.prenom LIKE ? OR v.cin LIKE ? OR v.num_passeport LIKE ? OR i.num_dossier LIKE ?)"; $s="%{$f['search']}%"; $params = array_merge($params, [$s,$s,$s,$s,$s]); }

// Sort
$allowedSorts = [
    'nom' => 'v.nom',
    'prenom' => 'v.prenom',
    'ville' => 'v.ville',
    'programme' => 'p.nom',
    'formule' => 'i.formule',
    'statut_visa' => 'i.statut_visa',
    'paiement' => 'i.statut_paiement',
    'dossier' => 'i.num_dossier',
    'date_inscription' => 'i.created_at',
];
$sortCol = $allowedSorts[$f['sort']] ?? 'v.nom';
$sortOrder = strtoupper($f['order']) === 'DESC' ? 'DESC' : 'ASC';

$sql = "SELECT 
    i.id as inscription_id, i.num_dossier, i.formule, i.statut_visa, i.vaccination,
    i.chambre_type, i.chambre_numero, i.prix_total, i.montant_paye, i.statut_paiement, i.status as inscription_status,
    i.groupe_id, i.hotel_id, i.vol_aller_id, i.vol_retour_id, i.created_at as date_inscription,
    v.id as voyageur_id, v.reference as voyageur_ref, v.nom, v.prenom, v.date_naissance, v.lieu_naissance,
    v.sexe, v.nationalite, v.cin, v.num_passeport, v.date_expiration_passeport,
    v.telephone, v.telephone2, v.email, v.adresse, v.ville,
    v.contact_urgence_nom, v.contact_urgence_tel, v.contact_urgence_lien,
    p.nom as programme_nom, p.type as programme_type, p.reference as programme_ref,
    p.date_depart as prog_date_depart, p.date_retour as prog_date_retour, p.destination,
    g.nom as groupe_nom,
    h.nom as hotel_nom, h.ville as hotel_ville,
    va.compagnie as vol_aller_compagnie, va.numero_vol as vol_aller_num, va.date_depart as vol_aller_date,
    vr.compagnie as vol_retour_compagnie, vr.numero_vol as vol_retour_num, vr.date_depart as vol_retour_date
FROM inscriptions i
JOIN voyageurs v ON i.voyageur_id = v.id
JOIN programmes p ON i.programme_id = p.id
LEFT JOIN groupes g ON i.groupe_id = g.id
LEFT JOIN hotels h ON i.hotel_id = h.id
LEFT JOIN vols va ON i.vol_aller_id = va.id
LEFT JOIN vols vr ON i.vol_retour_id = vr.id
$where
ORDER BY $sortCol $sortOrder";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll();

// Stats
$totalVoyageurs = count($results);
$totalPaye = array_sum(array_column($results, 'montant_paye'));
$totalDu = array_sum(array_column($results, 'prix_total'));
$totalRestant = $totalDu - $totalPaye;
$nbPaye = count(array_filter($results, fn($r) => $r['statut_paiement'] === 'paye'));
$nbPartiel = count(array_filter($results, fn($r) => $r['statut_paiement'] === 'partiel'));
$nbImpaye = count(array_filter($results, fn($r) => $r['statut_paiement'] === 'impaye'));
$nbVisaConfirme = count(array_filter($results, fn($r) => $r['statut_visa'] === 'confirme'));
$nbVisaAttente = count(array_filter($results, fn($r) => $r['statut_visa'] === 'en_attente'));
$nbVaccine = count(array_filter($results, fn($r) => $r['vaccination'] === 'oui'));
$nbHommes = count(array_filter($results, fn($r) => $r['sexe'] === 'M'));
$nbFemmes = count(array_filter($results, fn($r) => $r['sexe'] === 'F'));

// Agency info for print header
$agency = getAgencyInfo();

// All available columns definition
$allColumns = [
    'num_dossier'    => ['label' => 'N° Dossier',     'group' => 'inscription'],
    'nom_complet'    => ['label' => 'Nom & Prénom',    'group' => 'identite'],
    'sexe'           => ['label' => 'Sexe',            'group' => 'identite'],
    'date_naissance' => ['label' => 'Date naissance',  'group' => 'identite'],
    'nationalite'    => ['label' => 'Nationalité',     'group' => 'identite'],
    'cin'            => ['label' => 'CIN',             'group' => 'identite'],
    'passeport'      => ['label' => 'Passeport',       'group' => 'identite'],
    'exp_passeport'  => ['label' => 'Exp. Passeport',  'group' => 'identite'],
    'telephone'      => ['label' => 'Téléphone',       'group' => 'contact'],
    'telephone2'     => ['label' => 'Téléphone 2',     'group' => 'contact'],
    'email'          => ['label' => 'Email',           'group' => 'contact'],
    'adresse'        => ['label' => 'Adresse',         'group' => 'contact'],
    'ville'          => ['label' => 'Ville',           'group' => 'contact'],
    'contact_urgence'=> ['label' => 'Contact urgence', 'group' => 'contact'],
    'programme'      => ['label' => 'Programme',       'group' => 'inscription'],
    'destination'    => ['label' => 'Destination',     'group' => 'inscription'],
    'formule'        => ['label' => 'Chambre',         'group' => 'inscription'],
    'groupe'         => ['label' => 'Groupe',          'group' => 'inscription'],
    'hotel'          => ['label' => 'Hôtel',           'group' => 'logistique'],
    'chambre_info'   => ['label' => 'N° Chambre',      'group' => 'logistique'],
    'vol_aller'      => ['label' => 'Vol Aller',       'group' => 'logistique'],
    'vol_retour'     => ['label' => 'Vol Retour',      'group' => 'logistique'],
    'statut_visa'    => ['label' => 'Visa',            'group' => 'statut'],
    'vaccination'    => ['label' => 'Vaccination',     'group' => 'statut'],
    'paiement'       => ['label' => 'Paiement',        'group' => 'finance'],
    'montant_paye'   => ['label' => 'Montant payé',    'group' => 'finance'],
    'prix_total'     => ['label' => 'Prix total',      'group' => 'finance'],
    'reste'          => ['label' => 'Reste à payer',   'group' => 'finance'],
    'statut'         => ['label' => 'Statut',          'group' => 'statut'],
    'date_inscription'=> ['label' => 'Date inscription','group' => 'inscription'],
];

// Helper to build query string preserving filters
function buildFilterUrl($overrides = []) {
    global $f, $cols;
    $params = array_merge($f, $overrides);
    $params['cols'] = $overrides['cols'] ?? $cols;
    return '?' . http_build_query($params);
}
?>

<!-- Print-only styles -->
<style>
    @media print {
        .sidebar, .top-navbar, .no-print, .sidebar-overlay { display: none !important; }
        .main-content { margin-left: 0 !important; }
        .content-area { padding: 0 !important; }
        body { background: #fff !important; font-size: 11px !important; }
        .print-header { display: block !important; }
        .table th { background: #e9ecef !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        .table td, .table th { padding: 4px 6px !important; font-size: 10px !important; }
        .badge { border: 1px solid #999 !important; padding: 2px 5px !important; font-size: 9px !important; }
        .bg-success { background: #d4edda !important; color: #155724 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        .bg-warning { background: #fff3cd !important; color: #856404 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        .bg-danger { background: #f8d7da !important; color: #721c24 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        .bg-primary { background: #cce5ff !important; color: #004085 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        .bg-info { background: #d1ecf1 !important; color: #0c5460 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        .stat-card { box-shadow: none !important; border: 1px solid #dee2e6 !important; break-inside: avoid; }
        .print-stats .col-md-3 { flex: 0 0 25%; max-width: 25%; }
        .card { border-radius: 4px !important; }
        .table-card { border-radius: 0 !important; box-shadow: none !important; border: 1px solid #dee2e6 !important; }
        @page { size: landscape; margin: 10mm; }
        .print-footer { display: block !important; position: fixed; bottom: 0; width: 100%; text-align: center; font-size: 9px; color: #999; border-top: 1px solid #ddd; padding-top: 4px; }
    }
    @media screen {
        .print-header { display: none; }
        .print-footer { display: none; }
    }
    .filter-panel { background: #fff; border-radius: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
    .filter-panel .form-label { font-size: 0.75rem; font-weight: 600; color: #475569; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 0.25rem; }
    .filter-panel .form-select, .filter-panel .form-control { font-size: 0.85rem; padding: 0.35rem 0.6rem; }
    .columns-panel { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; }
    .columns-panel.show { max-height: 500px; }
    .col-check { display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; margin: 2px; background: #f1f5f9; border-radius: 6px; font-size: 0.8rem; cursor: pointer; transition: all 0.15s; }
    .col-check:hover { background: #e2e8f0; }
    .col-check input:checked + span { color: #065f46; font-weight: 600; }
    .col-group-title { font-size: 0.7rem; font-weight: 700; text-transform: uppercase; color: #94a3b8; letter-spacing: 0.5px; margin-bottom: 2px; margin-top: 8px; }
    .active-filters .badge { cursor: pointer; }
    .active-filters .badge:hover { opacity: 0.7; }
    .print-table { width: 100%; }
    .print-table th { white-space: nowrap; }
    .print-table td { white-space: nowrap; max-width: 200px; overflow: hidden; text-overflow: ellipsis; }
    .counter-badge { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; border-radius: 50%; font-size: 0.7rem; font-weight: 700; }
</style>

<!-- Print Header (visible only when printing) -->
<div class="print-header mb-3">
    <div class="d-flex justify-content-between align-items-start border-bottom pb-2 mb-2">
        <div>
            <h4 class="mb-0 fw-bold"><?= sanitize($agency['agence_nom'] ?? 'UpTours') ?></h4>
            <small class="text-muted"><?= sanitize($agency['agence_slogan'] ?? '') ?></small><br>
            <small><?= sanitize($agency['agence_adresse'] ?? '') ?> - <?= sanitize($agency['agence_ville'] ?? '') ?></small><br>
            <small>Tél: <?= sanitize($agency['agence_telephone'] ?? '') ?> | Email: <?= sanitize($agency['agence_email'] ?? '') ?></small>
        </div>
        <div class="text-end">
            <h5 class="mb-1">Liste des voyageurs</h5>
            <small>Imprimé le <?= date('d/m/Y à H:i') ?></small><br>
            <small class="fw-bold"><?= $totalVoyageurs ?> voyageur(s)</small>
            <?php if ($f['programme_id']):
                $selProg = array_filter($programmes, fn($p) => $p['id'] == $f['programme_id']);
                $selProg = reset($selProg);
                if ($selProg): ?>
                    <br><small>Programme: <?= sanitize($selProg['nom']) ?></small>
                <?php endif; endif; ?>
        </div>
    </div>
</div>

<!-- Toolbar -->
<div class="d-flex flex-wrap justify-content-between align-items-center mb-3 no-print gap-2">
    <div class="d-flex align-items-center gap-2">
        <h6 class="mb-0"><i class="bi bi-printer me-1"></i>Liste des voyageurs</h6>
        <span class="badge bg-primary rounded-pill"><?= $totalVoyageurs ?> résultat(s)</span>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary btn-sm" onclick="toggleColumns()">
            <i class="bi bi-layout-three-columns me-1"></i>Colonnes
        </button>
        <button class="btn btn-outline-success btn-sm" onclick="exportCSV()">
            <i class="bi bi-file-earmark-spreadsheet me-1"></i>Export CSV
        </button>
        <button class="btn btn-primary btn-sm" onclick="window.print()">
            <i class="bi bi-printer-fill me-1"></i>Imprimer
        </button>
    </div>
</div>

<!-- Filter Panel -->
<div class="filter-panel p-3 mb-3 no-print">
    <form method="GET" id="filterForm">
        <!-- Preserve column selection -->
        <div id="hiddenCols"></div>
        
        <div class="row g-2">
            <div class="col-md-3 col-lg-2">
                <label class="form-label">Programme</label>
                <select name="programme_id" class="form-select select2" onchange="this.form.submit()">
                    <option value="">-- Tous --</option>
                    <?php foreach ($programmes as $p): ?>
                        <option value="<?= $p['id'] ?>" <?= $f['programme_id']==$p['id']?'selected':'' ?>><?= sanitize($p['nom']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Type</label>
                <select name="type" class="form-select" onchange="this.form.submit()">
                    <option value="">Tous</option>
                    <option value="hajj" <?= $f['type']=='hajj'?'selected':'' ?>>Hajj</option>
                    <option value="omra" <?= $f['type']=='omra'?'selected':'' ?>>Omra</option>
                    <option value="voyage" <?= $f['type']=='voyage'?'selected':'' ?>>Voyage</option>
                </select>
            </div>
            <div class="col-md-3 col-lg-2">
                <label class="form-label">Vol</label>
                <select name="vol_id" class="form-select select2" onchange="this.form.submit()">
                    <option value="">-- Tous --</option>
                    <?php foreach ($vols as $vol): ?>
                        <option value="<?= $vol['id'] ?>" <?= $f['vol_id']==$vol['id']?'selected':'' ?>><?= sanitize($vol['compagnie'].' '.$vol['numero_vol'].' ('.$vol['aeroport_depart'].' → '.$vol['aeroport_arrivee'].')') ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 col-lg-2">
                <label class="form-label">Groupe</label>
                <select name="groupe_id" class="form-select select2" onchange="this.form.submit()">
                    <option value="">-- Tous --</option>
                    <?php foreach ($groupes as $g): ?>
                        <option value="<?= $g['id'] ?>" <?= $f['groupe_id']==$g['id']?'selected':'' ?>><?= sanitize($g['nom']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 col-lg-2">
                <label class="form-label">Hôtel</label>
                <select name="hotel_id" class="form-select select2" onchange="this.form.submit()">
                    <option value="">-- Tous --</option>
                    <?php foreach ($hotels as $h): ?>
                        <option value="<?= $h['id'] ?>" <?= $f['hotel_id']==$h['id']?'selected':'' ?>><?= sanitize($h['nom']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Chambre</label>
                <select name="formule" class="form-select" onchange="this.form.submit()">
                    <option value="">Toutes</option>
                    <option value="double" <?= $f['formule']=='double'?'selected':'' ?>>Double</option>
                    <option value="triple" <?= $f['formule']=='triple'?'selected':'' ?>>Triple</option>
                    <option value="quadruple" <?= $f['formule']=='quadruple'?'selected':'' ?>>Quadruple</option>
                    <option value="quintuple" <?= $f['formule']=='quintuple'?'selected':'' ?>>Quintuple</option>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Visa</label>
                <select name="statut_visa" class="form-select" onchange="this.form.submit()">
                    <option value="">Tous</option>
                    <option value="en_attente" <?= $f['statut_visa']=='en_attente'?'selected':'' ?>>En attente</option>
                    <option value="confirme" <?= $f['statut_visa']=='confirme'?'selected':'' ?>>Confirmé</option>
                    <option value="refuse" <?= $f['statut_visa']=='refuse'?'selected':'' ?>>Refusé</option>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Paiement</label>
                <select name="statut_paiement" class="form-select" onchange="this.form.submit()">
                    <option value="">Tous</option>
                    <option value="paye" <?= $f['statut_paiement']=='paye'?'selected':'' ?>>Payé</option>
                    <option value="partiel" <?= $f['statut_paiement']=='partiel'?'selected':'' ?>>Partiel</option>
                    <option value="impaye" <?= $f['statut_paiement']=='impaye'?'selected':'' ?>>Impayé</option>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Vaccination</label>
                <select name="vaccination" class="form-select" onchange="this.form.submit()">
                    <option value="">Tous</option>
                    <option value="oui" <?= $f['vaccination']=='oui'?'selected':'' ?>>Oui</option>
                    <option value="non" <?= $f['vaccination']=='non'?'selected':'' ?>>Non</option>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Sexe</label>
                <select name="sexe" class="form-select" onchange="this.form.submit()">
                    <option value="">Tous</option>
                    <option value="M" <?= $f['sexe']=='M'?'selected':'' ?>>Homme</option>
                    <option value="F" <?= $f['sexe']=='F'?'selected':'' ?>>Femme</option>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Ville</label>
                <select name="ville" class="form-select select2" onchange="this.form.submit()">
                    <option value="">Toutes</option>
                    <?php foreach ($villes as $v): ?>
                        <option value="<?= sanitize($v) ?>" <?= $f['ville']==$v?'selected':'' ?>><?= sanitize($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Statut</label>
                <select name="status" class="form-select" onchange="this.form.submit()">
                    <option value="">Tous</option>
                    <option value="en_cours" <?= $f['status']=='en_cours'?'selected':'' ?>>En cours</option>
                    <option value="confirme" <?= $f['status']=='confirme'?'selected':'' ?>>Confirmé</option>
                    <option value="annule" <?= $f['status']=='annule'?'selected':'' ?>>Annulé</option>
                </select>
            </div>
            <div class="col-md-3 col-lg-2">
                <label class="form-label">Recherche</label>
                <div class="input-group input-group-sm">
                    <input type="text" name="search" class="form-control" placeholder="Nom, CIN, Passeport..." value="<?= sanitize($f['search']) ?>">
                    <button class="btn btn-outline-primary" type="submit"><i class="bi bi-search"></i></button>
                </div>
            </div>
            <div class="col-md-2 col-lg-1">
                <label class="form-label">Tri</label>
                <select name="sort" class="form-select" onchange="this.form.submit()">
                    <option value="nom" <?= $f['sort']=='nom'?'selected':'' ?>>Nom</option>
                    <option value="prenom" <?= $f['sort']=='prenom'?'selected':'' ?>>Prénom</option>
                    <option value="ville" <?= $f['sort']=='ville'?'selected':'' ?>>Ville</option>
                    <option value="programme" <?= $f['sort']=='programme'?'selected':'' ?>>Programme</option>
                    <option value="formule" <?= $f['sort']=='formule'?'selected':'' ?>>Chambre</option>
                    <option value="paiement" <?= $f['sort']=='paiement'?'selected':'' ?>>Paiement</option>
                    <option value="dossier" <?= $f['sort']=='dossier'?'selected':'' ?>>N° Dossier</option>
                    <option value="date_inscription" <?= $f['sort']=='date_inscription'?'selected':'' ?>>Date inscr.</option>
                </select>
            </div>
            <div class="col-auto">
                <label class="form-label">Ordre</label>
                <select name="order" class="form-select" onchange="this.form.submit()">
                    <option value="asc" <?= $f['order']=='asc'?'selected':'' ?>>A→Z</option>
                    <option value="desc" <?= $f['order']=='desc'?'selected':'' ?>>Z→A</option>
                </select>
            </div>
            
            <!-- Hidden fields for mode -->
            <input type="hidden" name="mode" value="<?= sanitize($f['mode']) ?>">
        </div>
        
        <!-- Active filters display -->
        <?php
        $activeFilters = [];
        if ($f['programme_id']) { $p = array_filter($programmes, fn($x) => $x['id'] == $f['programme_id']); $p = reset($p); if($p) $activeFilters[] = ['key'=>'programme_id', 'label'=>'Programme: '.$p['nom']]; }
        if ($f['type']) $activeFilters[] = ['key'=>'type', 'label'=>'Type: '.ucfirst($f['type'])];
        if ($f['vol_id']) { $v = array_filter($vols, fn($x) => $x['id'] == $f['vol_id']); $v = reset($v); if($v) $activeFilters[] = ['key'=>'vol_id', 'label'=>'Vol: '.$v['compagnie'].' '.$v['numero_vol']]; }
        if ($f['groupe_id']) { $g = array_filter($groupes, fn($x) => $x['id'] == $f['groupe_id']); $g = reset($g); if($g) $activeFilters[] = ['key'=>'groupe_id', 'label'=>'Groupe: '.$g['nom']]; }
        if ($f['hotel_id']) { $h = array_filter($hotels, fn($x) => $x['id'] == $f['hotel_id']); $h = reset($h); if($h) $activeFilters[] = ['key'=>'hotel_id', 'label'=>'Hôtel: '.$h['nom']]; }
        if ($f['formule']) $activeFilters[] = ['key'=>'formule', 'label'=>'Chambre: '.ucfirst($f['formule'])];
        if ($f['statut_visa']) $activeFilters[] = ['key'=>'statut_visa', 'label'=>'Visa: '.ucfirst(str_replace('_',' ',$f['statut_visa']))];
        if ($f['statut_paiement']) $activeFilters[] = ['key'=>'statut_paiement', 'label'=>'Paiement: '.ucfirst($f['statut_paiement'])];
        if ($f['vaccination']) $activeFilters[] = ['key'=>'vaccination', 'label'=>'Vaccination: '.ucfirst($f['vaccination'])];
        if ($f['sexe']) $activeFilters[] = ['key'=>'sexe', 'label'=>'Sexe: '.($f['sexe']=='M'?'Homme':'Femme')];
        if ($f['ville']) $activeFilters[] = ['key'=>'ville', 'label'=>'Ville: '.$f['ville']];
        if ($f['status']) $activeFilters[] = ['key'=>'status', 'label'=>'Statut: '.ucfirst(str_replace('_',' ',$f['status']))];
        if ($f['search']) $activeFilters[] = ['key'=>'search', 'label'=>'Recherche: "'.$f['search'].'"'];
        ?>
        <?php if (!empty($activeFilters)): ?>
        <div class="active-filters mt-2 d-flex flex-wrap align-items-center gap-1">
            <small class="text-muted me-1"><i class="bi bi-funnel-fill"></i> Filtres:</small>
            <?php foreach ($activeFilters as $af): ?>
                <a href="<?= buildFilterUrl([$af['key'] => '']) ?>" class="badge bg-primary bg-opacity-10 text-primary text-decoration-none">
                    <?= sanitize($af['label']) ?> <i class="bi bi-x-lg ms-1"></i>
                </a>
            <?php endforeach; ?>
            <a href="<?= APP_URL ?>/imprimer.php" class="badge bg-danger bg-opacity-10 text-danger text-decoration-none ms-1">
                <i class="bi bi-x-circle me-1"></i>Tout effacer
            </a>
        </div>
        <?php endif; ?>
    </form>
    
    <!-- Column Selector -->
    <div class="columns-panel mt-2" id="columnsPanel">
        <div class="border-top pt-2">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <small class="fw-bold text-muted"><i class="bi bi-layout-three-columns me-1"></i>Colonnes à afficher</small>
                <div>
                    <button type="button" class="btn btn-outline-primary btn-sm py-0 px-2" style="font-size:0.75rem;" onclick="selectAllCols(true)">Tout cocher</button>
                    <button type="button" class="btn btn-outline-secondary btn-sm py-0 px-2" style="font-size:0.75rem;" onclick="selectAllCols(false)">Tout décocher</button>
                </div>
            </div>
            <?php
            $groups = ['identite'=>'Identité','contact'=>'Contact','inscription'=>'Inscription','logistique'=>'Logistique','statut'=>'Statuts','finance'=>'Finance'];
            foreach ($groups as $gk => $gLabel):
            ?>
            <div class="col-group-title"><?= $gLabel ?></div>
            <div class="d-flex flex-wrap">
                <?php foreach ($allColumns as $ck => $cinfo):
                    if ($cinfo['group'] !== $gk) continue;
                ?>
                <label class="col-check">
                    <input type="checkbox" class="col-toggle" value="<?= $ck ?>" <?= in_array($ck, $cols)?'checked':'' ?> onchange="updateColumns()">
                    <span><?= $cinfo['label'] ?></span>
                </label>
                <?php endforeach; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Stats Summary -->
<div class="row g-2 mb-3 print-stats">
    <div class="col-6 col-md-3">
        <div class="card stat-card">
            <div class="card-body py-2 px-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="text-muted" style="font-size:0.7rem;">VOYAGEURS</div>
                        <h5 class="mb-0 fw-bold"><?= $totalVoyageurs ?></h5>
                    </div>
                    <div>
                        <span class="counter-badge bg-primary bg-opacity-10 text-primary"><?= $nbHommes ?>H</span>
                        <span class="counter-badge bg-info bg-opacity-10 text-info"><?= $nbFemmes ?>F</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card stat-card">
            <div class="card-body py-2 px-3">
                <div class="text-muted" style="font-size:0.7rem;">VISA</div>
                <div class="d-flex gap-2 align-items-center">
                    <span class="badge bg-success"><?= $nbVisaConfirme ?></span>
                    <span class="badge bg-warning text-dark"><?= $nbVisaAttente ?></span>
                    <small class="text-muted">| Vaccinés: <?= $nbVaccine ?></small>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card stat-card">
            <div class="card-body py-2 px-3">
                <div class="text-muted" style="font-size:0.7rem;">PAIEMENTS</div>
                <div class="d-flex gap-1">
                    <span class="badge bg-success"><?= $nbPaye ?> payés</span>
                    <span class="badge bg-warning text-dark"><?= $nbPartiel ?> partiels</span>
                    <span class="badge bg-danger"><?= $nbImpaye ?> impayés</span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card stat-card">
            <div class="card-body py-2 px-3">
                <div class="text-muted" style="font-size:0.7rem;">FINANCE</div>
                <div style="font-size:0.8rem;">
                    <span class="text-success fw-bold"><?= formatMoney($totalPaye) ?></span>
                    <span class="text-muted"> / <?= formatMoney($totalDu) ?></span>
                </div>
                <?php if ($totalRestant > 0): ?>
                <small class="text-danger">Reste: <?= formatMoney($totalRestant) ?></small>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Data Table -->
<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover table-bordered table-sm print-table" id="printTable">
            <thead>
                <tr>
                    <th class="no-print text-center" style="width:30px;">
                        <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)" title="Sélectionner tout">
                    </th>
                    <th style="width:30px;">#</th>
                    <?php foreach ($allColumns as $ck => $cinfo): ?>
                        <?php if (in_array($ck, $cols)): ?>
                        <th class="col-<?= $ck ?>"><?= $cinfo['label'] ?></th>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($results)): ?>
                <tr><td colspan="<?= count($cols) + 2 ?>" class="text-center text-muted py-4">
                    <i class="bi bi-inbox fs-3 d-block mb-2"></i>Aucun voyageur ne correspond aux critères sélectionnés
                </td></tr>
            <?php else: ?>
                <?php foreach ($results as $idx => $r): ?>
                <tr class="data-row">
                    <td class="no-print text-center"><input type="checkbox" class="row-check" value="<?= $r['inscription_id'] ?>"></td>
                    <td class="text-center"><?= $idx + 1 ?></td>
                    <?php if (in_array('num_dossier', $cols)): ?><td><strong><?= sanitize($r['num_dossier'] ?: '-') ?></strong></td><?php endif; ?>
                    <?php if (in_array('nom_complet', $cols)): ?><td><strong><?= sanitize($r['nom'].' '.$r['prenom']) ?></strong></td><?php endif; ?>
                    <?php if (in_array('sexe', $cols)): ?><td class="text-center"><?= $r['sexe'] ?: '-' ?></td><?php endif; ?>
                    <?php if (in_array('date_naissance', $cols)): ?><td><?= formatDate($r['date_naissance']) ?></td><?php endif; ?>
                    <?php if (in_array('nationalite', $cols)): ?><td><?= sanitize($r['nationalite'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('cin', $cols)): ?><td><?= sanitize($r['cin'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('passeport', $cols)): ?><td><?= sanitize($r['num_passeport'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('exp_passeport', $cols)): ?>
                        <td>
                            <?php
                            $exp = $r['date_expiration_passeport'];
                            $isExpiring = $exp && strtotime($exp) <= strtotime('+3 months');
                            ?>
                            <span class="<?= $isExpiring ? 'text-danger fw-bold' : '' ?>"><?= formatDate($exp) ?></span>
                            <?php if ($isExpiring): ?><i class="bi bi-exclamation-triangle-fill text-danger" title="Expire bientôt"></i><?php endif; ?>
                        </td>
                    <?php endif; ?>
                    <?php if (in_array('telephone', $cols)): ?><td><?= sanitize($r['telephone'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('telephone2', $cols)): ?><td><?= sanitize($r['telephone2'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('email', $cols)): ?><td><?= sanitize($r['email'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('adresse', $cols)): ?><td><?= sanitize($r['adresse'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('ville', $cols)): ?><td><?= sanitize($r['ville'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('contact_urgence', $cols)): ?><td><?= sanitize(($r['contact_urgence_nom'] ?: '-') . ($r['contact_urgence_tel'] ? ' ('.$r['contact_urgence_tel'].')' : '')) ?></td><?php endif; ?>
                    <?php if (in_array('programme', $cols)): ?>
                        <td>
                            <span class="badge bg-<?= $r['programme_type']=='hajj'?'success':($r['programme_type']=='omra'?'info':'primary') ?> bg-opacity-75" style="font-size:0.7rem;"><?= ucfirst($r['programme_type']) ?></span>
                            <small class="d-block"><?= sanitize($r['programme_nom']) ?></small>
                        </td>
                    <?php endif; ?>
                    <?php if (in_array('destination', $cols)): ?><td><?= sanitize($r['destination'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('formule', $cols)): ?><td><?= ucfirst($r['formule']) ?></td><?php endif; ?>
                    <?php if (in_array('groupe', $cols)): ?><td><?= sanitize($r['groupe_nom'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('hotel', $cols)): ?><td><?= sanitize($r['hotel_nom'] ? $r['hotel_nom'].' ('.$r['hotel_ville'].')' : '-') ?></td><?php endif; ?>
                    <?php if (in_array('chambre_info', $cols)): ?><td><?= sanitize($r['chambre_numero'] ?: '-') ?></td><?php endif; ?>
                    <?php if (in_array('vol_aller', $cols)): ?><td><?= $r['vol_aller_compagnie'] ? sanitize($r['vol_aller_compagnie'].' '.$r['vol_aller_num']) : '-' ?></td><?php endif; ?>
                    <?php if (in_array('vol_retour', $cols)): ?><td><?= $r['vol_retour_compagnie'] ? sanitize($r['vol_retour_compagnie'].' '.$r['vol_retour_num']) : '-' ?></td><?php endif; ?>
                    <?php if (in_array('statut_visa', $cols)): ?><td><?= getStatusBadge($r['statut_visa']) ?></td><?php endif; ?>
                    <?php if (in_array('vaccination', $cols)): ?><td class="text-center"><?= $r['vaccination'] === 'oui' ? '<i class="bi bi-check-circle-fill text-success"></i>' : '<i class="bi bi-x-circle text-danger"></i>' ?></td><?php endif; ?>
                    <?php if (in_array('paiement', $cols)): ?><td><?= getStatusBadge($r['statut_paiement']) ?></td><?php endif; ?>
                    <?php if (in_array('montant_paye', $cols)): ?><td class="text-end text-success"><?= formatMoney($r['montant_paye']) ?></td><?php endif; ?>
                    <?php if (in_array('prix_total', $cols)): ?><td class="text-end"><?= formatMoney($r['prix_total']) ?></td><?php endif; ?>
                    <?php if (in_array('reste', $cols)): ?>
                        <td class="text-end <?= ($r['prix_total'] - $r['montant_paye']) > 0 ? 'text-danger fw-bold' : 'text-success' ?>">
                            <?= formatMoney($r['prix_total'] - $r['montant_paye']) ?>
                        </td>
                    <?php endif; ?>
                    <?php if (in_array('statut', $cols)): ?><td><?= getStatusBadge($r['inscription_status']) ?></td><?php endif; ?>
                    <?php if (in_array('date_inscription', $cols)): ?><td><?= formatDate($r['date_inscription']) ?></td><?php endif; ?>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
            <?php if (!empty($results) && (in_array('montant_paye', $cols) || in_array('prix_total', $cols) || in_array('reste', $cols))): ?>
            <tfoot>
                <tr class="fw-bold table-light">
                    <td class="no-print"></td>
                    <td></td>
                    <?php foreach ($allColumns as $ck => $cinfo): ?>
                        <?php if (!in_array($ck, $cols)) continue; ?>
                        <?php if ($ck === 'montant_paye'): ?>
                            <td class="text-end text-success"><?= formatMoney($totalPaye) ?></td>
                        <?php elseif ($ck === 'prix_total'): ?>
                            <td class="text-end"><?= formatMoney($totalDu) ?></td>
                        <?php elseif ($ck === 'reste'): ?>
                            <td class="text-end text-danger"><?= formatMoney($totalRestant) ?></td>
                        <?php elseif ($ck === 'nom_complet'): ?>
                            <td>Total: <?= $totalVoyageurs ?> voyageur(s)</td>
                        <?php else: ?>
                            <td></td>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </tr>
            </tfoot>
            <?php endif; ?>
        </table>
    </div>
</div>

<!-- Print Footer -->
<div class="print-footer">
    <?= sanitize($agency['agence_nom'] ?? 'UpTours') ?> - <?= sanitize($agency['agence_telephone'] ?? '') ?> - <?= sanitize($agency['agence_email'] ?? '') ?> | Imprimé le <?= date('d/m/Y à H:i') ?> | Page <span class="pagenum"></span>
</div>

<?php
$extraScripts = "
<script>
// Toggle columns panel
function toggleColumns() {
    document.getElementById('columnsPanel').classList.toggle('show');
}

// Select/deselect all columns
function selectAllCols(state) {
    document.querySelectorAll('.col-toggle').forEach(cb => cb.checked = state);
    updateColumns();
}

// Update columns: rebuild form hidden inputs and submit
function updateColumns() {
    var checked = [];
    document.querySelectorAll('.col-toggle:checked').forEach(cb => checked.push(cb.value));
    
    var container = document.getElementById('hiddenCols');
    container.innerHTML = '';
    checked.forEach(function(col) {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'cols[]';
        input.value = col;
        container.appendChild(input);
    });
    
    document.getElementById('filterForm').submit();
}

// Inject hidden cols on form submit
document.getElementById('filterForm').addEventListener('submit', function() {
    var container = document.getElementById('hiddenCols');
    if (container.children.length === 0) {
        document.querySelectorAll('.col-toggle:checked').forEach(function(cb) {
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'cols[]';
            input.value = cb.value;
            container.appendChild(input);
        });
    }
});

// Select all rows
function toggleSelectAll(master) {
    document.querySelectorAll('.row-check').forEach(cb => cb.checked = master.checked);
}

// CSV Export
function exportCSV() {
    var table = document.getElementById('printTable');
    var rows = [];
    
    // Header
    var headerCells = table.querySelectorAll('thead th:not(.no-print)');
    var headers = [];
    headerCells.forEach(function(th) { headers.push('\"' + th.textContent.trim().replace(/\"/g, '\"\"') + '\"'); });
    rows.push(headers.join(';'));
    
    // Data rows
    table.querySelectorAll('tbody tr.data-row').forEach(function(tr) {
        var cells = [];
        tr.querySelectorAll('td:not(.no-print)').forEach(function(td) {
            cells.push('\"' + td.textContent.trim().replace(/\"/g, '\"\"') + '\"');
        });
        rows.push(cells.join(';'));
    });
    
    // Footer
    var footerRow = table.querySelector('tfoot tr');
    if (footerRow) {
        var fCells = [];
        footerRow.querySelectorAll('td:not(.no-print)').forEach(function(td) {
            fCells.push('\"' + td.textContent.trim().replace(/\"/g, '\"\"') + '\"');
        });
        rows.push(fCells.join(';'));
    }
    
    var csvContent = '\\uFEFF' + rows.join('\\n');
    var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    var link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'liste_voyageurs_' + new Date().toISOString().slice(0,10) + '.csv';
    link.click();
}
</script>";

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