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

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

// Delete
if ($action === 'delete' && $id) {
    // Check if inscription exists
    $inscription = $db->prepare("SELECT * FROM inscriptions WHERE id=?");
    $inscription->execute([$id]);
    $inscription = $inscription->fetch();
    
    if (!$inscription) {
        flash('error', 'Inscription introuvable.');
        redirect('/inscriptions.php');
    }
    
    // Delete associated payments first
    $db->prepare("DELETE FROM paiements WHERE inscription_id=?")->execute([$id]);
    
    // Delete the inscription
    $db->prepare("DELETE FROM inscriptions WHERE id=?")->execute([$id]);
    
    logAction($_SESSION['user_id'], 'inscription_delete', "Inscription #$id supprimée");
    flash('success', 'Inscription supprimée avec succès.');
    redirect('/inscriptions.php');
}

// Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $editId = intval($_POST['id'] ?? 0);
    $voyageurId = intval($_POST['voyageur_id'] ?? 0);
    $programmeId = intval($_POST['programme_id'] ?? 0);
    $formule = $_POST['formule'] ?? 'double';
    
    // Get price based on formule (room type)
    $prog = $db->prepare("SELECT * FROM programmes WHERE id=?");
    $prog->execute([$programmeId]);
    $prog = $prog->fetch();
    
    $prix = $prog['prix_double'];
    if ($formule === 'triple') $prix = $prog['prix_triple'];
    if ($formule === 'quadruple') $prix = $prog['prix_quadruple'];
    if ($formule === 'quintuple') $prix = $prog['prix_quintuple'];
    
    $data = [
        $voyageurId,
        $programmeId,
        intval($_POST['groupe_id'] ?? 0) ?: null,
        $formule,
        $_POST['num_dossier'] ?? '',
        $_POST['statut_visa'] ?? 'en_attente',
        $_POST['vaccination'] ?? 'non',
        intval($_POST['hotel_id'] ?? 0) ?: null,
        $_POST['chambre_type'] ?? '',
        $_POST['chambre_numero'] ?? '',
        intval($_POST['vol_aller_id'] ?? 0) ?: null,
        intval($_POST['vol_retour_id'] ?? 0) ?: null,
        floatval($_POST['prix_total'] ?? $prix),
        $_POST['notes'] ?? '',
        $_POST['status'] ?? 'en_cours',
    ];

    if ($editId) {
        $data[] = $editId;
        $db->prepare("UPDATE inscriptions SET voyageur_id=?,programme_id=?,groupe_id=?,formule=?,num_dossier=?,statut_visa=?,vaccination=?,hotel_id=?,chambre_type=?,chambre_numero=?,vol_aller_id=?,vol_retour_id=?,prix_total=?,notes=?,status=?,updated_at=datetime('now') WHERE id=?")->execute($data);
        // Update payment status
        $montantPaye = $db->prepare("SELECT COALESCE(SUM(montant),0) FROM paiements WHERE inscription_id=?");
        $montantPaye->execute([$editId]);
        $mp = $montantPaye->fetchColumn();
        $prixTotal = floatval($_POST['prix_total'] ?? $prix);
        $statutPaiement = $mp >= $prixTotal ? 'paye' : ($mp > 0 ? 'partiel' : 'impaye');
        $db->prepare("UPDATE inscriptions SET montant_paye=?, statut_paiement=? WHERE id=?")->execute([$mp, $statutPaiement, $editId]);
        
        flash('success', 'Inscription modifiée.');
    } else {
        $numDossier = $_POST['num_dossier'] ?: generateReference(strtoupper(substr($prog['type'],0,3)).'-D');
        $data[4] = $numDossier;
        $db->prepare("INSERT INTO inscriptions (voyageur_id,programme_id,groupe_id,formule,num_dossier,statut_visa,vaccination,hotel_id,chambre_type,chambre_numero,vol_aller_id,vol_retour_id,prix_total,notes,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")->execute($data);
        // Update places count
        $db->prepare("UPDATE programmes SET places_reservees = places_reservees + 1 WHERE id=?")->execute([$programmeId]);
        flash('success', 'Inscription créée avec succès.');
    }
    redirect('/inscriptions.php');
}

// Form
if ($action === 'add' || $action === 'edit') {
    $inscription = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM inscriptions WHERE id=?");
        $stmt->execute([$id]);
        $inscription = $stmt->fetch();
    }
    
    $voyageurs = $db->query("SELECT id, nom, prenom, reference FROM voyageurs WHERE status='actif' ORDER BY nom")->fetchAll();
    $programmes = $db->query("SELECT id, nom, type, reference, prix_double, prix_triple, prix_quadruple, prix_quintuple FROM programmes WHERE status='en_cours' ORDER BY date_depart")->fetchAll();
    $groupes = $db->query("SELECT id, nom, type FROM groupes WHERE status='actif' ORDER BY nom")->fetchAll();
    $hotels = $db->query("SELECT id, nom, ville FROM hotels WHERE status='actif' ORDER BY nom")->fetchAll();
    $vols = $db->query("SELECT id, compagnie, numero_vol, aeroport_depart, aeroport_arrivee, date_depart FROM vols WHERE status='actif' ORDER BY date_depart")->fetchAll();
    
    $preselectedProgramme = intval($_GET['programme_id'] ?? ($inscription['programme_id'] ?? 0));
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/inscriptions.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-journal-plus me-2"></i><?= $inscription ? 'Modifier l\'inscription' : 'Nouvelle inscription' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $inscription['id'] ?? '' ?>">
                
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Voyageur *</label>
                        <select name="voyageur_id" class="form-select select2" required>
                            <option value="">-- Sélectionner --</option>
                            <?php foreach ($voyageurs as $v): ?>
                                <option value="<?= $v['id'] ?>" <?= ($inscription['voyageur_id'] ?? '')==$v['id']?'selected':'' ?>><?= sanitize($v['prenom'].' '.$v['nom'].' ('.$v['reference'].')') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Programme *</label>
                        <select name="programme_id" class="form-select select2" required id="programmeSelect">
                            <option value="">-- Sélectionner --</option>
                            <?php foreach ($programmes as $p): ?>
                                <option value="<?= $p['id'] ?>" data-double="<?= $p['prix_double'] ?>" data-triple="<?= $p['prix_triple'] ?>" data-quadruple="<?= $p['prix_quadruple'] ?>" data-quintuple="<?= $p['prix_quintuple'] ?>" <?= $preselectedProgramme==$p['id']?'selected':'' ?>><?= sanitize($p['nom'].' ['.ucfirst($p['type']).']') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Type de chambre</label>
                        <select name="formule" class="form-select" id="formuleSelect" onchange="updatePrix()">
                            <option value="double" <?= ($inscription['formule'] ?? '')=='double'?'selected':'' ?>>Double</option>
                            <option value="triple" <?= ($inscription['formule'] ?? '')=='triple'?'selected':'' ?>>Triple</option>
                            <option value="quadruple" <?= ($inscription['formule'] ?? '')=='quadruple'?'selected':'' ?>>Quadruple</option>
                            <option value="quintuple" <?= ($inscription['formule'] ?? '')=='quintuple'?'selected':'' ?>>Quintuple</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">N° Dossier</label>
                        <input type="text" name="num_dossier" class="form-control" value="<?= sanitize($inscription['num_dossier'] ?? '') ?>" placeholder="Auto-généré">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Prix total (MAD)</label>
                        <input type="number" step="0.01" name="prix_total" class="form-control" id="prixTotal" value="<?= $inscription['prix_total'] ?? '0' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Statut</label>
                        <select name="status" class="form-select">
                            <option value="en_cours" <?= ($inscription['status'] ?? '')=='en_cours'?'selected':'' ?>>En cours</option>
                            <option value="confirme" <?= ($inscription['status'] ?? '')=='confirme'?'selected':'' ?>>Confirmé</option>
                            <option value="annule" <?= ($inscription['status'] ?? '')=='annule'?'selected':'' ?>>Annulé</option>
                        </select>
                    </div>
                    
                    <div class="col-12"><h6 class="text-primary mt-3 border-bottom pb-2"><i class="bi bi-passport me-2"></i>Visa & Santé</h6></div>
                    <div class="col-md-4">
                        <label class="form-label">Statut Visa</label>
                        <select name="statut_visa" class="form-select">
                            <option value="en_attente" <?= ($inscription['statut_visa'] ?? '')=='en_attente'?'selected':'' ?>>En attente</option>
                            <option value="confirme" <?= ($inscription['statut_visa'] ?? '')=='confirme'?'selected':'' ?>>Confirmé</option>
                            <option value="refuse" <?= ($inscription['statut_visa'] ?? '')=='refuse'?'selected':'' ?>>Refusé</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Vaccination</label>
                        <select name="vaccination" class="form-select">
                            <option value="non" <?= ($inscription['vaccination'] ?? '')=='non'?'selected':'' ?>>Non</option>
                            <option value="oui" <?= ($inscription['vaccination'] ?? '')=='oui'?'selected':'' ?>>Oui</option>
                        </select>
                    </div>
                    
                    <div class="col-12"><h6 class="text-primary mt-3 border-bottom pb-2"><i class="bi bi-building me-2"></i>Hébergement & Transport</h6></div>
                    <div class="col-md-4">
                        <label class="form-label">Groupe</label>
                        <select name="groupe_id" class="form-select select2">
                            <option value="">-- Aucun --</option>
                            <?php foreach ($groupes as $g): ?>
                                <option value="<?= $g['id'] ?>" <?= ($inscription['groupe_id'] ?? '')==$g['id']?'selected':'' ?>><?= sanitize($g['nom']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Hôtel</label>
                        <select name="hotel_id" class="form-select select2">
                            <option value="">-- Aucun --</option>
                            <?php foreach ($hotels as $h): ?>
                                <option value="<?= $h['id'] ?>" <?= ($inscription['hotel_id'] ?? '')==$h['id']?'selected':'' ?>><?= sanitize($h['nom'].' - '.$h['ville']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Type chambre</label>
                        <select name="chambre_type" class="form-select">
                            <option value="">--</option>
                            <option value="double" <?= ($inscription['chambre_type'] ?? '')=='double'?'selected':'' ?>>Double</option>
                            <option value="triple" <?= ($inscription['chambre_type'] ?? '')=='triple'?'selected':'' ?>>Triple</option>
                            <option value="quadruple" <?= ($inscription['chambre_type'] ?? '')=='quadruple'?'selected':'' ?>>Quadruple</option>
                            <option value="quintuple" <?= ($inscription['chambre_type'] ?? '')=='quintuple'?'selected':'' ?>>Quintuple</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">N° Chambre</label>
                        <input type="text" name="chambre_numero" class="form-control" value="<?= sanitize($inscription['chambre_numero'] ?? '') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Vol Aller</label>
                        <select name="vol_aller_id" class="form-select select2">
                            <option value="">-- Aucun --</option>
                            <?php foreach ($vols as $vol): ?>
                                <option value="<?= $vol['id'] ?>" <?= ($inscription['vol_aller_id'] ?? '')==$vol['id']?'selected':'' ?>><?= sanitize($vol['compagnie'].' '.$vol['numero_vol'].' - '.$vol['aeroport_depart'].' → '.$vol['aeroport_arrivee'].' ('.formatDate($vol['date_depart']).')') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Vol Retour</label>
                        <select name="vol_retour_id" class="form-select select2">
                            <option value="">-- Aucun --</option>
                            <?php foreach ($vols as $vol): ?>
                                <option value="<?= $vol['id'] ?>" <?= ($inscription['vol_retour_id'] ?? '')==$vol['id']?'selected':'' ?>><?= sanitize($vol['compagnie'].' '.$vol['numero_vol'].' - '.$vol['aeroport_depart'].' → '.$vol['aeroport_arrivee'].' ('.formatDate($vol['date_depart']).')') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="2"><?= sanitize($inscription['notes'] ?? '') ?></textarea>
                    </div>
                </div>
                <div class="d-flex gap-2 mt-4">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Enregistrer</button>
                    <a href="<?= APP_URL ?>/inscriptions.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php
    $extraScripts = "<script>
    function updatePrix() {
        var sel = document.getElementById('programmeSelect');
        var opt = sel.options[sel.selectedIndex];
        var formule = document.getElementById('formuleSelect').value;
        var prix = opt.getAttribute('data-' + formule);
        if (prix) document.getElementById('prixTotal').value = prix;
    }
    document.getElementById('programmeSelect').addEventListener('change', updatePrix);
    </script>";
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

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

$where = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (v.nom LIKE ? OR v.prenom LIKE ? OR i.num_dossier LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s]; }
if ($typeFilter) { $where .= " AND p.type=?"; $params[] = $typeFilter; }
if ($statusFilter) { $where .= " AND i.statut_paiement=?"; $params[] = $statusFilter; }

$total = $db->prepare("SELECT COUNT(*) FROM inscriptions i JOIN voyageurs v ON i.voyageur_id=v.id JOIN programmes p ON i.programme_id=p.id $where");
$total->execute($params);
$pagination = paginate($total->fetchColumn(), 15, $page);

$stmt = $db->prepare("SELECT i.*, v.nom, v.prenom, v.telephone, p.nom as programme_nom, p.type as programme_type FROM inscriptions i JOIN voyageurs v ON i.voyageur_id=v.id JOIN programmes p ON i.programme_id=p.id $where ORDER BY i.created_at DESC LIMIT {$pagination['per_page']} OFFSET {$pagination['offset']}");
$stmt->execute($params);
$inscriptions = $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:130px;">
            <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>
        <select name="status" class="form-select" style="width:130px;">
            <option value="">Paiement</option>
            <option value="paye" <?= $statusFilter=='paye'?'selected':'' ?>>Payé</option>
            <option value="partiel" <?= $statusFilter=='partiel'?'selected':'' ?>>Partiel</option>
            <option value="impaye" <?= $statusFilter=='impaye'?'selected':'' ?>>Impayé</option>
        </select>
        <button class="btn btn-outline-primary">Filtrer</button>
    </form>
    <a href="<?= APP_URL ?>/inscriptions.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouvelle inscription</a>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr>
                <th>Dossier</th><th>Voyageur</th><th>Programme</th><th>Chambre</th><th>Visa</th><th>Paiement</th><th>Statut</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>
                        <br><small class="text-muted"><?= sanitize($ins['telephone'] ?: '') ?></small>
                    </td>
                    <td>
                        <span class="badge bg-<?= $ins['programme_type']=='hajj'?'success':($ins['programme_type']=='omra'?'info':'primary') ?> bg-opacity-10 text-<?= $ins['programme_type']=='hajj'?'success':($ins['programme_type']=='omra'?'info':'primary') ?>"><?= ucfirst($ins['programme_type']) ?></span>
                        <br><small><?= sanitize($ins['programme_nom']) ?></small>
                    </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><?= getStatusBadge($ins['status']) ?></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/inscriptions.php?action=edit&id=<?= $ins['id'] ?>" class="btn btn-outline-warning" title="Modifier"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/paiements.php?action=add&inscription_id=<?= $ins['id'] ?>" class="btn btn-outline-success" title="Paiement"><i class="bi bi-cash"></i></a>
                            <a href="<?= APP_URL ?>/inscriptions.php?action=delete&id=<?= $ins['id'] ?>" class="btn btn-outline-danger" title="Supprimer" onclick="return confirmDelete('Supprimer cette inscription et ses paiements associés ?')"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($inscriptions)): ?><tr><td colspan="8" class="text-center text-muted py-4">Aucune inscription</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <?= renderPagination($pagination, APP_URL.'/inscriptions.php?search='.urlencode($search).'&type='.urlencode($typeFilter).'&status='.urlencode($statusFilter)) ?>
    </div>
</div>

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