<!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>
    <link rel="stylesheet" href="base.css">
    <link rel="stylesheet" href="fileE.css">
    <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>
</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="professeur">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>
                    </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>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Les demandes seront ajoutées ici dynamiquement -->
                    </tbody>
                </table>
            </div>
        </div>
        <button id="logout-client">Se déconnecter</button>
    </div>

    <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, onSnapshot, serverTimestamp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-firestore.js";

        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;

        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()}`;

                document.getElementById('nom-client').textContent = formattedName;
                document.getElementById('student-name').value = formattedName;
                document.getElementById('client-container').classList.remove('hidden');

                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()
                        });
                        alert('Demande envoyée avec succès !');
                        ticketForm.reset();
                        lastSubmissionTime = currentTime;
                    } catch (err) {
                        console.error("Erreur lors de l'envoi de la demande :", err);
                    }
                });

                const demandeTableBody = document.getElementById('demande-table').querySelector('tbody');
                onSnapshot(collection(db, 'demandes'), (snapshot) => {
                    demandeTableBody.innerHTML = '';
                    let id = 1;
                    snapshot.forEach((doc) => {
                        const data = doc.data();
                        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);

                        demandeTableBody.appendChild(row);
                    });
                });
            } else {
                window.location.href = 'connexion.html';
            }
        });

        const logoutButton = document.getElementById('logout-client');
        logoutButton.addEventListener('click', () => {
            auth.signOut().then(() => {
                window.location.href = 'connexion.html';
            });
        });
    </script>
</body>
</html>
