document.addEventListener('DOMContentLoaded', function () {
    const loginForm = document.getElementById("loginForm");
    loginForm.addEventListener('submit', function (event) {
        event.preventDefault();
        const username = loginForm.querySelector('input[placeholder="Username"]').value;
        const password = loginForm.querySelector('input[placeholder="Password"]').value;

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "dist/php/custom.php?action=login", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onload = function () {
            if (xhr.status === 200) {
                const jsonStartIndex = xhr.responseText.indexOf('{');
                if (jsonStartIndex !== -1) {
                    const responseText = xhr.responseText.substring(jsonStartIndex);
                    const response = JSON.parse(responseText);
    
                    if (response.success) {
                        // alert("Login successful!");
                        window.location.href = "dashboard.php";
                    } else {
                        alert(response.error || "Invalid username or password.");
                    }
                } else {
                    console.error("Invalid response format (no JSON object found):", xhr.responseText);
                    alert("An error occurred during login. Please try again.");
                }
            } else {
                console.error("Error during login:", xhr.statusText);
            }
        };
        xhr.send(JSON.stringify({ username: username, password: password }));
    });
});
