<?php
$pageTitle = 'Voyageurs & Pèlerins';
require_once __DIR__ . '/includes/header.php';
$db = getDB();

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

// Delete
if ($action === 'delete' && $id) {
    $db->prepare("UPDATE voyageurs SET status='inactif' WHERE id=?")->execute([$id]);
    logAction($_SESSION['user_id'], 'voyageur_delete', "Voyageur #$id désactivé");
    flash('success', 'Voyageur désactivé avec succès.');
    redirect('/voyageurs.php');
}

// Save (create/update)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'nom' => sanitize($_POST['nom'] ?? ''),
        'prenom' => sanitize($_POST['prenom'] ?? ''),
        'date_naissance' => $_POST['date_naissance'] ?? '',
        'lieu_naissance' => sanitize($_POST['lieu_naissance'] ?? ''),
        'sexe' => $_POST['sexe'] ?? '',
        'nationalite' => sanitize($_POST['nationalite'] ?? 'Marocaine'),
        'cin' => sanitize($_POST['cin'] ?? ''),
        'num_passeport' => sanitize($_POST['num_passeport'] ?? ''),
        'date_expiration_passeport' => $_POST['date_expiration_passeport'] ?? '',
        'telephone' => sanitize($_POST['telephone'] ?? ''),
        'telephone2' => sanitize($_POST['telephone2'] ?? ''),
        'email' => sanitize($_POST['email'] ?? ''),
        'adresse' => sanitize($_POST['adresse'] ?? ''),
        'ville' => sanitize($_POST['ville'] ?? ''),
        'contact_urgence_nom' => sanitize($_POST['contact_urgence_nom'] ?? ''),
        'contact_urgence_tel' => sanitize($_POST['contact_urgence_tel'] ?? ''),
        'contact_urgence_lien' => sanitize($_POST['contact_urgence_lien'] ?? ''),
        'notes' => sanitize($_POST['notes'] ?? ''),
    ];

    // Handle photo upload
    $photo = null;
    if (!empty($_FILES['photo']['name'])) {
        $photo = uploadFile($_FILES['photo'], PHOTOS_DIR, ['jpg','jpeg','png']);
    }

    $editId = intval($_POST['id'] ?? 0);
    if ($editId) {
        $sql = "UPDATE voyageurs SET nom=?,prenom=?,date_naissance=?,lieu_naissance=?,sexe=?,nationalite=?,cin=?,num_passeport=?,date_expiration_passeport=?,telephone=?,telephone2=?,email=?,adresse=?,ville=?,contact_urgence_nom=?,contact_urgence_tel=?,contact_urgence_lien=?,notes=?,updated_at=datetime('now')";
        $params = array_values($data);
        if ($photo) {
            $sql .= ",photo=?";
            $params[] = $photo;
        }
        $sql .= " WHERE id=?";
        $params[] = $editId;
        $db->prepare($sql)->execute($params);
        logAction($_SESSION['user_id'], 'voyageur_update', "Voyageur #$editId modifié");
        flash('success', 'Voyageur modifié avec succès.');
    } else {
        $ref = generateReference('VYG');
        $sql = "INSERT INTO voyageurs (reference,nom,prenom,date_naissance,lieu_naissance,sexe,nationalite,cin,num_passeport,date_expiration_passeport,telephone,telephone2,email,adresse,ville,contact_urgence_nom,contact_urgence_tel,contact_urgence_lien,notes,photo) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $params = [$ref];
        $params = array_merge($params, array_values($data));
        $params[] = $photo;
        $db->prepare($sql)->execute($params);
        logAction($_SESSION['user_id'], 'voyageur_create', "Voyageur créé: $ref");
        flash('success', 'Voyageur ajouté avec succès.');
    }
    redirect('/voyageurs.php');
}

// VIEW / EDIT details
if ($action === 'view' && $id) {
    $voyageur = $db->prepare("SELECT * FROM voyageurs WHERE id=?")->execute([$id]) ? $db->prepare("SELECT * FROM voyageurs WHERE id=?") : null;
    $stmt = $db->prepare("SELECT * FROM voyageurs WHERE id=?");
    $stmt->execute([$id]);
    $voyageur = $stmt->fetch();
    if (!$voyageur) { flash('error','Voyageur introuvable.'); redirect('/voyageurs.php'); }
    
    // Get inscriptions
    $stmtIns = $db->prepare("SELECT i.*, p.nom as programme_nom, p.type as programme_type FROM inscriptions i JOIN programmes p ON i.programme_id=p.id WHERE i.voyageur_id=? ORDER BY i.created_at DESC");
    $stmtIns->execute([$id]);
    $inscriptions = $stmtIns->fetchAll();
    
    // Get paiements
    $stmtPay = $db->prepare("SELECT pa.*, p.nom as programme_nom FROM paiements pa JOIN inscriptions i ON pa.inscription_id=i.id JOIN programmes p ON i.programme_id=p.id WHERE pa.voyageur_id=? ORDER BY pa.date_paiement DESC");
    $stmtPay->execute([$id]);
    $paiements = $stmtPay->fetchAll();
    
    // Get documents
    $stmtDoc = $db->prepare("SELECT * FROM documents WHERE voyageur_id=? ORDER BY created_at DESC");
    $stmtDoc->execute([$id]);
    $documents = $stmtDoc->fetchAll();
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/voyageurs.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour</a>
        <div>
            <a href="<?= APP_URL ?>/voyageurs.php?action=edit&id=<?= $voyageur['id'] ?>" class="btn btn-warning"><i class="bi bi-pencil me-1"></i>Modifier</a>
        </div>
    </div>
    
    <div class="row g-3">
        <div class="col-lg-4">
            <div class="card table-card mb-3">
                <div class="card-body text-center p-4">
                    <?php if ($voyageur['photo']): ?>
                        <img src="<?= APP_URL ?>/uploads/photos/<?= $voyageur['photo'] ?>" class="rounded-circle mb-3" width="120" height="120" style="object-fit:cover;">
                    <?php else: ?>
                        <div class="rounded-circle bg-primary bg-opacity-10 d-inline-flex align-items-center justify-content-center mb-3" style="width:120px;height:120px;">
                            <i class="bi bi-person-fill text-primary" style="font-size:3rem;"></i>
                        </div>
                    <?php endif; ?>
                    <h4 class="mb-1"><?= sanitize($voyageur['prenom'].' '.$voyageur['nom']) ?></h4>
                    <p class="text-muted mb-2"><?= sanitize($voyageur['reference']) ?></p>
                    <?= getStatusBadge($voyageur['status']) ?>
                </div>
            </div>
            <div class="card table-card">
                <div class="card-header"><i class="bi bi-telephone me-2"></i>Contact d'urgence</div>
                <div class="card-body">
                    <p class="mb-1"><strong><?= sanitize($voyageur['contact_urgence_nom'] ?: '-') ?></strong></p>
                    <p class="mb-1"><i class="bi bi-phone me-2"></i><?= sanitize($voyageur['contact_urgence_tel'] ?: '-') ?></p>
                    <p class="mb-0"><i class="bi bi-people me-2"></i><?= sanitize($voyageur['contact_urgence_lien'] ?: '-') ?></p>
                </div>
            </div>
        </div>
        <div class="col-lg-8">
            <div class="card table-card mb-3">
                <div class="card-header"><i class="bi bi-info-circle me-2"></i>Informations personnelles</div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-6"><small class="text-muted">Date de naissance</small><br><strong><?= formatDate($voyageur['date_naissance']) ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Lieu de naissance</small><br><strong><?= sanitize($voyageur['lieu_naissance'] ?: '-') ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Sexe</small><br><strong><?= $voyageur['sexe']=='M'?'Masculin':'Féminin' ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Nationalité</small><br><strong><?= sanitize($voyageur['nationalite']) ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">CIN</small><br><strong><?= sanitize($voyageur['cin'] ?: '-') ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Passeport</small><br><strong><?= sanitize($voyageur['num_passeport'] ?: '-') ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Expiration passeport</small><br><strong><?= formatDate($voyageur['date_expiration_passeport']) ?: '-' ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Ville</small><br><strong><?= sanitize($voyageur['ville'] ?: '-') ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Téléphone</small><br><strong><?= sanitize($voyageur['telephone'] ?: '-') ?></strong></div>
                        <div class="col-md-6"><small class="text-muted">Email</small><br><strong><?= sanitize($voyageur['email'] ?: '-') ?></strong></div>
                        <div class="col-12"><small class="text-muted">Adresse</small><br><strong><?= sanitize($voyageur['adresse'] ?: '-') ?></strong></div>
                    </div>
                </div>
            </div>
            
            <!-- Inscriptions -->
            <div class="card table-card mb-3">
                <div class="card-header"><i class="bi bi-journal-check me-2"></i>Historique des inscriptions (<?= count($inscriptions) ?>)</div>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead><tr><th>Dossier</th><th>Programme</th><th>Chambre</th><th>Visa</th><th>Paiement</th><th>Statut</th></tr></thead>
                        <tbody>
                        <?php foreach ($inscriptions as $ins): ?>
                            <tr>
                                <td><strong><?= sanitize($ins['num_dossier'] ?: '-') ?></strong></td>
                                <td><?= sanitize($ins['programme_nom']) ?></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>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($inscriptions)): ?><tr><td colspan="6" class="text-center text-muted py-3">Aucune inscription</td></tr><?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Paiements -->
            <div class="card table-card">
                <div class="card-header"><i class="bi bi-cash-stack me-2"></i>Historique des paiements (<?= count($paiements) ?>)</div>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead><tr><th>Date</th><th>Programme</th><th>Montant</th><th>Mode</th><th>Référence</th></tr></thead>
                        <tbody>
                        <?php foreach ($paiements as $p): ?>
                            <tr>
                                <td><?= formatDate($p['date_paiement']) ?></td>
                                <td><?= sanitize($p['programme_nom']) ?></td>
                                <td class="fw-bold text-success"><?= formatMoney($p['montant']) ?></td>
                                <td><?= ucfirst($p['mode_paiement']) ?></td>
                                <td><small><?= sanitize($p['reference_paiement'] ?: '-') ?></small></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($paiements)): ?><tr><td colspan="5" class="text-center text-muted py-3">Aucun paiement</td></tr><?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// FORM (add/edit)
if ($action === 'add' || $action === 'edit') {
    $voyageur = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM voyageurs WHERE id=?");
        $stmt->execute([$id]);
        $voyageur = $stmt->fetch();
        if (!$voyageur) { flash('error','Voyageur introuvable.'); redirect('/voyageurs.php'); }
    }
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/voyageurs.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-person-plus me-2"></i><?= $voyageur ? 'Modifier le voyageur' : 'Nouveau voyageur' ?></div>
        <div class="card-body p-4">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?= $voyageur['id'] ?? '' ?>">
                
                <h6 class="text-primary mb-3 border-bottom pb-2"><i class="bi bi-person me-2"></i>Identité</h6>
                <div class="row g-3 mb-4">
                    <div class="col-md-4">
                        <label class="form-label">Nom *</label>
                        <input type="text" name="nom" class="form-control" value="<?= sanitize($voyageur['nom'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Prénom *</label>
                        <input type="text" name="prenom" class="form-control" value="<?= sanitize($voyageur['prenom'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Photo</label>
                        <input type="file" name="photo" class="form-control" accept="image/*">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Date de naissance</label>
                        <input type="date" name="date_naissance" class="form-control" value="<?= $voyageur['date_naissance'] ?? '' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Lieu de naissance</label>
                        <input type="text" name="lieu_naissance" class="form-control" value="<?= sanitize($voyageur['lieu_naissance'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Sexe</label>
                        <select name="sexe" class="form-select">
                            <option value="M" <?= ($voyageur['sexe'] ?? '')=='M'?'selected':'' ?>>Masculin</option>
                            <option value="F" <?= ($voyageur['sexe'] ?? '')=='F'?'selected':'' ?>>Féminin</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Nationalité</label>
                        <input type="text" name="nationalite" class="form-control" value="<?= sanitize($voyageur['nationalite'] ?? 'Marocaine') ?>">
                    </div>
                </div>
                
                <h6 class="text-primary mb-3 border-bottom pb-2"><i class="bi bi-card-text me-2"></i>Documents d'identité</h6>
                <div class="row g-3 mb-4">
                    <div class="col-md-4">
                        <label class="form-label">CIN</label>
                        <input type="text" name="cin" class="form-control" value="<?= sanitize($voyageur['cin'] ?? '') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">N° Passeport</label>
                        <input type="text" name="num_passeport" class="form-control" value="<?= sanitize($voyageur['num_passeport'] ?? '') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Date expiration passeport</label>
                        <input type="date" name="date_expiration_passeport" class="form-control" value="<?= $voyageur['date_expiration_passeport'] ?? '' ?>">
                    </div>
                </div>
                
                <h6 class="text-primary mb-3 border-bottom pb-2"><i class="bi bi-telephone me-2"></i>Coordonnées</h6>
                <div class="row g-3 mb-4">
                    <div class="col-md-3">
                        <label class="form-label">Téléphone</label>
                        <input type="text" name="telephone" class="form-control" value="<?= sanitize($voyageur['telephone'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Téléphone 2</label>
                        <input type="text" name="telephone2" class="form-control" value="<?= sanitize($voyageur['telephone2'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" value="<?= sanitize($voyageur['email'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Ville</label>
                        <input type="text" name="ville" class="form-control" value="<?= sanitize($voyageur['ville'] ?? '') ?>">
                    </div>
                    <div class="col-md-12">
                        <label class="form-label">Adresse</label>
                        <input type="text" name="adresse" class="form-control" value="<?= sanitize($voyageur['adresse'] ?? '') ?>">
                    </div>
                </div>
                
                <h6 class="text-primary mb-3 border-bottom pb-2"><i class="bi bi-heart-pulse me-2"></i>Contact d'urgence</h6>
                <div class="row g-3 mb-4">
                    <div class="col-md-4">
                        <label class="form-label">Nom complet</label>
                        <input type="text" name="contact_urgence_nom" class="form-control" value="<?= sanitize($voyageur['contact_urgence_nom'] ?? '') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Téléphone</label>
                        <input type="text" name="contact_urgence_tel" class="form-control" value="<?= sanitize($voyageur['contact_urgence_tel'] ?? '') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Lien de parenté</label>
                        <input type="text" name="contact_urgence_lien" class="form-control" value="<?= sanitize($voyageur['contact_urgence_lien'] ?? '') ?>">
                    </div>
                </div>
                
                <div class="mb-4">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="3"><?= sanitize($voyageur['notes'] ?? '') ?></textarea>
                </div>
                
                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Enregistrer</button>
                    <a href="<?= APP_URL ?>/voyageurs.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// LIST
$search = $_GET['search'] ?? '';
$filter = $_GET['filter'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));

$where = "WHERE v.status='actif'";
$params = [];
if ($search) {
    $where .= " AND (v.nom LIKE ? OR v.prenom LIKE ? OR v.cin LIKE ? OR v.num_passeport LIKE ? OR v.telephone LIKE ? OR v.reference LIKE ?)";
    $s = "%$search%";
    $params = [$s,$s,$s,$s,$s,$s];
}

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

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

<div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
    <form class="d-flex gap-2" method="GET">
        <div class="input-group" style="width:300px;">
            <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>
        <button class="btn btn-outline-primary">Chercher</button>
    </form>
    <a href="<?= APP_URL ?>/voyageurs.php?action=add" class="btn btn-primary">
        <i class="bi bi-plus-lg me-1"></i>Nouveau voyageur
    </a>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Réf</th><th>Nom complet</th><th>CIN</th><th>Passeport</th><th>Téléphone</th><th>Ville</th><th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($voyageurs as $v): ?>
                <tr>
                    <td><small class="fw-bold text-muted"><?= sanitize($v['reference']) ?></small></td>
                    <td><strong><?= sanitize($v['prenom'].' '.$v['nom']) ?></strong></td>
                    <td><?= sanitize($v['cin'] ?: '-') ?></td>
                    <td>
                        <?= sanitize($v['num_passeport'] ?: '-') ?>
                        <?php if ($v['date_expiration_passeport'] && $v['date_expiration_passeport'] <= date('Y-m-d', strtotime('+3 months'))): ?>
                            <br><small class="text-danger"><i class="bi bi-exclamation-triangle"></i> Exp: <?= formatDate($v['date_expiration_passeport']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?= sanitize($v['telephone'] ?: '-') ?></td>
                    <td><?= sanitize($v['ville'] ?: '-') ?></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $v['id'] ?>" class="btn btn-outline-primary" title="Voir"><i class="bi bi-eye"></i></a>
                            <a href="<?= APP_URL ?>/voyageurs.php?action=edit&id=<?= $v['id'] ?>" class="btn btn-outline-warning" title="Modifier"><i class="bi bi-pencil"></i></a>
                            <a href="<?= APP_URL ?>/voyageurs.php?action=delete&id=<?= $v['id'] ?>" class="btn btn-outline-danger" title="Supprimer" onclick="return confirmDelete()"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($voyageurs)): ?>
                <tr><td colspan="7" class="text-center text-muted py-4">Aucun voyageur trouvé</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <?= renderPagination($pagination, APP_URL.'/voyageurs.php?search='.urlencode($search)) ?>
        <p class="text-muted small text-center mb-0"><?= $pagination['total'] ?> voyageur(s) trouvé(s)</p>
    </div>
</div>

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