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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nom = trim($_POST['nom'] ?? '');
    
    if (empty($nom)) {
        flash('error', 'Le nom du groupe est obligatoire.');
        redirect('/groupes.php');
    }
    
    $editId = intval($_POST['id'] ?? 0);
    $data = [
        $nom, $_POST['type'] ?? 'hajj',
        intval($_POST['programme_id'] ?? 0) ?: null,
        $_POST['chef_groupe'] ?? '', $_POST['chef_groupe_tel'] ?? '',
        intval($_POST['capacite'] ?? 40), $_POST['notes'] ?? '',
    ];
    if ($editId) {
        $data[] = $editId;
        $db->prepare("UPDATE groupes SET nom=?,type=?,programme_id=?,chef_groupe=?,chef_groupe_tel=?,capacite=?,notes=?,updated_at=datetime('now') WHERE id=?")->execute($data);
        flash('success', 'Groupe modifié.');
    } else {
        $db->prepare("INSERT INTO groupes (nom,type,programme_id,chef_groupe,chef_groupe_tel,capacite,notes) VALUES (?,?,?,?,?,?,?)")->execute($data);
        flash('success', 'Groupe créé.');
    }
    redirect('/groupes.php');
}

// View group details with members
if ($action === 'view' && $id) {
    $stmt = $db->prepare("SELECT g.*, p.nom as programme_nom FROM groupes g LEFT JOIN programmes p ON g.programme_id=p.id WHERE g.id=?");
    $stmt->execute([$id]);
    $groupe = $stmt->fetch();
    if (!$groupe) { flash('error','Groupe introuvable.'); redirect('/groupes.php'); }
    
    $membres = $db->prepare("SELECT i.*, v.nom, v.prenom, v.telephone, v.cin, v.num_passeport FROM inscriptions i JOIN voyageurs v ON i.voyageur_id=v.id WHERE i.groupe_id=? AND i.status != 'annule' ORDER BY v.nom");
    $membres->execute([$id]);
    $membres = $membres->fetchAll();
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <a href="<?= APP_URL ?>/groupes.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour</a>
        <div class="d-flex gap-2">
            <button onclick="window.print()" class="btn btn-outline-primary no-print"><i class="bi bi-printer me-1"></i>Imprimer</button>
            <a href="<?= APP_URL ?>/groupes.php?action=edit&id=<?= $groupe['id'] ?>" class="btn btn-warning no-print"><i class="bi bi-pencil me-1"></i>Modifier</a>
        </div>
    </div>
    
    <div class="card table-card mb-3">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="bi bi-diagram-3 me-2"></i><?= sanitize($groupe['nom']) ?></span>
            <span class="badge bg-<?= $groupe['type']=='hajj'?'success':($groupe['type']=='omra'?'info':'primary') ?>"><?= ucfirst($groupe['type']) ?></span>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3"><small class="text-muted">Programme</small><br><strong><?= sanitize($groupe['programme_nom'] ?: '-') ?></strong></div>
                <div class="col-md-3"><small class="text-muted">Chef de groupe</small><br><strong><?= sanitize($groupe['chef_groupe'] ?: '-') ?></strong></div>
                <div class="col-md-3"><small class="text-muted">Tél. chef</small><br><strong><?= sanitize($groupe['chef_groupe_tel'] ?: '-') ?></strong></div>
                <div class="col-md-3"><small class="text-muted">Membres</small><br><strong><?= count($membres) ?> / <?= $groupe['capacite'] ?></strong></div>
            </div>
        </div>
    </div>
    
    <div class="card table-card">
        <div class="card-header"><i class="bi bi-people me-2"></i>Membres du groupe (<?= count($membres) ?>)</div>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead><tr><th>#</th><th>Nom & Prénom</th><th>CIN</th><th>Passeport</th><th>Téléphone</th><th>Chambre</th><th>Visa</th><th>Paiement</th></tr></thead>
                <tbody>
                <?php foreach ($membres as $i => $m): ?>
                    <tr>
                        <td><?= $i+1 ?></td>
                        <td><a href="<?= APP_URL ?>/voyageurs.php?action=view&id=<?= $m['voyageur_id'] ?>"><?= sanitize($m['prenom'].' '.$m['nom']) ?></a></td>
                        <td><?= sanitize($m['cin'] ?: '-') ?></td>
                        <td><?= sanitize($m['num_passeport'] ?: '-') ?></td>
                        <td><?= sanitize($m['telephone'] ?: '-') ?></td>
                        <td><?= ucfirst($m['formule']) ?></td>
                        <td><?= getStatusBadge($m['statut_visa']) ?></td>
                        <td><?= getStatusBadge($m['statut_paiement']) ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($membres)): ?><tr><td colspan="8" class="text-center text-muted py-3">Aucun membre</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php require_once __DIR__ . '/includes/footer.php'; exit; }

// Form
if ($action === 'add' || $action === 'edit') {
    $groupe = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM groupes WHERE id=?"); $stmt->execute([$id]); $groupe = $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 ?>/groupes.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-diagram-3 me-2"></i><?= $groupe ? 'Modifier le groupe' : 'Nouveau groupe' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $groupe['id'] ?? '' ?>">
                <div class="row g-3">
                    <div class="col-md-6"><label class="form-label">Nom du groupe *</label><input type="text" name="nom" class="form-control" value="<?= sanitize($groupe['nom'] ?? '') ?>" required></div>
                    <div class="col-md-3">
                        <label class="form-label">Type</label>
                        <select name="type" class="form-select">
                            <option value="hajj" <?= ($groupe['type']??'')=='hajj'?'selected':'' ?>>Hajj</option>
                            <option value="omra" <?= ($groupe['type']??'')=='omra'?'selected':'' ?>>Omra</option>
                            <option value="tourisme" <?= ($groupe['type']??'')=='tourisme'?'selected':'' ?>>Tourisme</option>
                        </select>
                    </div>
                    <div class="col-md-3"><label class="form-label">Capacité</label><input type="number" name="capacite" class="form-control" value="<?= $groupe['capacite'] ?? 40 ?>"></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'] ?>" <?= ($groupe['programme_id'] ?? '')==$p['id']?'selected':'' ?>><?= sanitize($p['nom']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4"><label class="form-label">Chef de groupe</label><input type="text" name="chef_groupe" class="form-control" value="<?= sanitize($groupe['chef_groupe'] ?? '') ?>"></div>
                    <div class="col-md-4"><label class="form-label">Tél. chef</label><input type="text" name="chef_groupe_tel" class="form-control" value="<?= sanitize($groupe['chef_groupe_tel'] ?? '') ?>"></div>
                    <div class="col-12"><label class="form-label">Notes</label><textarea name="notes" class="form-control" rows="2"><?= sanitize($groupe['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 ?>/groupes.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php require_once __DIR__ . '/includes/footer.php'; exit; }

// List
$groupes = $db->query("
    SELECT g.*, p.nom as programme_nom, 
    (SELECT COUNT(*) FROM inscriptions i WHERE i.groupe_id=g.id AND i.status != 'annule') as nb_membres
    FROM groupes g LEFT JOIN programmes p ON g.programme_id=p.id 
    WHERE g.status='actif' ORDER BY g.created_at DESC
")->fetchAll();
?>

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

<div class="row g-3">
<?php foreach ($groupes as $g): ?>
    <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">
                    <h6 class="fw-bold mb-0"><?= sanitize($g['nom']) ?></h6>
                    <span class="badge bg-<?= $g['type']=='hajj'?'success':($g['type']=='omra'?'info':'primary') ?>"><?= ucfirst($g['type']) ?></span>
                </div>
                <p class="text-muted small mb-2"><i class="bi bi-calendar me-1"></i><?= sanitize($g['programme_nom'] ?: 'Aucun programme') ?></p>
                <div class="row g-1 small mb-2">
                    <div class="col-6"><i class="bi bi-person-badge me-1"></i><?= sanitize($g['chef_groupe'] ?: '-') ?></div>
                    <div class="col-6"><i class="bi bi-telephone me-1"></i><?= sanitize($g['chef_groupe_tel'] ?: '-') ?></div>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="small">Membres: <strong><?= $g['nb_membres'] ?>/<?= $g['capacite'] ?></strong></span>
                    <span class="small text-muted"><?= $g['capacite']>0?round($g['nb_membres']/$g['capacite']*100):0 ?>%</span>
                </div>
                <div class="progress mb-3" style="height:4px;"><div class="progress-bar bg-success" style="width:<?= $g['capacite']>0?round($g['nb_membres']/$g['capacite']*100):0 ?>%"></div></div>
                <div class="d-flex gap-1">
                    <a href="<?= APP_URL ?>/groupes.php?action=view&id=<?= $g['id'] ?>" class="btn btn-sm btn-outline-primary flex-fill"><i class="bi bi-eye me-1"></i>Voir</a>
                    <a href="<?= APP_URL ?>/groupes.php?action=edit&id=<?= $g['id'] ?>" class="btn btn-sm btn-outline-warning"><i class="bi bi-pencil"></i></a>
                    <a href="<?= APP_URL ?>/groupes.php?action=delete&id=<?= $g['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirmDelete()"><i class="bi bi-trash"></i></a>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>
<?php if (empty($groupes)): ?><div class="col-12 text-center text-muted py-5">Aucun groupe</div><?php endif; ?>
</div>

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