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

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

if ($action === 'delete' && $id) {
    $db->prepare("UPDATE vols SET status='inactif' WHERE id=?")->execute([$id]);
    flash('success', 'Vol supprimé.'); redirect('/vols.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $editId = intval($_POST['id'] ?? 0);
    $data = [
        $_POST['compagnie'] ?? '', $_POST['numero_vol'] ?? '',
        $_POST['aeroport_depart'] ?? '', $_POST['aeroport_arrivee'] ?? '',
        $_POST['date_depart'] ?? '', $_POST['heure_depart'] ?? '',
        $_POST['date_arrivee'] ?? '', $_POST['heure_arrivee'] ?? '',
        intval($_POST['places_total'] ?? 0), floatval($_POST['prix'] ?? 0),
        intval($_POST['programme_id'] ?? 0) ?: null, $_POST['notes'] ?? '',
    ];
    if ($editId) {
        $data[] = $editId;
        $db->prepare("UPDATE vols SET compagnie=?,numero_vol=?,aeroport_depart=?,aeroport_arrivee=?,date_depart=?,heure_depart=?,date_arrivee=?,heure_arrivee=?,places_total=?,prix=?,programme_id=?,notes=?,updated_at=datetime('now') WHERE id=?")->execute($data);
        flash('success', 'Vol modifié.');
    } else {
        $db->prepare("INSERT INTO vols (compagnie,numero_vol,aeroport_depart,aeroport_arrivee,date_depart,heure_depart,date_arrivee,heure_arrivee,places_total,prix,programme_id,notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")->execute($data);
        flash('success', 'Vol ajouté.');
    }
    redirect('/vols.php');
}

// Passenger list print
if ($action === 'passagers' && $id) {
    $vol = $db->prepare("SELECT v.*, p.nom as programme_nom FROM vols v LEFT JOIN programmes p ON v.programme_id=p.id WHERE v.id=?");
    $vol->execute([$id]);
    $vol = $vol->fetch();
    if (!$vol) { flash('error','Vol introuvable.'); redirect('/vols.php'); }
    
    $passagers = $db->query("
        SELECT vy.nom, vy.prenom, vy.cin, vy.num_passeport, vy.telephone, vy.sexe, i.num_dossier, i.formule
        FROM inscriptions i 
        JOIN voyageurs vy ON i.voyageur_id=vy.id 
        WHERE (i.vol_aller_id={$id} OR i.vol_retour_id={$id}) AND i.status != 'annule'
        ORDER BY vy.nom, vy.prenom
    ")->fetchAll();
    $ag = getAgencyInfo();
?>
<!DOCTYPE html><html lang="fr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Liste Passagers - <?= sanitize($vol['numero_vol']) ?></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>@media print { .no-print { display:none; } body { font-size: 12px; } }</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 ?>/vols.php" class="btn btn-outline-secondary ms-2">Retour</a>
</div>
<div class="container py-3">
    <div class="text-center mb-3">
        <?php if (!empty($ag['agence_logo'])): ?>
            <img src="<?= APP_URL ?>/uploads/<?= sanitize($ag['agence_logo']) ?>" alt="Logo" style="max-height:50px;" class="mb-1"><br>
        <?php endif; ?>
        <h4><?= sanitize($ag['agence_nom'] ?? 'UpTours') ?> – Liste des Passagers</h4>
        <p class="small text-muted mb-1"><?= sanitize($ag['agence_adresse'] ?? '') ?> – <?= sanitize($ag['agence_ville'] ?? '') ?> | Tél: <?= sanitize($ag['agence_telephone'] ?? '') ?></p>
        <p class="mb-0"><strong><?= sanitize($vol['compagnie'].' - '.$vol['numero_vol']) ?></strong></p>
        <p><?= sanitize($vol['aeroport_depart'].' → '.$vol['aeroport_arrivee']) ?> | <?= formatDate($vol['date_depart']) ?> <?= $vol['heure_depart'] ?></p>
    </div>
    <table class="table table-bordered table-sm">
        <thead class="table-dark"><tr><th>#</th><th>Nom & Prénom</th><th>Sexe</th><th>CIN</th><th>Passeport</th><th>Dossier</th><th>Formule</th><th>Téléphone</th></tr></thead>
        <tbody>
        <?php foreach ($passagers as $i => $p): ?>
            <tr><td><?= $i+1 ?></td><td><strong><?= sanitize($p['nom'].' '.$p['prenom']) ?></strong></td><td><?= $p['sexe'] ?></td><td><?= sanitize($p['cin'] ?: '-') ?></td><td><?= sanitize($p['num_passeport'] ?: '-') ?></td><td><?= sanitize($p['num_dossier']) ?></td><td><?= ucfirst($p['formule']) ?></td><td><?= sanitize($p['telephone'] ?: '-') ?></td></tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <p class="text-muted small">Total: <?= count($passagers) ?> passager(s) | <?= sanitize($ag['agence_nom'] ?? 'UpTours') ?> | Généré le <?= date('d/m/Y H:i') ?></p>
</div></body></html>
<?php exit; }

// Form
if ($action === 'add' || $action === 'edit') {
    $vol = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM vols WHERE id=?"); $stmt->execute([$id]); $vol = $stmt->fetch();
    }
    $programmes = $db->query("SELECT id, nom, type FROM programmes WHERE status='en_cours' ORDER BY date_depart")->fetchAll();
?>
    <div class="d-flex justify-content-between mb-4">
        <a href="<?= APP_URL ?>/vols.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-airplane me-2"></i><?= $vol ? 'Modifier le vol' : 'Nouveau vol' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $vol['id'] ?? '' ?>">
                <div class="row g-3">
                    <div class="col-md-4"><label class="form-label">Compagnie *</label><input type="text" name="compagnie" class="form-control" value="<?= sanitize($vol['compagnie'] ?? '') ?>" required></div>
                    <div class="col-md-4"><label class="form-label">N° Vol</label><input type="text" name="numero_vol" class="form-control" value="<?= sanitize($vol['numero_vol'] ?? '') ?>"></div>
                    <div class="col-md-4">
                        <label class="form-label">Programme</label>
                        <select name="programme_id" class="form-select select2">
                            <option value="">-- Aucun --</option>
                            <?php foreach ($programmes as $p): ?>
                                <option value="<?= $p['id'] ?>" <?= ($vol['programme_id'] ?? '')==$p['id']?'selected':'' ?>><?= sanitize($p['nom']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6"><label class="form-label">Aéroport départ</label><input type="text" name="aeroport_depart" class="form-control" value="<?= sanitize($vol['aeroport_depart'] ?? '') ?>"></div>
                    <div class="col-md-6"><label class="form-label">Aéroport arrivée</label><input type="text" name="aeroport_arrivee" class="form-control" value="<?= sanitize($vol['aeroport_arrivee'] ?? '') ?>"></div>
                    <div class="col-md-3"><label class="form-label">Date départ</label><input type="date" name="date_depart" class="form-control" value="<?= $vol['date_depart'] ?? '' ?>"></div>
                    <div class="col-md-3"><label class="form-label">Heure départ</label><input type="time" name="heure_depart" class="form-control" value="<?= $vol['heure_depart'] ?? '' ?>"></div>
                    <div class="col-md-3"><label class="form-label">Date arrivée</label><input type="date" name="date_arrivee" class="form-control" value="<?= $vol['date_arrivee'] ?? '' ?>"></div>
                    <div class="col-md-3"><label class="form-label">Heure arrivée</label><input type="time" name="heure_arrivee" class="form-control" value="<?= $vol['heure_arrivee'] ?? '' ?>"></div>
                    <div class="col-md-4"><label class="form-label">Places total</label><input type="number" name="places_total" class="form-control" value="<?= $vol['places_total'] ?? '' ?>"></div>
                    <div class="col-md-4"><label class="form-label">Prix (MAD)</label><input type="number" step="0.01" name="prix" class="form-control" value="<?= $vol['prix'] ?? '0' ?>"></div>
                    <div class="col-md-4"><label class="form-label">Notes</label><input type="text" name="notes" class="form-control" value="<?= sanitize($vol['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 ?>/vols.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php require_once __DIR__ . '/includes/footer.php'; exit; }

// List
$vols = $db->query("SELECT v.*, p.nom as programme_nom, (SELECT COUNT(*) FROM inscriptions i WHERE i.vol_aller_id=v.id OR i.vol_retour_id=v.id) as nb_passagers FROM vols v LEFT JOIN programmes p ON v.programme_id=p.id WHERE v.status='actif' ORDER BY v.date_depart DESC")->fetchAll();
?>

<div class="d-flex justify-content-between mb-4">
    <h6 class="text-muted mb-0"><?= count($vols) ?> vol(s)</h6>
    <a href="<?= APP_URL ?>/vols.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouveau vol</a>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr><th>Compagnie</th><th>N° Vol</th><th>Départ</th><th>Arrivée</th><th>Date & Heure</th><th>Places</th><th>Prix</th><th>Programme</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($vols as $v): ?>
                <tr>
                    <td><strong><?= sanitize($v['compagnie']) ?></strong></td>
                    <td><?= sanitize($v['numero_vol']) ?></td>
                    <td><?= sanitize($v['aeroport_depart']) ?></td>
                    <td><?= sanitize($v['aeroport_arrivee']) ?></td>
                    <td><?= formatDate($v['date_depart']) ?> <?= $v['heure_depart'] ?></td>
                    <td><?= $v['nb_passagers'] ?>/<?= $v['places_total'] ?></td>
                    <td><?= formatMoney($v['prix']) ?></td>
                    <td><small><?= sanitize($v['programme_nom'] ?: '-') ?></small></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/vols.php?action=passagers&id=<?= $v['id'] ?>" class="btn btn-outline-info" title="Liste passagers" target="_blank"><i class="bi bi-list-check"></i></a>
                            <a href="<?= APP_URL ?>/vols.php?action=edit&id=<?= $v['id'] ?>" class="btn btn-outline-warning"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/vols.php?action=delete&id=<?= $v['id'] ?>" class="btn btn-outline-danger" onclick="return confirmDelete()"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($vols)): ?><tr><td colspan="9" class="text-center text-muted py-4">Aucun vol</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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