let resetPasswordEmail = "";

async function forgotPassword() {
    const email = document.getElementById("email").value.trim();

    if (!email) {
        Swal.fire({
            title: "Email Required",
            text: "Please enter your email address",
            icon: "warning",
            confirmButtonColor: "#d92626"
        });
        return;
    }

    const userEmail = {
        email: email
    };

    const emailJSON = JSON.stringify(userEmail);

    try {
        const response = await fetch(
            "Backend/Process/forgotPasswordProcess.php",
            {
                method: "POST",
                body: emailJSON,
                headers: {
                    "Content-type": "application/json"
                }
            }
        );

        if (response.ok) {
            const json = await response.json();
            console.log(json);

            if (json.status) {
                // Store email for reset password
                resetPasswordEmail = email;
                
                // Open reset password modal immediately
                const modalElement = document.getElementById("resetPasswordModal");
                if (modalElement) {
                    // Clear form first
                    document.getElementById("verificationCode").value = "";
                    document.getElementById("newPassword").value = "";
                    document.getElementById("confirmPassword").value = "";
                    document.getElementById("passwordStrength").style.display = "none";
                    document.getElementById("passwordMatch").style.display = "none";
                    
                    // Use Bootstrap 5 modal API
                    const modal = new bootstrap.Modal(modalElement);
                    modal.show();
                    
                    // Show success message after modal opens
                    setTimeout(() => {
                        Swal.fire({
                            title: "Code Sent!",
                            text: json.message,
                            icon: "success",
                            confirmButtonColor: "#d92626",
                            timer: 3000,
                            showConfirmButton: true
                        });
                    }, 300);
                } else {
                    console.error("Reset password modal not found");
                    Swal.fire({
                        title: "Code Sent!",
                        text: json.message + " Please refresh the page to access the reset form.",
                        icon: "success",
                        confirmButtonColor: "#d92626"
                    });
                }
            } else {
                Swal.fire({
                    title: "Error",
                    text: json.message,
                    icon: "error",
                    confirmButtonColor: "#d92626"
                });
            }
        } else {
            Swal.fire({
                title: "Server Error",
                text: "Something went wrong. Please try again.",
                icon: "error",
                confirmButtonColor: "#d92626"
            });
        }
    } catch (error) {
        console.error("Error:", error);
        Swal.fire({
            title: "Error",
            text: "Network error. Please check your connection.",
            icon: "error",
            confirmButtonColor: "#d92626"
        });
    }
}

// Reset Password Function
async function resetPassword() {
    const vcode = document.getElementById("verificationCode").value.trim();
    const newPassword = document.getElementById("newPassword").value;
    const confirmPassword = document.getElementById("confirmPassword").value;
    const email = resetPasswordEmail || document.getElementById("email").value.trim();

    // Validation
    if (!vcode || vcode.length !== 5) {
        Swal.fire({
            title: "Invalid Code",
            text: "Please enter a valid 5-digit verification code",
            icon: "warning",
            confirmButtonColor: "#d92626"
        });
        return;
    }

    if (!newPassword) {
        Swal.fire({
            title: "Password Required",
            text: "Please enter a new password",
            icon: "warning",
            confirmButtonColor: "#d92626"
        });
        return;
    }

    if (newPassword !== confirmPassword) {
        Swal.fire({
            title: "Password Mismatch",
            text: "New password and confirm password do not match",
            icon: "warning",
            confirmButtonColor: "#d92626"
        });
        return;
    }

    const resetData = {
        email: email,
        newPassword: newPassword,
        rePassword: confirmPassword,
        vcode: vcode
    };

    const resetJSON = JSON.stringify(resetData);

    try {
        const response = await fetch(
            "Backend/Process/resetPasswordProcess.php",
            {
                method: "POST",
                body: resetJSON,
                headers: {
                    "Content-type": "application/json"
                }
            }
        );

        if (response.ok) {
            const json = await response.json();

            if (json.status) {
                Swal.fire({
                    title: "Success!",
                    text: json.message,
                    icon: "success",
                    confirmButtonColor: "#d92626"
                }).then(() => {
                    // Close modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById("resetPasswordModal"));
                    if (modal) {
                        modal.hide();
                    }
                    // Reload page to show login form
                    window.location.reload();
                });
            } else {
                Swal.fire({
                    title: "Error",
                    text: json.message,
                    icon: "error",
                    confirmButtonColor: "#d92626"
                });
            }
        } else {
            Swal.fire({
                title: "Server Error",
                text: "Something went wrong. Please try again.",
                icon: "error",
                confirmButtonColor: "#d92626"
            });
        }
    } catch (error) {
        console.error("Error:", error);
        Swal.fire({
            title: "Error",
            text: "Network error. Please check your connection.",
            icon: "error",
            confirmButtonColor: "#d92626"
        });
    }
}

// Password toggle functionality
document.addEventListener("DOMContentLoaded", function() {
    // Toggle new password visibility
    const toggleNewPassword = document.getElementById("toggleNewPassword");
    const newPasswordInput = document.getElementById("newPassword");
    
    if (toggleNewPassword && newPasswordInput) {
        toggleNewPassword.addEventListener("click", function() {
            if (newPasswordInput.type === "password") {
                newPasswordInput.type = "text";
                toggleNewPassword.classList.remove("fa-eye");
                toggleNewPassword.classList.add("fa-eye-slash");
            } else {
                newPasswordInput.type = "password";
                toggleNewPassword.classList.remove("fa-eye-slash");
                toggleNewPassword.classList.add("fa-eye");
            }
        });
    }

    // Toggle confirm password visibility
    const toggleConfirmPassword = document.getElementById("toggleConfirmPassword");
    const confirmPasswordInput = document.getElementById("confirmPassword");
    
    if (toggleConfirmPassword && confirmPasswordInput) {
        toggleConfirmPassword.addEventListener("click", function() {
            if (confirmPasswordInput.type === "password") {
                confirmPasswordInput.type = "text";
                toggleConfirmPassword.classList.remove("fa-eye");
                toggleConfirmPassword.classList.add("fa-eye-slash");
            } else {
                confirmPasswordInput.type = "password";
                toggleConfirmPassword.classList.remove("fa-eye-slash");
                toggleConfirmPassword.classList.add("fa-eye");
            }
        });
    }

    // Password strength checker
    if (newPasswordInput) {
        newPasswordInput.addEventListener("input", function() {
            const password = this.value;
            const strengthDiv = document.getElementById("passwordStrength");
            const strengthBar = strengthDiv.querySelector(".progress-bar");
            const strengthText = document.getElementById("passwordStrengthText");

            if (password.length > 0) {
                strengthDiv.style.display = "block";
                
                let strength = 0;
                let strengthLabel = "";
                let strengthColor = "";

                // Check password strength
                if (password.length >= 8) strength += 25;
                if (/[a-z]/.test(password)) strength += 25;
                if (/[A-Z]/.test(password)) strength += 25;
                if (/[0-9]/.test(password)) strength += 12.5;
                if (/[^A-Za-z0-9]/.test(password)) strength += 12.5;

                if (strength < 50) {
                    strengthLabel = "Weak";
                    strengthColor = "#dc3545";
                } else if (strength < 75) {
                    strengthLabel = "Medium";
                    strengthColor = "#ffc107";
                } else {
                    strengthLabel = "Strong";
                    strengthColor = "#28a745";
                }

                strengthBar.style.width = strength + "%";
                strengthBar.style.backgroundColor = strengthColor;
                strengthText.textContent = "Password Strength: " + strengthLabel;
                strengthText.style.color = strengthColor;
            } else {
                strengthDiv.style.display = "none";
            }
        });
    }

    // Password match checker
    if (confirmPasswordInput && newPasswordInput) {
        confirmPasswordInput.addEventListener("input", function() {
            const matchDiv = document.getElementById("passwordMatch");
            const matchText = document.getElementById("passwordMatchText");
            const newPass = newPasswordInput.value;
            const confirmPass = this.value;

            if (confirmPass.length > 0) {
                matchDiv.style.display = "block";
                if (newPass === confirmPass) {
                    matchText.textContent = "✓ Passwords match";
                    matchText.style.color = "#28a745";
                } else {
                    matchText.textContent = "✗ Passwords do not match";
                    matchText.style.color = "#dc3545";
                }
            } else {
                matchDiv.style.display = "none";
            }
        });
    }
});

// async function resetPassword() {
//     const email = document.getElementById("e2").value;
//     const newPassword = document.getElementById("np").value;
//     const rePassword = document.getElementById("rp").value;
//     const vcode = document.getElementById("vcode").value;

//     const resetData = {
//         email: email,
//         newPassword: newPassword,
//         rePassword: rePassword,
//         vcode: vcode
//     };

//     const resetJSON = JSON.stringify(resetData);

//     const response = await fetch(
//         "Backend/Process/resetPasswordProcess",
//         {
//             method: "POST",
//             body: resetJSON,
//             headers: {
//                 "Content-type": "application/json"
//             }
//         }
//     );

//     if(response.ok){
//         const json = response.json();

//         if(json.status){
//             alert(json.message);
//         }else{
//             alert(json.message);
//         }
//     }else{
//         alert("Server Error")
//     }
// }


// function showPassword1() {

//     var np = document.getElementById("np");
//     var npb = document.getElementById("npb");

//     if (np.type == "password") {
//         np.type = "text";
//         npb.innerHTML = '<i class="bi bi-eye"></i>';
//     } else {
//         np.type = "password";
//         npb.innerHTML = '<i class="bi bi-eye-slash-fill"></i>';
//     }

// }

// function showPassword2() {

//     var rnp = document.getElementById("rp");
//     var rnpb = document.getElementById("rpb");

//     if (rnp.type == "password") {
//         rnp.type = "text";
//         rnpb.innerHTML = '<i class="bi bi-eye"></i>';
//     } else {
//         rnp.type = "password";
//         rnpb.innerHTML = '<i class="bi bi-eye-slash-fill"></i>';
//     }

// }