

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File d'attente STI2D</title>

    <!-- Google Fonts pour une meilleure police -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
    
    <!-- Firebase -->
    <script src="https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/11.1.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/11.1.0/firebase-firestore.js"></script>
    
    <style>
        /* Réinitialisation de base */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Roboto', sans-serif;
        }

        .hidden {
    display: none;
}
        body {
            background-color: #f5f5f5;
            background-image: url('Buisson.jpg');
            background-size: cover;
            background-position: center;
            color: #333;
            line-height: 1.6;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }

        /* Conteneur principal */
        #client-container {
            background: rgba(255, 255, 255, 0.90);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            border-radius: 12px;
            padding: 20px;
            width: 90%;
            max-width: 1000px;
            overflow-y: auto;
        }

        /* Titres */
        h1, h2 {
            text-align: center;
            color: #444;
        }

        /* Formulaire */
        form {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        label {
            font-weight: 500;
        }

        input, select, button {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 6px;
            font-size: 16px;
        }

        button {
            background-color: #4CAF50;
            color: #fff;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #45a049;
        }

        /* Tableau */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        table th, table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
        }

        table th {
            background-color: #4CAF50;
            color: white;
        }

        table td {
            background-color: #f9f9f9;
        }

        table button {
            padding: 5px 10px;
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        table button:hover {
            background-color: #e53935;
        }

        /* Bouton Déconnexion */
        #logout-client {
            display: block;
            width: 100%;
            margin-top: 20px;
            background-color: #f44336;
        }

        #logout-client:hover {
            background-color: #e53935;
        }

        /* Responsive */
        @media (max-width: 768px) {
            table {
                font-size: 12px;
            }

            input, select, button {
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
    <div id="client-container" class="hidden">
        <div id="welcome-container">
            <h1>Bienvenue, <span id="nom-client"></span></h1>
        </div>
        <div class="container">
            <div class="form-container">
                <form method="post" id="ticket-form">
                    <label for="student-name">Votre nom :</label>
                    <input type="text" id="student-name" name="nom" disabled>
                    <label for="professeur">Choisir un professeur :</label>
                    <select id="professeur" name="prof" required>
                        <option value="Mr Fouques">Mr Fouques</option>
                        <option value="Mr Metay">Mr Metay</option>
                        <option value="Mr Fosset">Mr Fosset</option>
                        <option value="Mr Flandin">Mr Flandin</option>
                        <option value="N'importe qui">N'importe qui</option>
                    </select>
                    <button type="submit" id="submit">Envoyer la demande</button>
                </form>
                <div id="anti-spam-message" class="hidden" style="color: red; margin-top: 10px;">
                    Vous devez attendre 30 secondes avant de soumettre une nouvelle demande.
                </div>
            </div>
            
            <div class="demande-container">
                <h2>Demandes de tickets</h2>
                <table id="demande-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Nom de l'élève</th>
                            <th>Professeur</th>
                            <th>Heure</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Les demandes sont ajoutées ici -->
                    </tbody>
                </table>
            </div>
        </div>
        <button id="logout-client">Se déconnecter</button>
    </div>

    <!-- Ton JavaScript intact -->
       <script type="module">
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
        import { getAuth } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js";
        import { getFirestore, collection, addDoc, deleteDoc, doc, onSnapshot, query, orderBy, serverTimestamp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-firestore.js";
    
        // Configuration Firebase
        const firebaseConfig = {
            apiKey: "AIzaSyBaFwA2kJM8CvlzBBkeCkq1CdlYclcxNZ0",
            authDomain: "sti2d-file-attente.firebaseapp.com",
            projectId: "sti2d-file-attente",
            storageBucket: "sti2d-file-attente.firebasestorage.app",
            messagingSenderId: "861290828360",
            appId: "1:861290828360:web:749ffe7565bd95db273e7d"
        };
    
        const app = initializeApp(firebaseConfig);
        const auth = getAuth(app);
        const db = getFirestore(app);
    
        let lastSubmissionTime = 0;
        let currentUser = null;

        // Authentification utilisateur
        auth.onAuthStateChanged((user) => {
            if (user) {
                const userEmail = user.email;
    
                if (!userEmail.endsWith('@lyc-buisson.com')) {
                    alert('Vous devez utiliser une adresse email valide @lyc-buisson.com');
                    auth.signOut();
                    window.location.href = 'connexion.html';
                    return;
                }
    
                const [firstName, lastName] = userEmail.split('@')[0].split('.');
                const formattedName = `${firstName.charAt(0).toUpperCase() + firstName.slice(1)}.${lastName.charAt(0).toUpperCase()}`;
                currentUser = formattedName;
    
                document.getElementById('nom-client').textContent = formattedName;
                document.getElementById('student-name').value = formattedName;
                document.getElementById('client-container').classList.remove('hidden');
    
                // Formulaire d'envoi de ticket
                const ticketForm = document.getElementById('ticket-form');
                ticketForm.addEventListener('submit', async (e) => {
                    e.preventDefault();
    
                    const currentTime = Date.now();
                    if (currentTime - lastSubmissionTime < 30000) {
                        document.getElementById('anti-spam-message').classList.remove('hidden');
                        return;
                    }
    
                    document.getElementById('anti-spam-message').classList.add('hidden');
    
                    const prof = document.getElementById('professeur').value;
                    try {
                        await addDoc(collection(db, 'demandes'), {
                            nom: formattedName,
                            professeur: prof,
                            timestamp: serverTimestamp()
                        });
                        lastSubmissionTime = currentTime;
                    } catch (err) {
                        console.error("Erreur lors de l'envoi de la demande :", err);
                    }
                });
    
                // Affichage des demandes
                const demandeTableBody = document.getElementById('demande-table').querySelector('tbody');
                const demandesRef = collection(db, 'demandes');
                const demandesQuery = query(demandesRef, orderBy("timestamp", "asc"));

    
                onSnapshot(demandesQuery, (snapshot) => {
    demandeTableBody.innerHTML = ''; // Réinitialiser le tableau à chaque mise à jour
    let id = 1;
    snapshot.forEach((docSnapshot) => {  // Modifier doc en docSnapshot pour éviter toute confusion
        const data = docSnapshot.data(); // Récupère les données du document
        const row = document.createElement('tr');

        const idCell = document.createElement('td');
        idCell.textContent = id++;
        row.appendChild(idCell);

        const nameCell = document.createElement('td');
        nameCell.textContent = data.nom;
        row.appendChild(nameCell);

        const profCell = document.createElement('td');
        profCell.textContent = data.professeur;
        row.appendChild(profCell);

        const timeCell = document.createElement('td');
        const requestTime = data.timestamp ? new Date(data.timestamp.toMillis()) : new Date();
        timeCell.textContent = requestTime.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
        row.appendChild(timeCell);

        const actionCell = document.createElement('td');
        if (data.nom === currentUser) {  // Vérification si l'élève est le bon utilisateur
            const deleteButton = document.createElement('button');
            deleteButton.textContent = '-';
            deleteButton.addEventListener('click', async () => {
                try {
                    const docRef = doc(db, 'demandes', docSnapshot.id); // Utilisation de docSnapshot.id pour obtenir la référence du document
                    await deleteDoc(docRef);  // Suppression du document
                    console.log("Demande supprimée :", docSnapshot.id); // Vérification dans la console
                } catch (err) {
                    console.error("Erreur lors de la suppression :", err);
                    alert("Erreur lors de la suppression de la demande.");
                }
            });
            actionCell.appendChild(deleteButton);
        }
        row.appendChild(actionCell);

        demandeTableBody.appendChild(row);
    });
});
            } else {
                window.location.href = 'connexion.html';
            }
        });
    
        // Déconnexion utilisateur
        const logoutButton = document.getElementById('logout-client');
        logoutButton.addEventListener('click', () => {
            auth.signOut().then(() => {
                window.location.href = 'connexion.html';
            });
        });

        const actionCell = document.createElement('td');
if (data.nom === currentUser) {  // Vérifier si c'est la demande de l'utilisateur
    const deleteButton = document.createElement('button');
    deleteButton.textContent = 'Supprimer';
    deleteButton.addEventListener('click', async () => {
        try {
            const docRef = doc(db, 'demandes', doc.id); // Référence du document à supprimer
            await deleteDoc(docRef); // Supprimer le document
            console.log("Demande supprimée :", doc.id); // Log pour vérification
        } catch (err) {
            console.error("Erreur lors de la suppression :", err);
            alert("Erreur lors de la suppression de la demande.");
        }
    });
    actionCell.appendChild(deleteButton);
}
row.appendChild(actionCell);
    </script>
</body>
</html>
