<?php 
session_start();
$userprofil = $_SESSION['user'] ?? null;
if (!$userprofil) {
    header("Location: login.php");
    exit();
}

include('includes/header.php');
require_once "includes/dbconn.php";

// Fonction pour formater les dates en français
function formatDateFr($date) {
    if (empty($date)) return '';
    $months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];
    $d = date('j', strtotime($date));
    $m = date('n', strtotime($date)) - 1;
    $y = date('Y', strtotime($date));
    return "$d {$months[$m]} $y";
}

// Paiement d'inscription
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['gerer_inscription'])) {
    $etudiant_id = intval($_POST['etudiant_id']);
    $montant_inscription = 10000;
    $mois = 'inscription';
    $date_paiement = date('Y-m-d');

    $check = $conn->prepare("SELECT id FROM mensualites WHERE etudiant_id = ? AND mois = ?");
    $check->bind_param("is", $etudiant_id, $mois);
    $check->execute();
    $res_check = $check->get_result();

    if ($res_check->num_rows > 0) {
        echo "<script>
            Swal.fire({
                icon: 'info',
                title: 'Déjà payé',
                text: 'L\'inscription a déjà été réglée.',
                confirmButtonText: 'OK'
            });
        </script>";
    } else {
        $insert = $conn->prepare("INSERT INTO mensualites (etudiant_id, mois, montant, date_paiement) VALUES (?, ?, ?, ?)");
        $insert->bind_param("isds", $etudiant_id, $mois, $montant_inscription, $date_paiement);

        if ($insert->execute()) {
            $last_id = $insert->insert_id;
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>";
            echo "<script>
                Swal.fire({
                    icon: 'success',
                    title: 'Paiement enregistré',
                    text: 'L\'inscription a été réglée avec succès.',
                    confirmButtonText: 'OK'
                }).then(() => {
                    window.location.href = 'recu_inscription.php?id={$last_id}';
                });
            </script>";
            exit;
        } else {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>";
            echo "<script>Swal.fire('Erreur', 'Échec lors de l\'enregistrement.', 'error');</script>";
        }
    }
}

// Récupération des infos
if (isset($_GET['id'])) {
    $student_id = mysqli_real_escape_string($conn, $_GET['id']);

    $query = "
        SELECT e.*, c.nom AS classe_nom, n.nom_niveau AS niveau_nom 
        FROM etudiants e
        LEFT JOIN classes c ON e.classe_id = c.id
        LEFT JOIN niveaux n ON c.niveau_id = n.id
        WHERE e.id = '$student_id'
    ";
    $query_run = mysqli_query($conn, $query);
    if (mysqli_num_rows($query_run) > 0) {
        $student = mysqli_fetch_array($query_run);
        $etudiant_id = $student['id'];

        $stmt_insc = $conn->prepare("SELECT id, montant, date_paiement FROM mensualites WHERE etudiant_id = ? AND mois = 'inscription'");
        $stmt_insc->bind_param("i", $etudiant_id);
        $stmt_insc->execute();
        $result_insc = $stmt_insc->get_result();
        $inscription = $result_insc->fetch_assoc();

        $stmt = $conn->prepare("SELECT id, mois, montant, date_paiement FROM mensualites WHERE etudiant_id = ? AND mois != 'inscription' ORDER BY mois DESC");
        $stmt->bind_param("i", $etudiant_id);
        $stmt->execute();
        $result_mensualites = $stmt->get_result();
        $nb_mensualites = $result_mensualites->num_rows;
        
        // Récupérer les deux dernières mensualités
        $stmt_last = $conn->prepare("SELECT id, mois, montant, date_paiement FROM mensualites WHERE etudiant_id = ? AND mois != 'inscription' ORDER BY mois DESC LIMIT 2");
        $stmt_last->bind_param("i", $etudiant_id);
        $stmt_last->execute();
        $result_last_mensualites = $stmt_last->get_result();
        $last_mensualites = [];
        while($row = $result_last_mensualites->fetch_assoc()) {
            $last_mensualites[] = $row;
        }
    } else {
        echo "<div class='alert alert-danger'>Étudiant non trouvé.</div>";
        exit;
    }
} else {
    echo "<div class='alert alert-warning'>ID étudiant non fourni.</div>";
    exit;
}
?>

<!-- CSS personnalisé -->
<style>
    :root {
        --primary-color: #3498db;
        --secondary-color: #2ecc71;
        --dark-color: #2980b9;
        --light-color: #ecf0f1;
        --success-color: #27ae60;
        --info-color: #3498db;
        --warning-color: #f39c12;
        --danger-color: #e74c3c;
    }
    
    body {
        background-color: #f8f9fa;
    }
    
    .card-header {
        font-weight: 600;
        letter-spacing: 0.5px;
        background: linear-gradient(135deg, var(--secondary-color), var(--primary-color));
    }
    
    .student-photo {
        border: 3px solid #fff;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        transition: transform 0.3s;
    }
    
    .student-photo:hover {
        transform: scale(1.05);
    }
    
    .progress {
        height: 1.5rem;
        border-radius: 10px;
        background-color: #f0f0f0;
    }
    
    .progress-bar {
        font-size: 0.9rem;
        font-weight: 500;
        background-color: var(--secondary-color);
    }
    
    .payment-badge {
        font-size: 0.85rem;
        padding: 0.35rem 0.7rem;
    }
    
    .table th {
        background-color: var(--light-color);
        font-weight: 600;
        color: #34495e;
    }
    
    .receipt-btn {
        min-width: 80px;
    }
    
    .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }
    
    .btn-success {
        background-color: var(--success-color);
        border-color: var(--success-color);
    }
    
    .btn-info {
        background-color: var(--info-color);
        border-color: var(--info-color);
    }
    
    .btn-warning {
        background-color: var(--warning-color);
        border-color: var(--warning-color);
    }
    
    .btn-danger {
        background-color: var(--danger-color);
        border-color: var(--danger-color);
    }
    
    .badge-primary {
        background-color: var(--primary-color);
    }
    
    .badge-success {
        background-color: var(--success-color);
    }
    
    .badge-danger {
        background-color: var(--danger-color);
    }
    
    .badge-info {
        background-color: var(--info-color);
    }
    
    .badge-warning {
        background-color: var(--warning-color);
    }
    
    .nav-pills .nav-link.active {
        background-color: var(--secondary-color);
    }
    
    .nav-pills .nav-link {
        color: var(--dark-color);
    }
    
    .step-card {
        border-left: 4px solid var(--secondary-color);
        transition: all 0.3s;
    }
    
    .step-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    }
</style>

<div class="container mt-4">
    <!-- En-tête -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0 text-primary fw-bold">
            <i class="fas fa-user-graduate me-2"></i>Dossier étudiant
        </h2>
        <span class="badge bg-primary fs-6 p-2">
            Matricule : <?= htmlspecialchars($student['matricule']) ?>
        </span>
    </div>

    <!-- Carte principale -->
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-header text-white d-flex justify-content-between align-items-center">
            <span>
                <i class="fas fa-id-card me-2"></i>
                <?= htmlspecialchars($student['prenom'] . ' ' . $student['noms']) ?>
            </span>
            <div>
                <?php if($inscription): ?>
                    <span class="badge bg-light text-success fs-6">
                        <i class="fas fa-check-circle me-1"></i> Inscription payée
                    </span>
                <?php else: ?>
                    <span class="badge bg-light text-danger fs-6">
                        <i class="fas fa-exclamation-circle me-1"></i> Inscription impayée
                    </span>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="card-body">
            <div class="row">
                <!-- Photo et info rapide -->
                <div class="col-md-3 text-center">
                    <img src="studentimages/<?= htmlspecialchars($student['photo']) ?>" 
                         class="img-fluid rounded-circle student-photo mb-3" 
                         width="180" height="180" 
                         alt="Photo de <?= htmlspecialchars($student['prenom']) ?>">
                    
                    <div class="d-grid gap-2">
                        <span class="badge bg-success payment-badge">
                            <i class="fas fa-calendar-check me-1"></i>
                            <?= $nb_mensualites ?> mois payés
                        </span>
                    </div>
                </div>
                
                <!-- Informations détaillées -->
                <div class="col-md-9">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <tbody>
                                <tr>
                                    <th width="20%"><i class="fas fa-user me-2"></i>Prénom</th>
                                    <td width="30%"><?= htmlspecialchars($student['prenom']) ?></td>
                                    <th width="20%"><i class="fas fa-user-tag me-2"></i>Nom</th>
                                    <td width="30%"><?= htmlspecialchars($student['noms']) ?></td>
                                </tr>
                                <tr>
                                    <th><i class="fas fa-birthday-cake me-2"></i>Naissance</th>
                                    <td><?= formatDateFr($student['date_de_naissance']) ?></td>
                                    <th><i class="fas fa-map-marker-alt me-2"></i>Lieu</th>
                                    <td><?= htmlspecialchars($student['lieu_de_naissance']) ?></td>
                                </tr>
                                <tr>
                                    <th><i class="fas fa-home me-2"></i>Adresse</th>
                                    <td><?= htmlspecialchars($student['adresse']) ?></td>
                                    <th><i class="fas fa-phone me-2"></i>Téléphone</th>
                                    <td><?= htmlspecialchars($student['phone']) ?></td>
                                </tr>
                                <tr>
                                    <th><i class="fas fa-graduation-cap me-2"></i>Classe</th>
                                    <td><?= htmlspecialchars($student['classe_nom']) ?></td>
                                    <th><i class="fas fa-layer-group me-2"></i>Niveau</th>
                                    <td><?= htmlspecialchars($student['niveau_nom']) ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Progression -->
    <div class="card shadow-sm border-0 mb-4 step-card">
        <div class="card-header text-white">
            <i class="fas fa-chart-line me-2"></i>Progression du paiement
        </div>
        <div class="card-body">
            <?php
                $progress = $inscription ? 10 : 0;
                $progress += ($nb_mensualites * 10); // max 10 mois
                if ($progress > 100) $progress = 100;
                
                $progress_class = '';
                if ($progress < 30) $progress_class = 'bg-danger';
                elseif ($progress < 70) $progress_class = 'bg-warning';
                else $progress_class = 'bg-success';
            ?>
            <div class="progress mb-3">
                <div class="progress-bar progress-bar-striped <?= $progress_class ?>" 
                     role="progressbar" 
                     style="width: <?= $progress ?>%;" 
                     aria-valuenow="<?= $progress ?>" 
                     aria-valuemin="0" 
                     aria-valuemax="100">
                    <?= $progress ?>%
                </div>
            </div>
            <small class="text-muted">
                <i class="fas fa-info-circle me-1"></i>
                Progression basée sur les paiements effectués (10% pour l'inscription + 10% par mois payé)
            </small>
        </div>
    </div>

    <!-- Tuteur -->
    <div class="card shadow-sm border-0 mb-4 step-card">
        <div class="card-header text-white">
            <i class="fas fa-user-friends me-2"></i>Informations du tuteur
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <tbody>
                        <tr>
                            <th width="25%"><i class="fas fa-phone-alt me-2"></i>Numéro du tuteur</th>
                            <td width="25%"><?= htmlspecialchars($student['tutor_num']) ?></td>
                            <th width="25%"><i class="fas fa-map-marked-alt me-2"></i>Adresse du tuteur</th>
                            <td width="25%"><?= htmlspecialchars($student['adresse_tutor']) ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Paiements -->
    <div class="card shadow-sm border-0 step-card">
        <div class="card-header text-white">
            <i class="fas fa-money-bill-wave me-2"></i>Historique des paiements
        </div>
        <div class="card-body">
            <!-- Inscription -->
            <div class="mb-4">
                <h5 class="d-flex justify-content-between align-items-center">
                    <span>
                        <i class="fas fa-file-signature me-2"></i>
                        Paiement d'inscription
                    </span>
                    <span class="badge bg-<?= $inscription ? 'success' : 'danger' ?>">
                        <?= $inscription ? 'Payé' : 'Impayé' ?>
                    </span>
                </h5>
                
                <?php if ($inscription): ?>
                    <div class="d-flex justify-content-between align-items-center bg-light p-3 rounded">
                        <div>
                            <span class="fw-bold"><?= number_format($inscription['montant'], 0, ',', ' ') ?> F CFA</span>
                            <span class="text-muted ms-2">payé le <?= formatDateFr($inscription['date_paiement']) ?></span>
                        </div>
                        <a href="recu_inscription.php?id=<?= $inscription['id'] ?>" 
                           target="_blank" 
                           class="btn btn-sm btn-outline-success receipt-btn">
                            <i class="fas fa-print me-1"></i>Reçu
                        </a>
                    </div>
                <?php else: ?>
                    <form method="POST" id="formInscription" class="bg-light p-3 rounded">
                        <input type="hidden" name="etudiant_id" value="<?= $etudiant_id ?>">
                        <input type="hidden" name="gerer_inscription" value="1">
                        <button type="button" 
                                class="btn btn-warning fw-bold"
                                onclick="confirmerPaiement()">
                            <i class="fas fa-money-bill me-1"></i>Payer l'inscription (10 000 F CFA)
                        </button>
                    </form>
                <?php endif; ?>
            </div>
            
            <!-- Mensualités -->
            <div>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">
                        <i class="fas fa-calendar-alt me-2"></i>
                        Mensualités payées
                    </h5>
                    <span class="badge bg-primary"><?= $nb_mensualites ?> mois</span>
                </div>
                
                <?php if ($nb_mensualites > 0): ?>
                    <!-- Boutons pour afficher les deux dernières étapes -->
                    <div class="mb-3">
                        <button class="btn btn-sm btn-outline-primary me-2" onclick="toggleLastPayments()">
                            <i class="fas fa-eye me-1"></i>Afficher les 2 derniers paiements
                        </button>
                        <button class="btn btn-sm btn-outline-secondary" onclick="toggleAllPayments()">
                            <i class="fas fa-list me-1"></i>Afficher tous les paiements
                        </button>
                    </div>
                    
                    <!-- Deux dernières mensualités -->
                    <div id="lastPayments" class="mb-4">
                        <h6><i class="fas fa-clock me-1"></i> Derniers paiements</h6>
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th><i class="fas fa-calendar me-1"></i> Mois</th>
                                        <th><i class="fas fa-coins me-1"></i> Montant</th>
                                        <th><i class="fas fa-clock me-1"></i> Date paiement</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($last_mensualites as $m): ?>
                                        <tr>
                                            <td><?= ucfirst(htmlspecialchars($m['mois'])) ?></td>
                                            <td><?= number_format($m['montant'], 0, ',', ' ') ?> F CFA</td>
                                            <td><?= formatDateFr($m['date_paiement']) ?></td>
                                            <td class="text-end">
                                                <a href="recu_inscription.php?id=<?= $m['id'] ?>" 
                                                   target="_blank" 
                                                   class="btn btn-sm btn-outline-success receipt-btn">
                                                    <i class="fas fa-print me-1"></i>Reçu
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Toutes les mensualités (caché par défaut) -->
                    <div id="allPayments" style="display: none;">
                        <h6><i class="fas fa-list me-1"></i> Tous les paiements</h6>
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th><i class="fas fa-calendar me-1"></i> Mois</th>
                                        <th><i class="fas fa-coins me-1"></i> Montant</th>
                                        <th><i class="fas fa-clock me-1"></i> Date paiement</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $result_mensualites->data_seek(0); // Réinitialiser le pointeur
                                    while ($m = $result_mensualites->fetch_assoc()): ?>
                                        <tr>
                                            <td><?= ucfirst(htmlspecialchars($m['mois'])) ?></td>
                                            <td><?= number_format($m['montant'], 0, ',', ' ') ?> F CFA</td>
                                            <td><?= formatDateFr($m['date_paiement']) ?></td>
                                            <td class="text-end">
                                                <a href="recu_inscription.php?id=<?= $m['id'] ?>" 
                                                   target="_blank" 
                                                   class="btn btn-sm btn-outline-success receipt-btn">
                                                    <i class="fas fa-print me-1"></i>Reçu
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>Aucune mensualité enregistrée pour le moment.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert et Font Awesome -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<script>
function confirmerPaiement() {
    Swal.fire({
        title: 'Confirmer le paiement ?',
        html: `<p>Vous êtes sur le point d'enregistrer le paiement de l'inscription pour :</p>
              <p class="fw-bold"><?= htmlspecialchars($student['prenom'] . ' ' . $student['noms']) ?></p>
              <p class="text-success fw-bold">Montant : 10 000 F CFA</p>`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: '<i class="fas fa-check me-1"></i> Confirmer',
        cancelButtonText: '<i class="fas fa-times me-1"></i> Annuler',
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#dc3545'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('formInscription').submit();
        }
    });
}

function toggleLastPayments() {
    document.getElementById('lastPayments').style.display = 'block';
    document.getElementById('allPayments').style.display = 'none';
}

function toggleAllPayments() {
    document.getElementById('lastPayments').style.display = 'none';
    document.getElementById('allPayments').style.display = 'block';
}
</script>

<?php include('includes/footer.php'); ?>