<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>

    <link rel="stylesheet" href="../../styles/stylesheet.css">

    <script type="module">
        // Import necessary Firebase modules from CDN
        import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js';
        import { getAnalytics } from 'https://www.gstatic.com/firebasejs/9.22.2/firebase-analytics.js';
        import { getAuth, GoogleAuthProvider, signInWithPopup, signInWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.22.2/firebase-auth.js';

        const firebaseConfig = {
            apiKey: "AIzaSyCZfi1aIc3zDdZD7NR7kN2Jm4hnCtPHWcQ", 
            authDomain: "appointment-scheduling-s-57d01.firebaseapp.com",
            databaseURL: "https://appointment-scheduling-s-57d01-default-rtdb.asia-southeast1.firebasedatabase.app",
            projectId: "appointment-scheduling-s-57d01",
            storageBucket: "appointment-scheduling-s-57d01.firebasestorage.app",
            messagingSenderId: "1069885306589",
            appId: "1:1069885306589:web:b31768194add4087754d34",
            measurementId: "G-KQ4PQZZZBM"
        };

        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        const analytics = getAnalytics(app);
        const auth = getAuth(app); 

        const handleLogin = (email, password) => {
            console.log("handleLogin called with:", email, password);

            // Check for admin credentials
            if (email === 'admin.control@mail.com' && password === 'adminXCZ457!@#') {
                window.location.href = '../manageuser/adminhome.html';
                return Promise.resolve();
            }

            return signInWithEmailAndPassword(auth, email, password)
                .then((userCredential) => {
                    const user = userCredential.user;
                    console.log("User logged in: ", user);

                    window.location.href = 'userprofile.html'; 

                    return user; 
                })
                .catch((error) => {
                    const errorCode = error.code;
                    const errorMessage = error.message;
                    console.error("Login error:", errorMessage);

                    let customMessage = "";

                    if (errorCode === 'auth/wrong-password' || errorCode === 'auth/user-not-found') {
                        customMessage = "Invalid email or password. Please try again.";
                    } else {
                        customMessage = "Invalid email or password. Please try again.";
                    }

                    alert(customMessage);

                    const messageDiv = document.getElementById("message");
                    messageDiv.innerText = customMessage;

                    throw error;
                });
        };

        window.signInWithGoogle = function () {
            const provider = new GoogleAuthProvider();
            signInWithPopup(auth, provider)
                .then((result) => {
                    const user = result.user;
                    console.log("User signed in: ", user);
                    window.location.href = 'userprofile.html'; 
                })
                .catch((error) => {
                    console.error("Error signing in with Google: ", error);
                });
        };

        const loginForm = document.getElementById('auth');

        loginForm.addEventListener('submit', (event) => {
            event.preventDefault();

            const email = document.getElementById("email").value;
            const password = document.getElementById("password").value;

            handleLogin(email, password)
                .catch((error) => { 
                    // Error is already handled in handleLogin
                });
        });
    </script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> 
    
</head>

<body>
    <div class="bg-image"></div>
    <div class="header">
        <nav>
            <h2>ELAD School of Potentials Therapy Center</h2>
            <ul>
                <li><a href="../../../index.html">Home</a></li>
                <li><a href="../contact_home.html">Contact Us</a></li>
            </ul>
        </nav>
    </div>

    <div class="login-container">
        <h2>Log-In</h2>
        <form id="auth">
            <div class="form-group">
                <label for="email">Email:</label>
                <input id="email" type="email" name="email" required />
            </div>
            <div class="form-group">
                <label for="password">Password:</label>
                <input id="password" type="password" name="password" required />
            </div>

            <div id="loadingSpinner" class="loading" style="display: none;">Loading...</div>
            <div id="message" style="color: red;"></div>

            <button id="submit" type="submit">Log-in</button>
            <br>or<br><br>
            <a href="signup.html">Sign-up</a>
            <br><br>
            <button type="button" onclick="signInWithGoogle()">Log-in with Google</button>
        </form>
    </div>

    <div class="footer">
        <div class="social-links">
            <a href="https://www.facebook.com/ELADSchoolofPotentials" class="footer-style-button">Facebook</a>
        </div>
        <p>&copy; 2024 ELAD School of Potentials Therapy Center</p>
    </div>

</body>
</html>
