/**
 * Enhanced Authentication Module
 * Handles OTP-based signup, email verification, and forgot password functionality
 * Include this file on all pages with auth modals
 */

// Initialize authentication handlers when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    initializeAuthHandlers();
});

function initializeAuthHandlers() {
    // Sign Up Handler - Step 1: Send OTP
    const signUpForm = document.getElementById('signUpForm');
    if (signUpForm) {
        signUpForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleSignUpSubmit();
        });
    }

    // Email Verification Handler
    const emailVerificationForm = document.getElementById('emailVerificationForm');
    if (emailVerificationForm) {
        emailVerificationForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleEmailVerification();
        });
    }

    // Resend Email OTP
    const resendEmailOTPBtn = document.getElementById('resendEmailOTP');
    if (resendEmailOTPBtn) {
        resendEmailOTPBtn.addEventListener('click', function(e) {
            e.preventDefault();
            handleResendEmailOTP();
        });
    }

    // Forgot Password - Send OTP
    const sendResetOTPBtn = document.getElementById('sendResetOTPBtn');
    if (sendResetOTPBtn) {
        sendResetOTPBtn.addEventListener('click', function(e) {
            e.preventDefault();
            handleSendResetOTP();
        });
    }

    // Back to email button
    const backToEmailBtn = document.getElementById('backToEmailBtn');
    if (backToEmailBtn) {
        backToEmailBtn.addEventListener('click', function(e) {
            e.preventDefault();
            document.getElementById('forgotPasswordStep2').style.display = 'none';
            document.getElementById('forgotPasswordStep1').style.display = 'block';
            document.getElementById('forgotPasswordMessage').style.display = 'none';
        });
    }

    // Reset Password with OTP
    const resetPasswordBtn = document.getElementById('resetPasswordBtn');
    if (resetPasswordBtn) {
        resetPasswordBtn.addEventListener('click', function(e) {
            e.preventDefault();
            handleResetPassword();
        });
    }

    // Resend Reset OTP
    const resendResetOTPBtn = document.getElementById('resendResetOTP');
    if (resendResetOTPBtn) {
        resendResetOTPBtn.addEventListener('click', function(e) {
            e.preventDefault();
            handleResendResetOTP();
        });
    }

    // Sign In Handler
    const signInForm = document.getElementById('signInForm');
    if (signInForm) {
        signInForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleSignInSubmit();
        });
    }
}

// Handle Sign Up Submission - Send OTP
function handleSignUpSubmit() {
    const formData = {
        action: 'send_signup_otp',
        name: document.getElementById('signupName').value,
        email: document.getElementById('signupEmail').value,
        phone: document.getElementById('signupPhone').value,
        password: document.getElementById('signupPassword').value,
        confirmPassword: document.getElementById('signupConfirmPassword').value
    };

    const messageDiv = document.getElementById('signupMessage');
    messageDiv.style.display = 'flex';
    messageDiv.className = 'auth-message';
    messageDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending OTP...';

    fetch('backend/send_otp.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        messageDiv.style.display = 'flex';
        if (data.success) {
            messageDiv.className = 'auth-message success';
            messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message;
            
            // Store email for verification
            document.getElementById('verifyEmailAddress').value = data.data.email;
            
            // Close sign up modal and open email verification modal after a delay
            setTimeout(() => {
                $('#signUpModal').modal('hide');
                setTimeout(() => {
                    $('#emailVerificationModal').modal('show');
                    document.getElementById('verifyEmailMessage').style.display = 'none';
                }, 500);
            }, 2000);
        } else {
            messageDiv.className = 'auth-message error';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
        }
    })
    .catch(error => {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Error: ' + error.message;
        console.error('Error:', error);
    });
}

// Handle Email Verification
function handleEmailVerification() {
    const email = document.getElementById('verifyEmailAddress').value;
    const otp = document.getElementById('emailOTP').value;
    const messageDiv = document.getElementById('verifyEmailMessage');

    const formData = {
        action: 'verify_signup_otp',
        email: email,
        otp: otp
    };

    messageDiv.style.display = 'flex';
    messageDiv.className = 'auth-message';
    messageDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verifying OTP...';

    fetch('backend/verify_otp.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        messageDiv.style.display = 'flex';
        if (data.success) {
            messageDiv.className = 'auth-message success';
            messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message + ' Redirecting to sign in...';
            
            // Clear form
            document.getElementById('emailVerificationForm').reset();
            document.getElementById('signUpForm').reset();
            
            // Close modal and show sign in
            setTimeout(() => {
                $('#emailVerificationModal').modal('hide');
                setTimeout(() => {
                    messageDiv.style.display = 'none';
                    $('#signInModal').modal('show');
                }, 500);
            }, 2000);
        } else {
            messageDiv.className = 'auth-message error';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
        }
    })
    .catch(error => {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Error: ' + error.message;
        console.error('Error:', error);
    });
}

// Resend Email OTP
function handleResendEmailOTP() {
    const email = document.getElementById('verifyEmailAddress').value;
    const messageDiv = document.getElementById('verifyEmailMessage');

    const formData = {
        action: 'resend_otp',
        email: email,
        purpose: 'signup'
    };

    messageDiv.style.display = 'flex';
    messageDiv.className = 'auth-message';
    messageDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Resending OTP...';

    fetch('backend/send_otp.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        messageDiv.style.display = 'flex';
        if (data.success) {
            messageDiv.className = 'auth-message success';
            messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message;
        } else {
            messageDiv.className = 'auth-message error';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
        }
    })
    .catch(error => {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Error: ' + error.message;
    });
}

// Forgot Password - Send OTP
function handleSendResetOTP() {
    const email = document.getElementById('forgotEmail').value;
    const messageDiv = document.getElementById('forgotPasswordMessage');

    if (!email) {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Please enter your email address';
        return;
    }

    const formData = {
        action: 'send_reset_otp',
        email: email
    };

    messageDiv.style.display = 'flex';
    messageDiv.className = 'auth-message';
    messageDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending OTP...';

    fetch('backend/send_otp.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        messageDiv.style.display = 'flex';
        if (data.success) {
            messageDiv.className = 'auth-message success';
            messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message;
            
            // Store token for verification
            document.getElementById('resetToken').value = data.data.token;
            
            // Show step 2 after 2 seconds
            setTimeout(() => {
                document.getElementById('forgotPasswordStep1').style.display = 'none';
                document.getElementById('forgotPasswordStep2').style.display = 'block';
                messageDiv.style.display = 'none';
            }, 2000);
        } else {
            messageDiv.className = 'auth-message error';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
        }
    })
    .catch(error => {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Error: ' + error.message;
    });
}

// Reset Password with OTP
function handleResetPassword() {
    const email = document.getElementById('forgotEmail').value;
    const token = document.getElementById('resetToken').value;
    const otp = document.getElementById('resetOTP').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmNewPassword').value;
    const messageDiv = document.getElementById('forgotPasswordMessage');

    if (!otp || !newPassword || !confirmPassword) {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Please fill in all fields';
        return;
    }

    const formData = {
        action: 'verify_reset_otp',
        email: email,
        token: token,
        otp: otp,
        newPassword: newPassword,
        confirmPassword: confirmPassword
    };

    messageDiv.style.display = 'flex';
    messageDiv.className = 'auth-message';
    messageDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Resetting password...';

    fetch('backend/verify_otp.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        messageDiv.style.display = 'flex';
        if (data.success) {
            messageDiv.className = 'auth-message success';
            messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message + ' Redirecting to sign in...';
            
            // Clear form
            document.getElementById('forgotPasswordForm').reset();
            document.getElementById('forgotPasswordStep2').style.display = 'none';
            document.getElementById('forgotPasswordStep1').style.display = 'block';
            
            // Close modal and show sign in
            setTimeout(() => {
                $('#forgotPasswordModal').modal('hide');
                setTimeout(() => {
                    messageDiv.style.display = 'none';
                    $('#signInModal').modal('show');
                }, 500);
            }, 2000);
        } else {
            messageDiv.className = 'auth-message error';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
        }
    })
    .catch(error => {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Error: ' + error.message;
    });
}

// Resend Reset OTP
function handleResendResetOTP() {
    const email = document.getElementById('forgotEmail').value;
    const messageDiv = document.getElementById('forgotPasswordMessage');

    const formData = {
        action: 'resend_otp',
        email: email,
        purpose: 'reset'
    };

    messageDiv.style.display = 'flex';
    messageDiv.className = 'auth-message';
    messageDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Resending OTP...';

    fetch('backend/send_otp.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        messageDiv.style.display = 'flex';
        if (data.success) {
            messageDiv.className = 'auth-message success';
            messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message;
        } else {
            messageDiv.className = 'auth-message error';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
        }
    })
    .catch(error => {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Error: ' + error.message;
    });
}

// Handle Sign In Submission
function handleSignInSubmit() {
    const formData = {
        email: document.getElementById('signinEmail').value,
        password: document.getElementById('signinPassword').value,
        rememberMe: document.getElementById('rememberMe').checked
    };

    const messageDiv = document.getElementById('signinMessage');

    fetch('backend/signin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        messageDiv.style.display = 'flex';
        if (data.success) {
            messageDiv.className = 'auth-message success';
            messageDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message;
            
            // Clear form
            document.getElementById('signInForm').reset();
            
            // Store user data in localStorage
            localStorage.setItem('user', JSON.stringify(data.data));
            
            // Update cartManager login status
            if (window.cartManager) {
                window.cartManager.updateLoginStatus();
            }
            
            // Close modal
            setTimeout(() => {
                $('#signInModal').modal('hide');
                messageDiv.style.display = 'none';
                // Update header with user profile if function exists
                if (typeof updateHeaderWithUserProfile === 'function') {
                    updateHeaderWithUserProfile(data.data);
                }
                // Refresh page after successful sign-in
                setTimeout(() => {
                    window.location.reload();
                }, 500);
            }, 2000);
        } else {
            messageDiv.className = 'auth-message error';
            messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
        }
    })
    .catch(error => {
        messageDiv.style.display = 'flex';
        messageDiv.className = 'auth-message error';
        messageDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Error: ' + error.message;
        console.error('Error:', error);
    });
}
