document.getElementById('loginForm').addEventListener('submit', function(event) { 
    event.preventDefault();

    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    const formData = new FormData();
    formData.append('email', email);
    formData.append('password', password);

    fetch('../php/login.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        const messageElement = document.getElementById('message');
        if (data.success) {
            window.location.href = '../html/main.html';
        } else {
            messageElement.textContent = data.message || 'Pierakstīšanās neveiksmīga!';
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
});

document.getElementById('registerForm').addEventListener('submit', function(event) {
    event.preventDefault();

    const registerEmail = document.getElementById('register-email').value;
    const registerPassword = document.getElementById('register-password').value;

    const formData = new FormData();
    formData.append('register-email', registerEmail);
    formData.append('register-password', registerPassword);

    fetch('../php/register.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        const registerMessageElement = document.getElementById('register-message');
        if (data.success) {
            registerMessageElement.textContent = 'Lietotājs veiksmīgi piereģistrēts!';
            document.getElementById('registerForm').reset();
        } else {
            registerMessageElement.textContent = data.message || 'Registration failed!';
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
});

document.getElementById('toggleForm').addEventListener('click', function() {
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    const formTitle = document.getElementById('form-title');
    
    if (loginForm.style.display === 'none') {
        loginForm.style.display = 'flex';
        registerForm.style.display = 'none';
        this.textContent = 'Neesi reģistrējies?';
        formTitle.textContent = 'Pieteikties';
    } else {
        loginForm.style.display = 'none';
        registerForm.style.display = 'flex';
        this.textContent = 'Esi jau reģistrējies?';
        formTitle.textContent = 'Reģistrēties';
    }
});
