const firebaseConfig = {
    apiKey: "AIzaSyBzzAO2WjD1DuTXEnFS4Dor9xYfHZBTjgM",
    authDomain: "key-askdoctor.firebaseapp.com",
    databaseURL: "https://key-askdoctor-default-rtdb.firebaseio.com",
    projectId: "key-askdoctor",
    storageBucket: "key-askdoctor.appspot.com",
    messagingSenderId: "85091263212",
    appId: "1:85091263212:web:e3be485dd3c5e260c37bc9",
    measurementId: "G-VNEC1FNMTT"
  };


firebase.initializeApp(firebaseConfig);

document.getElementById("signinForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent the form from submitting

    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    // Reference to the Firebase Realtime Database
    var database = firebase.database();

    // Reference to the 'users' node in the database
    var usersRef = database.ref("users");

    // Query to check if the username and password match any user in the database
    usersRef.orderByChild("username").equalTo(username).once("value", function(snapshot) {
        if (snapshot.exists()) {
            var userData = snapshot.val();
            var userKey = Object.keys(userData)[0];
            if (userData[userKey].password === password) {
                // Redirect to a dashboard page or perform other actions after successful sign-in
                window.location.href = "keyaskHome.html";
            } else {
                alert("Invalid password. Please try again.");
            }
        } else {
            alert("User does not exist. Please check your username.");
        }
    }, function(error) {
        console.error("Error fetching user data:", error);
    });
});

function signOut() {
    firebase.auth().signOut().then(function() {
        // Sign-out successful.
        alert("Signed out successfully!");
        window.location.href = "keyaskIndex.html"; // Redirect to sign-in page
    }).catch(function(error) {
        // An error happened.
        console.error("Sign-out error:", error);
    });
}