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

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

// Delete
if ($action === 'delete' && $id) {
    // Check if programme exists
    $programme = $db->prepare("SELECT * FROM programmes WHERE id=?");
    $programme->execute([$id]);
    $programme = $programme->fetch();
    
    if (!$programme) {
        flash('error', 'Programme introuvable.');
        redirect('/programmes.php');
    }
    
    try {
        // Début de la transaction pour s'assurer que tout ou rien n'est supprimé
        $db->beginTransaction();

        // 1. Gérer les dépendances sans suppression en cascade forte (Groupes, Vols)
        // Mettre à NULL le programme_id dans les groupes et vols associés
        $db->prepare("UPDATE groupes SET programme_id = NULL WHERE programme_id = ?")->execute([$id]);
        $db->prepare("UPDATE vols SET programme_id = NULL WHERE programme_id = ?")->execute([$id]);

        // 2. Gérer les dépendances fortes (Inscriptions et leurs Paiements)
        $inscriptions = $db->prepare("SELECT id FROM inscriptions WHERE programme_id=?");
        $inscriptions->execute([$id]);
        $inscriptionIds = $inscriptions->fetchAll(PDO::FETCH_COLUMN);
        
        if (!empty($inscriptionIds)) {
            $placeholders = implode(',', array_fill(0, count($inscriptionIds), '?'));
            // Supprimer d'abord les paiements liés à ces inscriptions
            $db->prepare("DELETE FROM paiements WHERE inscription_id IN ($placeholders)")->execute($inscriptionIds);
        }
        
        // Supprimer toutes les inscriptions pour ce programme
        $db->prepare("DELETE FROM inscriptions WHERE programme_id=?")->execute([$id]);
        
        // 3. Enfin, supprimer le programme
        $db->prepare("DELETE FROM programmes WHERE id=?")->execute([$id]);
        
        $db->commit();
        
        logAction($_SESSION['user_id'], 'programme_delete', "Programme #$id supprimé avec toutes ses données");
        flash('success', 'Programme et toutes ses données supprimés avec succès.');
    } catch (Exception $e) {
        $db->rollBack();
        flash('error', 'Erreur lors de la suppression: ' . $e->getMessage());
    }
    
    redirect('/programmes.php');
}

// Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        $_POST['nom'] ?? '',
        $_POST['type'] ?? 'hajj',
        $_POST['destination'] ?? '',
        $_POST['date_depart'] ?? '',
        $_POST['date_retour'] ?? '',
        intval($_POST['duree'] ?? 0),
        floatval($_POST['prix_double'] ?? 0),
        floatval($_POST['prix_triple'] ?? 0),
        floatval($_POST['prix_quadruple'] ?? 0),
        floatval($_POST['prix_quintuple'] ?? 0),
        intval($_POST['places_max'] ?? 0),
        $_POST['description'] ?? '',
        $_POST['status'] ?? 'en_cours',
    ];

    $editId = intval($_POST['id'] ?? 0);
    if ($editId) {
        $data[] = $editId;
        $db->prepare("UPDATE programmes SET nom=?,type=?,destination=?,date_depart=?,date_retour=?,duree=?,prix_double=?,prix_triple=?,prix_quadruple=?,prix_quintuple=?,places_max=?,description=?,status=?,updated_at=datetime('now') WHERE id=?")->execute($data);
        logAction($_SESSION['user_id'], 'programme_update', "Programme #$editId modifié");
        flash('success', 'Programme modifié avec succès.');
    } else {
        $ref = generateReference(strtoupper(substr($_POST['type'] ?? 'PRG', 0, 3)));
        array_unshift($data, $ref);
        $db->prepare("INSERT INTO programmes (reference,nom,type,destination,date_depart,date_retour,duree,prix_double,prix_triple,prix_quadruple,prix_quintuple,places_max,description,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")->execute($data);
        logAction($_SESSION['user_id'], 'programme_create', "Programme créé: $ref");
        flash('success', 'Programme créé avec succès.');
    }
    redirect('/programmes.php');
}

// View details
if ($action === 'view' && $id) {
    $stmt = $db->prepare("SELECT * FROM programmes WHERE id=?");
    $stmt->execute([$id]);
    $prog = $stmt->fetch();
    if (!$prog) { flash('error','Programme introuvable.'); redirect('/programmes.php'); }
    
    $inscriptions = $db->prepare("SELECT i.*, v.nom, v.prenom, v.telephone FROM inscriptions i JOIN voyageurs v ON i.voyageur_id=v.id WHERE i.programme_id=? ORDER BY i.created_at DESC");
    $inscriptions->execute([$id]);
    $inscriptions = $inscriptions->fetchAll();
    
    $vols = $db->prepare("SELECT * FROM vols WHERE programme_id=? ORDER BY date_depart");
    $vols->execute([$id]);
    $vols = $vols->fetchAll();
    
    $depenses = $db->prepare("SELECT * FROM depenses WHERE programme_id=? ORDER BY date_depense DESC");
    $depenses->execute([$id]);
    $depenses = $depenses->fetchAll();
    
    $totalRevenu = $db->prepare("SELECT COALESCE(SUM(pa.montant),0) FROM paiements pa JOIN inscriptions i ON pa.inscription_id=i.id WHERE i.programme_id=?");
    $totalRevenu->execute([$id]);
    $totalRevenu = $totalRevenu->fetchColumn();
    
    $totalDepenses = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM depenses WHERE programme_id=?");
    $totalDepenses->execute([$id]);
    $totalDepensesVal = $totalDepenses->fetchColumn();
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/programmes.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour</a>
        <div class="d-flex gap-2">
            <a href="<?= APP_URL ?>/programmes.php?action=edit&id=<?= $prog['id'] ?>" class="btn btn-warning"><i class="bi bi-pencil me-1"></i>Modifier</a>
            <a href="<?= APP_URL ?>/inscriptions.php?action=add&programme_id=<?= $prog['id'] ?>" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Inscrire</a>
        </div>
    </div>
    
    <div class="row g-3 mb-4">
        <div class="col-lg-8">
            <div class="card table-card">
                <div class="card-header d-flex justify-content-between">
                    <span><i class="bi bi-info-circle me-2"></i>Détails du programme</span>
                    <?= getStatusBadge($prog['status']) ?>
                </div>
                <div class="card-body">
                    <h4 class="mb-2"><?= sanitize($prog['nom']) ?></h4>
                    <span class="badge bg-<?= $prog['type']=='hajj'?'success':($prog['type']=='omra'?'info':'primary') ?> mb-3"><?= ucfirst($prog['type']) ?></span>
                    <div class="row g-3">
                        <div class="col-md-6"><small class="text-muted">Référence</small><br><strong><?= sanitize($prog['reference']) ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Destination</small><br><strong><?= sanitize($prog['destination']) ?></strong></div>
                        <div class="col-md-4"><small class="text-muted">Départ</small><br><strong><?= formatDate($prog['date_depart']) ?></strong></div>
                        <div class="col-md-4"><small class="text-muted">Retour</small><br><strong><?= formatDate($prog['date_retour']) ?></strong></div>
                        <div class="col-md-4"><small class="text-muted">Durée</small><br><strong><?= $prog['duree'] ?> jours</strong></div>
                        <div class="col-md-3"><small class="text-muted">Prix Double</small><br><strong class="text-success"><?= formatMoney($prog['prix_double']) ?></strong></div>
                        <div class="col-md-3"><small class="text-muted">Prix Triple</small><br><strong class="text-primary"><?= formatMoney($prog['prix_triple']) ?></strong></div>
                        <div class="col-md-3"><small class="text-muted">Prix Quadruple</small><br><strong class="text-warning"><?= formatMoney($prog['prix_quadruple']) ?></strong></div>
                        <div class="col-md-3"><small class="text-muted">Prix Quintuple</small><br><strong class="text-info"><?= formatMoney($prog['prix_quintuple']) ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Places</small><br><strong><?= $prog['places_reservees'] ?> / <?= $prog['places_max'] ?></strong>
                            <div class="progress mt-1" style="height:6px;"><div class="progress-bar bg-success" style="width:<?= $prog['places_max']>0?round($prog['places_reservees']/$prog['places_max']*100):0 ?>%"></div></div>
                        </div>
                        <?php if ($prog['description']): ?>
                        <div class="col-12"><small class="text-muted">Description</small><br><?= nl2br(sanitize($prog['description'])) ?></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card stat-card border-start border-success border-4 mb-3">
                <div class="card-body"><div class="text-muted small">Revenus</div><h4 class="text-success mb-0"><?= formatMoney($totalRevenu) ?></h4></div>
            </div>
            <div class="card stat-card border-start border-danger border-4 mb-3">
                <div class="card-body"><div class="text-muted small">Dépenses</div><h4 class="text-danger mb-0"><?= formatMoney($totalDepensesVal) ?></h4></div>
            </div>
            <div class="card stat-card border-start border-primary border-4 mb-3">
                <div class="card-body"><div class="text-muted small">Bénéfice net</div><h4 class="text-primary mb-0"><?= formatMoney($totalRevenu - $totalDepensesVal) ?></h4></div>
            </div>
            <div class="card stat-card">
                <div class="card-body text-center">
                    <h2 class="mb-0"><?= count($inscriptions) ?></h2>
                    <small class="text-muted">Inscrits</small>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Participants -->
    <div class="card table-card mb-3">
        <div class="card-header"><i class="bi bi-people me-2"></i>Participants (<?= count($inscriptions) ?>)</div>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead><tr><th>Dossier</th><th>Voyageur</th><th>Téléphone</th><th>Chambre</th><th>Visa</th><th>Paiement</th><th>Actions</th></tr></thead>
                <tbody>
                <?php foreach ($inscriptions as $ins): ?>
                    <tr>
                        <td><strong><?= sanitize($ins['num_dossier'] ?: '-') ?></strong></td>
                        <td><a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $ins['voyageur_id'] ?>"><?= sanitize($ins['prenom'].' '.$ins['nom']) ?></a></td>
                        <td><?= sanitize($ins['telephone'] ?: '-') ?></td>
                        <td><?= ucfirst($ins['formule']) ?></td>
                        <td><?= getStatusBadge($ins['statut_visa']) ?></td>
                        <td><?= getStatusBadge($ins['statut_paiement']) ?><br><small><?= formatMoney($ins['montant_paye']) ?>/<?= formatMoney($ins['prix_total']) ?></small></td>
                        <td><a href="<?= APP_URL ?>/inscriptions.php?action=edit&id=<?= $ins['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($inscriptions)): ?><tr><td colspan="7" class="text-center text-muted py-3">Aucun participant</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Vols -->
    <div class="card table-card mb-3">
        <div class="card-header"><i class="bi bi-airplane me-2"></i>Vols associés</div>
        <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</th><th>Places</th></tr></thead>
                <tbody>
                <?php foreach ($vols as $vol): ?>
                    <tr>
                        <td><strong><?= sanitize($vol['compagnie']) ?></strong></td>
                        <td><?= sanitize($vol['numero_vol']) ?></td>
                        <td><?= sanitize($vol['aeroport_depart']) ?></td>
                        <td><?= sanitize($vol['aeroport_arrivee']) ?></td>
                        <td><?= formatDate($vol['date_depart']) ?> <?= $vol['heure_depart'] ?></td>
                        <td><?= $vol['places_reservees'] ?>/<?= $vol['places_total'] ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($vols)): ?><tr><td colspan="6" class="text-center text-muted py-3">Aucun vol</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// Form
if ($action === 'add' || $action === 'edit') {
    $prog = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM programmes WHERE id=?");
        $stmt->execute([$id]);
        $prog = $stmt->fetch();
        if (!$prog) { flash('error','Programme introuvable.'); redirect('/programmes.php'); }
    }
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/programmes.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-calendar-plus me-2"></i><?= $prog ? 'Modifier le programme' : 'Nouveau programme' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $prog['id'] ?? '' ?>">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Nom du programme *</label>
                        <input type="text" name="nom" class="form-control" value="<?= sanitize($prog['nom'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Type *</label>
                        <select name="type" class="form-select" required>
                            <option value="hajj" <?= ($prog['type']??'')=='hajj'?'selected':'' ?>>Hajj</option>
                            <option value="omra" <?= ($prog['type']??'')=='omra'?'selected':'' ?>>Omra</option>
                            <option value="voyage" <?= ($prog['type']??'')=='voyage'?'selected':'' ?>>Voyage</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Statut</label>
                        <select name="status" class="form-select">
                            <option value="en_cours" <?= ($prog['status']??'')=='en_cours'?'selected':'' ?>>En cours</option>
                            <option value="termine" <?= ($prog['status']??'')=='termine'?'selected':'' ?>>Terminé</option>
                            <option value="annule" <?= ($prog['status']??'')=='annule'?'selected':'' ?>>Annulé</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Destination</label>
                        <input type="text" name="destination" class="form-control" value="<?= sanitize($prog['destination'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Date départ</label>
                        <input type="date" name="date_depart" class="form-control" value="<?= $prog['date_depart'] ?? '' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Date retour</label>
                        <input type="date" name="date_retour" class="form-control" value="<?= $prog['date_retour'] ?? '' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Durée (jours)</label>
                        <input type="number" name="duree" class="form-control" value="<?= $prog['duree'] ?? '' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Places max</label>
                        <input type="number" name="places_max" class="form-control" value="<?= $prog['places_max'] ?? '' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Prix Double (MAD)</label>
                        <input type="number" step="0.01" name="prix_double" class="form-control" value="<?= $prog['prix_double'] ?? '0' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Prix Triple (MAD)</label>
                        <input type="number" step="0.01" name="prix_triple" class="form-control" value="<?= $prog['prix_triple'] ?? '0' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Prix Quadruple (MAD)</label>
                        <input type="number" step="0.01" name="prix_quadruple" class="form-control" value="<?= $prog['prix_quadruple'] ?? '0' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Prix Quintuple (MAD)</label>
                        <input type="number" step="0.01" name="prix_quintuple" class="form-control" value="<?= $prog['prix_quintuple'] ?? '0' ?>">
                    </div>
                    <div class="col-12">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3"><?= sanitize($prog['description'] ?? '') ?></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 ?>/programmes.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

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

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (nom LIKE ? OR reference LIKE ? OR destination LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s]; }
if ($typeFilter) { $where .= " AND type=?"; $params[] = $typeFilter; }

$total = $db->prepare("SELECT COUNT(*) FROM programmes $where");
$total->execute($params);
$pagination = paginate($total->fetchColumn(), 15, $page);

$stmt = $db->prepare("SELECT * FROM programmes $where ORDER BY date_depart DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$programmes = $stmt->fetchAll();
?>

<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="type" class="form-select" style="width:150px;">
            <option value="">Tous types</option>
            <option value="hajj" <?= $typeFilter=='hajj'?'selected':'' ?>>Hajj</option>
            <option value="omra" <?= $typeFilter=='omra'?'selected':'' ?>>Omra</option>
            <option value="voyage" <?= $typeFilter=='voyage'?'selected':'' ?>>Voyage</option>
        </select>
        <button class="btn btn-outline-primary">Filtrer</button>
    </form>
    <a href="<?= APP_URL ?>/programmes.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouveau programme</a>
</div>

<div class="row g-3">
<?php foreach ($programmes as $p): ?>
    <div class="col-md-6 col-lg-4">
        <div class="card stat-card h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <span class="badge bg-<?= $p['type']=='hajj'?'success':($p['type']=='omra'?'info':'primary') ?>"><?= ucfirst($p['type']) ?></span>
                    <?= getStatusBadge($p['status']) ?>
                </div>
                <h6 class="fw-bold mb-1"><?= sanitize($p['nom']) ?></h6>
                <p class="text-muted small mb-2"><i class="bi bi-geo-alt me-1"></i><?= sanitize($p['destination']) ?></p>
                <div class="row g-1 mb-2 small">
                    <div class="col-6"><i class="bi bi-calendar me-1"></i><?= formatDate($p['date_depart']) ?></div>
                    <div class="col-6"><i class="bi bi-clock me-1"></i><?= $p['duree'] ?> jours</div>
                </div>
                <div class="d-flex justify-content-between align-items-center small mb-2">
                    <span>Places: <strong><?= $p['places_reservees'] ?>/<?= $p['places_max'] ?></strong></span>
                    <span class="fw-bold text-success">Dès <?= formatMoney($p['prix_quintuple']) ?></span>
                </div>
                <div class="progress mb-3" style="height:4px;"><div class="progress-bar bg-success" style="width:<?= $p['places_max']>0?round($p['places_reservees']/$p['places_max']*100):0 ?>%"></div></div>
                <div class="d-flex gap-1">
                    <a href="<?= APP_URL ?>/programmes.php?action=view&id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-primary flex-fill"><i class="bi bi-eye me-1"></i>Détails</a>
                    <a href="<?= APP_URL ?>/programmes.php?action=edit&id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-warning"><i class="bi bi-pencil"></i></a>
                    <a href="<?= APP_URL ?>/programmes.php?action=delete&id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-danger" title="Supprimer" onclick="return confirmDelete('Supprimer ce programme et toutes ses données (inscriptions et paiements) ?')"><i class="bi bi-trash"></i></a>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>
<?php if (empty($programmes)): ?>
    <div class="col-12"><div class="text-center text-muted py-5">Aucun programme trouvé</div></div>
<?php endif; ?>
</div>
<div class="mt-4">
    <?= renderPagination($pagination, APP_URL.'/programmes.php?search='.urlencode($search).'&type='.urlencode($typeFilter)) ?>
</div>

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