<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
$userprofil = $_SESSION['user'];
if (!$userprofil) {
    header("Location: login.php");
    exit();
}

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

$afficher_confirmation = false;
$afficher_recu = false;
$erreur = "";

// Récupération des classes et niveaux pour le formulaire
$classes = mysqli_query($conn, "SELECT * FROM classes");
$niveaux = mysqli_query($conn, "SELECT * FROM niveaux");

// Étape 1 : traitement inscription
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["etape"]) && $_POST["etape"] === "1") {
    $prenom = $_POST["prenom"];
    $nom = $_POST["nom"];
    $date = $_POST["date_de_naissance"];
    $lieu = $_POST["lieu_de_naissance"];
    $adresse = $_POST["adresse"];
    $phone = $_POST["phone"];
    $nationalite = $_POST["nationalite"];
    $tutor_num = $_POST["tutor_num"];
    $tutor_adresse = $_POST["tutor_adress"];
    $classe_id = $_POST["classe_id"];
    $niveau_id = $_POST["niveau_id"];
    $annee = $_POST["annee_academique"];
    
    // Gestion de la photo (webcam ou upload)
    $photo = '';
    if (!empty($_POST['webcam_image'])) {
        // Traitement de l'image webcam
        $imageData = $_POST['webcam_image'];
        
        if (preg_match('/^data:image\/(\w+);base64,/', $imageData, $type)) {
            $imageData = substr($imageData, strpos($imageData, ',') + 1);
            $type = strtolower($type[1]); // jpg, png, gif
            
            if (in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
                $imageData = base64_decode($imageData);
                
                if ($imageData !== false) {
                    $filename = 'student_' . time() . '.' . $type;
                    $filepath = 'studentimages/' . $filename;
                    
                    if (file_put_contents($filepath, $imageData)) {
                        $photo = $filename;
                    } else {
                        $erreur = "Erreur lors de l'enregistrement de la photo";
                    }
                }
            }
        }
    } elseif (!empty($_FILES["photo"]["name"])) {
        // Traitement de l'upload classique
        $photo = $_FILES["photo"]["name"];
        move_uploaded_file($_FILES["photo"]["tmp_name"], "studentimages/" . $photo);
    }

    // Validation de l'année académique
    if (!preg_match('/^\d{4}-\d{4}$/', $annee)) {
        $erreur = "Format d'année académique invalide. Format attendu : YYYY-YYYY";
    }

    if (empty($erreur)) {
        function generermatricule() {
            return substr(str_shuffle("0123456789"), 0, 6) . substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 2);
        }
        $matricule = generermatricule();

        // Correction de l'ordre des champs pour l'année académique
        $sql = "INSERT INTO etudiants (
            prenom, noms, date_de_naissance, lieu_de_naissance, adresse, phone,
            nationnalite, tutor_num, adresse_tutor, annee_academique, photo, matricule, classe_id, niveau
        ) VALUES (
            '".mysqli_real_escape_string($conn,$prenom)."',
            '".mysqli_real_escape_string($conn,$nom)."',
            '".mysqli_real_escape_string($conn,$date)."',
            '".mysqli_real_escape_string($conn,$lieu)."',
            '".mysqli_real_escape_string($conn,$adresse)."',
            '".mysqli_real_escape_string($conn,$phone)."',
            '".mysqli_real_escape_string($conn,$nationalite)."',
            '".mysqli_real_escape_string($conn,$tutor_num)."',
            '".mysqli_real_escape_string($conn,$tutor_adresse)."',
            '".mysqli_real_escape_string($conn,$annee)."',
            '".mysqli_real_escape_string($conn,$photo)."',
            '".mysqli_real_escape_string($conn,$matricule)."',
            ".intval($classe_id).",
            ".intval($niveau_id)."
        )";

        if (mysqli_query($conn, $sql)) {
            $etudiant_id = mysqli_insert_id($conn);
            $_SESSION["etudiant_id"] = $etudiant_id;
            $_SESSION["matricule"] = $matricule;
            $_SESSION["prenom"] = $prenom;
            $_SESSION["nom"] = $nom;
            $_SESSION["classe"] = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nom FROM classes WHERE id=".intval($classe_id)))["nom"];
            $_SESSION["niveau"] = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nom_niveau FROM niveaux WHERE id=".intval($niveau_id)))["nom_niveau"];
            $_SESSION["annee"] = $annee;

            $afficher_confirmation = true;
        } else {
            $erreur = "Erreur lors de l'enregistrement de l'étudiant: " . mysqli_error($conn);
        }
    }
}

// Étape 2 : traitement confirmation + paiement
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["etape"]) && $_POST["etape"] === "2") {
    $etudiant_id = $_SESSION["etudiant_id"];
    $montant = floatval($_POST["montant"]);
    $mois = "Inscription";
    $date_paiement = date("Y-m-d");
    $annee = $_SESSION["annee"];

    $annee_courante = date("Y");
    $result = mysqli_query($conn, "SELECT numero_recu FROM recu_inscription WHERE numero_recu LIKE 'REC$annee_courante%' ORDER BY id DESC LIMIT 1");
    if ($row = mysqli_fetch_assoc($result)) {
        $dernier_num = $row['numero_recu'];
        $num = intval(substr($dernier_num, 7)) + 1;
    } else {
        $num = 1;
    }
    $numero_recu = "REC" . $annee_courante . str_pad($num, 4, "0", STR_PAD_LEFT);

    $sql = "INSERT INTO mensualites (etudiant_id, mois, montant, date_paiement)
            VALUES ($etudiant_id, '$mois', $montant, '$date_paiement')";

    if (mysqli_query($conn, $sql)) {
        $sql_recu = "INSERT INTO recu_inscription (etudiant_id, numero_recu, date_emission)
                     VALUES ($etudiant_id, '$numero_recu', '$date_paiement')";
        mysqli_query($conn, $sql_recu);

        $_SESSION["montant"] = $montant;
        $_SESSION["numero_recu"] = $numero_recu;
        $afficher_recu = true;
    } else {
        $erreur = "Erreur lors de l'enregistrement du montant: " . mysqli_error($conn);
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8" />
    <title>Inscription Étudiant - E3S</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <style>
        :root {
            --primary-teal: #008080;
            --secondary-teal: #20B2AA;
            --light-teal: #E0F7FA;
            --dark-teal: #006666;
            --light-gray: #f8f9fa;
        }
        
        body {
            background-color: var(--light-gray);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        /* Styles pour le formulaire */
        .form-container {
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 128, 128, 0.1);
            overflow: hidden;
            border: none;
            background-color: white;
        }
        
        .form-header {
            background: linear-gradient(135deg, var(--primary-teal), var(--secondary-teal));
            color: white;
            padding: 1.5rem;
            border-bottom: 4px solid var(--dark-teal);
        }
        
        .form-body {
            padding: 2rem;
        }
        
        .form-label {
            font-weight: 500;
            color: var(--dark-teal);
        }
        
        .form-control, .form-select {
            border-radius: 5px;
            border: 1px solid #ced4da;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-teal);
            box-shadow: 0 0 0 0.25rem rgba(0, 128, 128, 0.25);
        }
        
        /* Styles pour les boutons */
        .btn-teal {
            background-color: var(--primary-teal);
            color: white;
            border-color: var(--primary-teal);
        }
        
        .btn-teal:hover {
            background-color: var(--dark-teal);
            border-color: var(--dark-teal);
            color: white;
        }
        
        .btn-outline-teal {
            color: var(--primary-teal);
            border-color: var(--primary-teal);
        }
        
        .btn-outline-teal:hover {
            background-color: var(--primary-teal);
            color: white;
        }
        
        /* Indicateur d'étapes */
        .step-indicator {
            position: relative;
            padding-bottom: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .step-indicator::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            height: 4px;
            background-color: #e9ecef;
            z-index: 1;
        }
        
        .step-indicator .step {
            position: relative;
            z-index: 2;
            text-align: center;
        }
        
        .step-indicator .step .step-number {
            width: 40px;
            height: 40px;
            line-height: 40px;
            border-radius: 50%;
            background-color: #e9ecef;
            color: #6c757d;
            display: inline-block;
            margin-bottom: 0.5rem;
            font-weight: bold;
        }
        
        .step-indicator .step.active .step-number {
            background-color: var(--primary-teal);
            color: white;
        }
        
        .step-indicator .step.completed .step-number {
            background-color: var(--secondary-teal);
            color: white;
        }
        
        .step-indicator .step .step-label {
            font-size: 0.85rem;
            color: #6c757d;
            font-weight: 500;
        }
        
        .step-indicator .step.active .step-label,
        .step-indicator .step.completed .step-label {
            color: var(--primary-teal);
            font-weight: 600;
        }
        
        /* Styles pour les modals */
        .modal-header.teal {
            background: linear-gradient(135deg, var(--primary-teal), var(--secondary-teal));
            color: white;
        }
        
        /* Styles pour les reçus */
        .receipt-container {
            border: 2px solid var(--primary-teal);
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 128, 128, 0.1);
            background: white;
            overflow: hidden;
        }
        
        .receipt-header {
            background: linear-gradient(135deg, var(--primary-teal), var(--secondary-teal));
            color: white;
            padding: 1rem;
            border-bottom: 3px solid var(--dark-teal);
        }
        
        .table-teal thead th {
            background-color: var(--primary-teal);
            color: white;
        }
        
        .badge-teal {
            background-color: var(--secondary-teal);
            color: white;
            font-weight: 500;
        }
        
        /* Styles pour la webcam */
        .webcam-container {
            position: relative;
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
        }
        
        #webcam {
            width: 100%;
            background-color: #f0f0f0;
            border-radius: 8px;
        }
        
        #canvas {
            display: none;
        }
        
        .webcam-controls {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }
        
        .webcam-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .webcam-btn-primary {
            background-color: var(--primary-teal);
            color: white;
        }
        
        .webcam-btn-danger {
            background-color: #e74c3c;
            color: white;
        }
        
        .webcam-btn-success {
            background-color: #2ecc71;
            color: white;
        }
        
        .webcam-btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
        
        .photo-options {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            border-top: 1px solid #eee;
            padding-top: 20px;
        }
        
        .photo-tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        
        .photo-tab {
            padding: 10px 20px;
            cursor: pointer;
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-bottom: none;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
        }
        
        .photo-tab.active {
            background: var(--primary-teal);
            color: white;
            border-color: var(--primary-teal);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .preview-image {
            max-width: 100%;
            max-height: 300px;
            border-radius: 8px;
            margin: 0 auto;
            display: block;
        }
        
        /* Styles d'impression */
        @media print {
            .no-print {
                display: none !important;
            }
            
            body, html {
                margin: 0; 
                padding: 0; 
                height: 297mm; 
                width: 210mm; 
                background: white;
            }
            
            .print-area {
                width: 190mm; 
                margin: auto; 
                background-color: white !important; 
                padding: 20px; 
                box-sizing: border-box;
            }
            
            .btn {
                display: none !important;
            }
            
            .watermark {
                position: absolute;
                opacity: 0.1;
                font-size: 80px;
                transform: rotate(-45deg);
                z-index: -1;
                top: 30%;
                left: 10%;
                white-space: nowrap;
            }
            
            .bg-teal, .bg-teal > th, .bg-teal > td {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                background-color: var(--primary-teal) !important;
                color: white !important;
            }
            
            .text-teal {
                color: var(--primary-teal) !important;
            }
            
            .border-teal {
                border-color: var(--primary-teal) !important;
            }
            
            .bg-light-teal {
                background-color: var(--light-teal) !important;
            }
        }
    </style>
</head>
<body>
<div class="container py-5">

    <?php if ($erreur): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle me-2"></i>
            <?= htmlspecialchars($erreur) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Formulaire inscription classique -->
    <?php if (!$afficher_confirmation && !$afficher_recu): ?>
    <div class="form-container mx-auto" style="max-width: 900px;">
        <div class="form-header text-center">
            <h4><i class="fas fa-user-graduate me-2"></i>Inscription Étudiant</h4>
        </div>
        
        <div class="form-body">
            <!-- Indicateur d'étape -->
            <div class="step-indicator d-flex justify-content-between mb-4">
                <div class="step active">
                    <div class="step-number">1</div>
                    <div class="step-label">Informations</div>
                </div>
                <div class="step">
                    <div class="step-number">2</div>
                    <div class="step-label">Confirmation</div>
                </div>
                <div class="step">
                    <div class="step-number">3</div>
                    <div class="step-label">Paiement</div>
                </div>
            </div>
            
            <form method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
                <input type="hidden" name="etape" value="1" />
                <input type="hidden" name="webcam_image" id="webcam-image-data" />

                <div class="row">
                    <div class="col-md-4 col-12 mb-3">
                        <label for="prenom" class="form-label">Prénom <span class="text-danger">*</span></label>
                        <input type="text" id="prenom" name="prenom" class="form-control" required />
                        <div class="invalid-feedback">Veuillez saisir le prénom.</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="nom" class="form-label">Nom <span class="text-danger">*</span></label>
                        <input type="text" id="nom" name="nom" class="form-control" required />
                        <div class="invalid-feedback">Veuillez saisir le nom.</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="date_de_naissance" class="form-label">Date de naissance <span class="text-danger">*</span></label>
                        <input type="date" id="date_de_naissance" name="date_de_naissance" class="form-control" required />
                        <div class="invalid-feedback">Veuillez saisir la date de naissance.</div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4 col-12 mb-3">
                        <label for="lieu_de_naissance" class="form-label">Lieu de naissance <span class="text-danger">*</span></label>
                        <input type="text" id="lieu_de_naissance" name="lieu_de_naissance" class="form-control" required />
                        <div class="invalid-feedback">Veuillez saisir le lieu de naissance.</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="adresse" class="form-label">Adresse <span class="text-danger">*</span></label>
                        <input type="text" id="adresse" name="adresse" class="form-control" required />
                        <div class="invalid-feedback">Veuillez saisir l'adresse.</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="phone" class="form-label">Téléphone <span class="text-danger">*</span></label>
                        <input type="tel" id="phone" name="phone" class="form-control" required pattern="\d{8,15}" />
                        <div class="invalid-feedback">Veuillez saisir un numéro valide (8 à 15 chiffres).</div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4 col-12 mb-3">
                        <label for="nationalite" class="form-label">Nationalité <span class="text-danger">*</span></label>
                        <input type="text" id="nationalite" name="nationalite" class="form-control" required />
                        <div class="invalid-feedback">Veuillez saisir la nationalité.</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="tutor_num" class="form-label">Numéro tuteur <span class="text-danger">*</span></label>
                        <input type="tel" id="tutor_num" name="tutor_num" class="form-control" required pattern="\d{8,15}" />
                        <div class="invalid-feedback">Veuillez saisir un numéro valide (8 à 15 chiffres).</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="tutor_adress" class="form-label">Adresse tuteur <span class="text-danger">*</span></label>
                        <input type="text" id="tutor_adress" name="tutor_adress" class="form-control" required />
                        <div class="invalid-feedback">Veuillez saisir l'adresse du tuteur.</div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4 col-12 mb-3">
                        <label for="annee_academique" class="form-label">Année académique <span class="text-danger">*</span></label>
                        <input type="text" id="annee_academique" name="annee_academique" class="form-control" 
                               value="<?= date('Y') . '-' . (date('Y')+1) ?>" required pattern="\d{4}-\d{4}" />
                        <div class="invalid-feedback">Format attendu : YYYY-YYYY.</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="classe_id" class="form-label">Classe <span class="text-danger">*</span></label>
                        <select name="classe_id" id="classe_id" class="form-select" required>
                            <option value="">Sélectionnez une classe</option>
                            <?php mysqli_data_seek($classes, 0);
                            while ($row = mysqli_fetch_assoc($classes)): ?>
                                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['nom']) ?></option>
                            <?php endwhile; ?>
                        </select>
                        <div class="invalid-feedback">Veuillez sélectionner une classe.</div>
                    </div>
                    <div class="col-md-4 col-12 mb-3">
                        <label for="niveau_id" class="form-label">Niveau <span class="text-danger">*</span></label>
                        <select name="niveau_id" id="niveau_id" class="form-select" required>
                            <option value="">Sélectionnez un niveau</option>
                            <?php mysqli_data_seek($niveaux, 0);
                            while ($row = mysqli_fetch_assoc($niveaux)): ?>
                                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['nom_niveau']) ?></option>
                            <?php endwhile; ?>
                        </select>
                        <div class="invalid-feedback">Veuillez sélectionner un niveau.</div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Photo de l'étudiant</label>
                        
                        <!-- Onglets pour choisir la méthode -->
                        <div class="photo-tabs mb-4">
                            <div class="photo-tab active" onclick="switchTab('webcam')">
                                <i class="fas fa-camera me-1"></i> Prendre une photo
                            </div>
                            <div class="photo-tab" onclick="switchTab('upload')">
                                <i class="fas fa-upload me-1"></i> Uploader une photo
                            </div>
                        </div>
                        
                        <!-- Contenu Webcam -->
                        <div id="webcam-tab" class="tab-content active">
                            <div class="webcam-container">
                                <video id="webcam" autoplay playsinline></video>
                                <canvas id="canvas"></canvas>
                                
                                <div class="webcam-controls">
                                    <button type="button" id="capture-btn" class="webcam-btn webcam-btn-primary">
                                        <i class="fas fa-camera me-1"></i> Capturer
                                    </button>
                                    <button type="button" id="retake-btn" class="webcam-btn webcam-btn-danger" style="display:none;">
                                        <i class="fas fa-redo me-1"></i> Reprendre
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Contenu Upload -->
                        <div id="upload-tab" class="tab-content">
                            <div class="mb-3">
                                <label for="photo-upload" class="form-label">Sélectionner une image</label>
                                <input class="form-control" type="file" id="photo-upload" name="photo" accept="image/*">
                            </div>
                            <div class="text-center">
                                <button type="button" class="btn btn-outline-teal" onclick="previewUpload()">
                                    <i class="fas fa-eye me-1"></i> Prévisualiser
                                </button>
                            </div>
                        </div>
                        
                        <!-- Prévisualisation -->
                        <div id="preview-container" class="photo-options" style="display:none;">
                            <h6 class="text-center mb-3">Prévisualisation</h6>
                            <img id="preview-image" class="preview-image" src="" alt="Preview">
                        </div>
                    </div>
                </div>

                <div class="d-grid mt-4">
                    <button type="submit" class="btn btn-teal btn-lg">
                        <i class="fas fa-arrow-right me-2"></i>Étape suivante - Confirmation
                    </button>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <!-- Modal Confirmation étape 2 -->
    <?php if ($afficher_confirmation): ?>
        <!-- Modal -->
        <div class="modal fade show" id="modalConfirmation" tabindex="-1" style="display:block;" aria-modal="true" role="dialog">
            <div class="modal-dialog modal-lg">
                <form method="POST" class="modal-content needs-validation" novalidate>
                    <input type="hidden" name="etape" value="2" />
                    <div class="modal-header teal">
                        <h5 class="modal-title"><i class="fas fa-check-circle me-2"></i>Confirmation des informations</h5>
                        <button type="button" class="btn-close btn-close-white" onclick="fermerModal('modalConfirmation')"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>Veuillez vérifier les informations avant de procéder au paiement.
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card mb-3 border-teal">
                                    <div class="card-header bg-light-teal">
                                        <h6 class="mb-0 text-teal"><i class="fas fa-user me-2"></i>Informations étudiant</h6>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>Prénom :</strong> <?= htmlspecialchars($_SESSION["prenom"]) ?></p>
                                        <p><strong>Nom :</strong> <?= htmlspecialchars($_SESSION["nom"]) ?></p>
                                        <p><strong>Classe :</strong> <?= htmlspecialchars($_SESSION["classe"]) ?></p>
                                        <p><strong>Niveau :</strong> <?= htmlspecialchars($_SESSION["niveau"]) ?></p>
                                        <p><strong>Année Académique :</strong> <?= htmlspecialchars($_SESSION["annee"]) ?></p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card border-teal">
                                    <div class="card-header bg-light-teal">
                                        <h6 class="mb-0 text-teal"><i class="fas fa-money-bill-wave me-2"></i>Paiement</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="montant" class="form-label">Montant à payer (FCFA) <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <span class="input-group-text">FCFA</span>
                                                <input type="number" id="montant" name="montant" class="form-control" required min="0" step="100" />
                                            </div>
                                            <div class="invalid-feedback">Veuillez saisir un montant valide (minimum 1000 FCFA).</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" onclick="fermerModal('modalConfirmation')">
                            <i class="fas fa-times me-2"></i>Annuler
                        </button>
                        <button type="submit" class="btn btn-teal">
                            <i class="fas fa-check me-2"></i>Confirmer et payer
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <script>
            // Affiche modal automatiquement
            window.onload = () => {
                let modal = new bootstrap.Modal(document.getElementById('modalConfirmation'));
                modal.show();
            };
            // Fonction pour fermer modal et reload page
            function fermerModal(id) {
                let modal = bootstrap.Modal.getInstance(document.getElementById(id));
                if(modal) modal.hide();
                // Recharge la page pour repartir à zéro
                window.location.href = window.location.pathname;
            }

            (() => {
                'use strict';
                const form = document.querySelector('.modal-content.needs-validation');
                form.addEventListener('submit', event => {
                    if (!form.checkValidity()) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    form.classList.add('was-validated');
                });
            })();
        </script>
    <?php endif; ?>

    <!-- Modal Reçu -->
    <?php if ($afficher_recu): ?>
        <div class="modal fade show" id="modalRecu" tabindex="-1" style="display:block;" aria-modal="true" role="dialog">
            <div class="modal-dialog modal-xl modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header no-print teal">
                        <h5 class="modal-title"><i class="fas fa-receipt me-2"></i>Reçu d'inscription</h5>
                        <button type="button" class="btn-close btn-close-white" onclick="fermerModalRecu()"></button>
                    </div>
                    <div class="modal-body">
                        <div class="print-area d-flex justify-content-between" id="recuContent" style="gap: 20px;">
                            <!-- Premier reçu -->
                            <div class="receipt-container">
                                <!-- En-tête -->
                                <div class="receipt-header d-flex justify-content-between align-items-center">
                                    <div>
                                        <img src="assetss/logo.png" alt="Logo École" class="img-fluid" style="max-height: 80px;">
                                    </div>
                                    <div class="text-end">
                                        <h4 class="mb-1 fw-bold text-white">MAIN IT CENTER</h4></h4>
                                        <p class="mb-0 small text-white">Kaolack Niary Tally près de la pharmacie du Lycée</p>
                                        <p class="small text-white">Tél: +221 77 500 73 54</p>
                                    </div>
                                </div>
                                
                                <!-- Corps du reçu -->
                                <div class="p-4">
                                    <!-- Titre -->
                                    <div class="text-center mb-3">
                                        <h5 class="text-teal fw-bold mb-1">REÇU D'INSCRIPTION</h5>
                                        <p class="text-muted small mb-0">N°: <?= htmlspecialchars($_SESSION["numero_recu"]) ?></p>
                                    </div>
                                    
                                    <!-- Informations étudiant -->
                                    <div class="table-responsive mb-3">
                                        <table class="table table-sm table-bordered">
                                            <tbody>
                                                <tr>
                                                    <td class="w-40 bg-light-teal fw-bold text-teal">Matricule</td>
                                                    <td><?= htmlspecialchars($_SESSION["matricule"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Nom & Prénom</td>
                                                    <td><?= htmlspecialchars($_SESSION["nom"]) ?> <?= htmlspecialchars($_SESSION["prenom"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Classe/Niveau</td>
                                                    <td><?= htmlspecialchars($_SESSION["classe"]) ?> / <?= htmlspecialchars($_SESSION["niveau"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Année scolaire</td>
                                                    <td><?= htmlspecialchars($_SESSION["annee"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Date</td>
                                                    <td><?= date("d/m/Y") ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Paiement -->
                                    <div class="table-responsive mb-3">
                                        <table class="table table-sm">
                                            <thead class="bg-teal text-white">
                                                <tr>
                                                    <th>Désignation</th>
                                                    <th class="text-end">Montant</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>Frais d'inscription</td>
                                                    <td class="text-end"><?= number_format($_SESSION["montant"], 0, ',', ' ') ?> FCFA</td>
                                                </tr>
                                                <tr class="fw-bold">
                                                    <td>TOTAL</td>
                                                    <td class="text-end"><?= number_format($_SESSION["montant"], 0, ',', ' ') ?> FCFA</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- QR Code + Signature -->
                                    <div class="d-flex justify-content-between mt-4">
                                        <div class="text-center">
                                            <img src="https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=<?= urlencode(
                                                "E3S SANTÉ\n".
                                                "Reçu: ".$_SESSION["numero_recu"]."\n".
                                                "Étudiant: ".$_SESSION["nom"]." ".$_SESSION["prenom"]."\n".
                                                "Montant: ".number_format($_SESSION["montant"], 0, ',', ' ')." FCFA\n".
                                                "Date: ".date("d/m/Y")
                                            ) ?>" alt="QR Code" class="border p-1" width="100">
                                            <p class="small text-muted mt-1">Scanner pour vérification</p>
                                        </div>
                                        
                                        <div class="text-center" style="width: 150px;">
                                            <p class="small text-muted mb-5">Le Caissier</p>
                                            <div class="border-top border-teal pt-1">
                                                <p class="small text-muted mb-0">Signature et cachet</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Pied de page -->
                                    <div class="text-center mt-3">
                                        <p class="small text-teal mb-0">
                                            <i class="fas fa-shield-alt me-1"></i>
                                            Document officiel - Ne pas jeter
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Deuxième reçu (copie) -->
                            <div class="receipt-container">
                                <!-- En-tête -->
                                <div class="receipt-header d-flex justify-content-between align-items-center">
                                    <div>
                                        <img src="assetss/logo.png" alt="Logo École" class="img-fluid" style="max-height: 80px;">
                                    </div>
                                    <div class="text-end">
                                        <h4 class="mb-1 fw-bold text-white">MAIN IT CENTER</h4></h4>
                                        <p class="mb-0 small text-white">Kaolack, Leona Lot 167</p>
                                        <p class="small text-white">Tél: +221 77 500 73 54</p>
                                    </div>
                                </div>
                                
                                <!-- Corps du reçu -->
                                <div class="p-4">
                                    <!-- Titre -->
                                    <div class="text-center mb-3">
                                        <h5 class="text-teal fw-bold mb-1">REÇU D'INSCRIPTION</h5>
                                        <p class="text-muted small mb-0">N°: <?= htmlspecialchars($_SESSION["numero_recu"]) ?> (Copie)</p>
                                    </div>
                                    
                                    <!-- Informations étudiant -->
                                    <div class="table-responsive mb-3">
                                        <table class="table table-sm table-bordered">
                                            <tbody>
                                                <tr>
                                                    <td class="w-40 bg-light-teal fw-bold text-teal">Matricule</td>
                                                    <td><?= htmlspecialchars($_SESSION["matricule"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Nom & Prénom</td>
                                                    <td><?= htmlspecialchars($_SESSION["nom"]) ?> <?= htmlspecialchars($_SESSION["prenom"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Classe/Niveau</td>
                                                    <td><?= htmlspecialchars($_SESSION["classe"]) ?> / <?= htmlspecialchars($_SESSION["niveau"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Année scolaire</td>
                                                    <td><?= htmlspecialchars($_SESSION["annee"]) ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="bg-light-teal fw-bold text-teal">Date</td>
                                                    <td><?= date("d/m/Y") ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Paiement -->
                                    <div class="table-responsive mb-3">
                                        <table class="table table-sm">
                                            <thead class="bg-teal text-white">
                                                <tr>
                                                    <th>Désignation</th>
                                                    <th class="text-end">Montant</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>Frais d'inscription</td>
                                                    <td class="text-end"><?= number_format($_SESSION["montant"], 0, ',', ' ') ?> FCFA</td>
                                                </tr>
                                                <tr class="fw-bold">
                                                    <td>TOTAL</td>
                                                    <td class="text-end"><?= number_format($_SESSION["montant"], 0, ',', ' ') ?> FCFA</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- QR Code + Signature -->
                                    <div class="d-flex justify-content-between mt-4">
                                        <div class="text-center">
                                            <img src="https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=<?= urlencode(
                                                "E3S SANTÉ\n".
                                                "Reçu: ".$_SESSION["numero_recu"]."\n".
                                                "Étudiant: ".$_SESSION["nom"]." ".$_SESSION["prenom"]."\n".
                                                "Montant: ".number_format($_SESSION["montant"], 0, ',', ' ')." FCFA\n".
                                                "Date: ".date("d/m/Y")
                                            ) ?>" alt="QR Code" class="border p-1" width="100">
                                            <p class="small text-muted mt-1">Scanner pour vérification</p>
                                        </div>
                                        
                                        <div class="text-center" style="width: 150px;">
                                            <p class="small text-muted mb-5">Le Caissier</p>
                                            <div class="border-top border-teal pt-1">
                                                <p class="small text-muted mb-0">Signature et cachet</p>
                                            </div>
                                    </div>
                                </div>
                                
                                <!-- Pied de page -->
                                <div class="text-center mt-3">
                                    <p class="small text-teal mb-0">
                                        <i class="fas fa-shield-alt me-1"></i>
                                        Document officiel - Ne pas jeter
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer no-print">
                    <button onclick="printRecu()" class="btn btn-teal">
                        <i class="fas fa-print me-2"></i>Imprimer
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="fermerModalRecu()">
                        <i class="fas fa-times me-2"></i>Fermer
                    </button>
                </div>
            </div>
        </div>

        <script>
            function printRecu() {
                const originalContent = document.body.innerHTML;
                const printContent = document.getElementById('recuContent').innerHTML;
                
                document.body.innerHTML = `
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>Reçu d'inscription</title>
                        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
                        <style>
                            @page {
                                size: A4 landscape;
                                margin: 5mm;
                            }
                            body {
                                width: 297mm;
                                height: 210mm;
                                padding: 9px;
                                font-family: Arial, sans-serif;
                            }
                            .receipt-container {
                                width: 49%;
                                page-break-inside: avoid;
                                border: 2px solid #008080;
                                border-radius: 8px;
                                padding:10px;
                            }
                            .bg-teal, .bg-teal > th, .bg-teal > td {
                                -webkit-print-color-adjust: exact;
                                print-color-adjust: exact;
                                background-color: #008080 !important;
                                color: white !important;
                            }
                            .text-teal {
                                color: #008080 !important;
                            }
                            .border-teal {
                                border-color: #008080 !important;
                            }
                            .bg-light-teal {
                                background-color: #E0F7FA !important;
                            }
                        </style>
                    </head>
                    <body>
                        <div class="print-area d-flex justify-content-between">
                            ${printContent}
                        </div>
                    </body>
                    </html>
                `;
                
                window.print();
                document.body.innerHTML = originalContent;
                
                // Réaffiche le modal après impression
                let modalElement = document.getElementById('modalRecu');
                let modal = new bootstrap.Modal(modalElement);
                modal.show();
            }

            function fermerModalRecu() {
                const modal = document.getElementById('modalRecu');
                modal.classList.remove('show');
                modal.style.display = 'none';
                document.body.classList.remove('modal-open');
                document.querySelector('.modal-backdrop')?.remove();

                setTimeout(() => {
                    window.location.href = window.location.pathname;
                }, 300);
            }
        </script>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Validation du formulaire
    (() => {
        'use strict';
        const forms = document.querySelectorAll('.needs-validation');
        
        Array.from(forms).forEach(form => {
            form.addEventListener('submit', event => {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            });
        });
    })();

    // Variables globales pour la webcam
    let streaming = false;
    let video = document.getElementById('webcam');
    let canvas = document.getElementById('canvas');
    let captureBtn = document.getElementById('capture-btn');
    let retakeBtn = document.getElementById('retake-btn');
    let previewContainer = document.getElementById('preview-container');
    let previewImage = document.getElementById('preview-image');
    let webcamImageData = document.getElementById('webcam-image-data');

    // Basculer entre les onglets
    function switchTab(tab) {
        document.querySelectorAll('.photo-tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        
        if (tab === 'webcam') {
            document.querySelector('.photo-tab:nth-child(1)').classList.add('active');
            document.getElementById('webcam-tab').classList.add('active');
            startWebcam();
        } else {
            document.querySelector('.photo-tab:nth-child(2)').classList.add('active');
            document.getElementById('upload-tab').classList.add('active');
            stopWebcam();
        }
    }

    // Démarrer la webcam
    function startWebcam() {
        navigator.mediaDevices.getUserMedia({ video: true, audio: false })
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
                streaming = true;
            })
            .catch(function(err) {
                console.error("Erreur webcam: ", err);
                Swal.fire({
                    icon: 'error',
                    title: 'Erreur webcam',
                    text: 'Impossible d\'accéder à la webcam. Veuillez vérifier les permissions.',
                    confirmButtonText: 'OK'
                });
            });
    }

    // Arrêter la webcam
    function stopWebcam() {
        if (video.srcObject) {
            video.srcObject.getTracks().forEach(track => track.stop());
        }
        streaming = false;
    }

    // Capturer une image
    captureBtn.addEventListener('click', function() {
        if (!streaming) return;
        
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // Afficher la prévisualisation
        let imageData = canvas.toDataURL('image/png');
        previewImage.src = imageData;
        webcamImageData.value = imageData;
        previewContainer.style.display = 'block';
        
        // Changer les boutons
        captureBtn.style.display = 'none';
        retakeBtn.style.display = 'block';
    });

    // Reprendre une photo
    retakeBtn.addEventListener('click', function() {
        previewContainer.style.display = 'none';
        captureBtn.style.display = 'block';
        retakeBtn.style.display = 'none';
    });

    // Prévisualiser l'image uploadée
    function previewUpload() {
        let fileInput = document.getElementById('photo-upload');
        let file = fileInput.files[0];
        
        if (!file) {
            Swal.fire({
                icon: 'warning',
                title: 'Aucun fichier',
                text: 'Veuillez sélectionner une image à uploader',
                confirmButtonText: 'OK'
            });
            return;
        }
        
        if (!file.type.match('image.*')) {
            Swal.fire({
                icon: 'error',
                title: 'Format invalide',
                text: 'Veuillez sélectionner un fichier image valide',
                confirmButtonText: 'OK'
            });
            return;
        }
        
        let reader = new FileReader();
        reader.onload = function(e) {
            previewImage.src = e.target.result;
            previewContainer.style.display = 'block';
            
            // Convertir en base64 pour l'envoi si on veut utiliser cette méthode
            let img = new Image();
            img.onload = function() {
                canvas.width = img.width;
                canvas.height = img.height;
                let ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0);
                
                webcamImageData.value = canvas.toDataURL('image/png');
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    // Démarrer la webcam au chargement si l'onglet est actif
    document.addEventListener('DOMContentLoaded', function() {
        if (document.getElementById('webcam-tab').classList.contains('active')) {
            startWebcam();
        }
    });

    // Arrêter la webcam quand on quitte la page
    window.addEventListener('beforeunload', function() {
        stopWebcam();
    });
</script>
</body>
</html>