// script.js

document.addEventListener('DOMContentLoaded', function() {
    // DOM elements
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const setupSection = document.getElementById('setup-section');
    const verifySection = document.getElementById('verify-section');
    const qrCodeContainer = document.getElementById('qr-code-container');
    const qrCodeDiv = document.getElementById('qr-code');
    const secretDisplay = document.getElementById('secret-display');
    const secretValue = document.getElementById('secret-value');
    const verificationCodeInput = document.getElementById('verification-code');
    const verificationResultDiv = document.getElementById('verification-result');
    const logoutButton = document.getElementById('logout-button');
    const loginSection = document.getElementById('login-section');
    const registerSection = document.getElementById('register-section');
    const errorMessage = document.getElementById('error-message');

    const showRegisterButton = document.getElementById('show-register');
    const showLoginButton = document.getElementById('show-login');

    if (showRegisterButton) {
        showRegisterButton.addEventListener('click', function() {
            loginSection.style.display = 'none';
            registerSection.style.display = 'block';
            clearError();
        });
    }

    if (showLoginButton) {
        showLoginButton.addEventListener('click', function() {
            registerSection.style.display = 'none';
            loginSection.style.display = 'block';
            clearError();
        });
    }


    // Helper function to display error messages
    function displayError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
    }
    function clearError(){
        errorMessage.textContent = "";
        errorMessage.style.display = 'none';
    }

    // Login form submission
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            clearError();

            const formData = new FormData(loginForm);
            fetch('login.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    loginSection.style.display = 'none';
                    registerSection.style.display = 'none';
                    setupSection.style.display = 'block';
                } else {
                    displayError(data.message);
                }
            })
            .catch(error => {
                displayError('An error occurred during login.');
                console.error('Login error:', error);
            });
        });
    }

    // Register form submission
    if (registerForm) {
        registerForm.addEventListener('submit', function(e) {
            e.preventDefault();
            clearError();

            const formData = new FormData(registerForm);
            fetch('register.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    loginSection.style.display = 'block';
                    registerSection.style.display = 'none';
                    displayError(data.message);
                } else {
                    displayError(data.message);
                }
            })
            .catch(error => {
                displayError('An error occurred during registration.');
                console.error('Registration error:', error);
            });
        });
    }

    // Generate QR code
    if(setupSection) {
        const generateButton = document.getElementById('generate-button');
        if (generateButton) {
            generateButton.addEventListener('click', function() {
                clearError();
                fetch('generate.php', {
                    method: 'POST'
                })
                .then(response => response.json())
                
                .then(data => {
                  console.log('Server response:', data);
                    if (data.status === 'success') {
                        qrCodeDiv.innerHTML = data.qrcode;
                        secretValue.textContent = data.secret;
                        qrCodeContainer.style.display = 'block';
                        secretDisplay.style.display = 'block';
                        setupSection.style.display = 'none';
                        verifySection.style.display = 'block';
                    } else {
                        displayError(data.message);
                    }
                })
                .catch(error => {
                  console.error('Fetch error:', error);
                    displayError('An error occurred generating the QR code.');
                    console.error('QR code generation error:', error);
                });
            });
        }
    }

    // Verify code
    if(verifySection){
        const verifyButton = document.getElementById('verify-button');
        if(verifyButton){
            verifyButton.addEventListener('click', function() {
                clearError();
                const formData = new FormData();
                formData.append('code', verificationCodeInput.value);

                fetch('verify.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    verificationResultDiv.textContent = data.message;
                    if(data.status === "success"){
                        verificationResultDiv.style.backgroundColor = "#d4edda";
                        verificationResultDiv.style.color = "#155724";
                    } else {
                        verificationResultDiv.style.backgroundColor = "#f8d7da";
                        verificationResultDiv.style.color = "#721c24";
                    }

                })
                .catch(error => {
                    displayError('An error occurred during verification.');
                    console.error('Verification error:', error);
                });
            });
        }
    }

    // Logout
    if (logoutButton) {
        logoutButton.addEventListener('click', function() {
            fetch('logout.php', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    loginSection.style.display = 'block';
                    registerSection.style.display = 'none';
                    setupSection.style.display = 'none';
                    verifySection.style.display = 'none';
                    qrCodeContainer.style.display = 'none';
                    secretDisplay.style.display = 'none';
                }
            })
            .catch(error => {
                displayError('An error occurred during logout.');
                console.error('Logout error:', error);
            });
        });
    }

});
