document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('receive-sms').addEventListener('change', (e) => {
        document.getElementById('phone-field').classList.toggle('hidden');
    });
    
    const form = document.getElementById('newsletter-signup-form');
    form.addEventListener('submit', (e) => {
        // Prevent the form from submitting
        e.preventDefault();

        // Get the form data
        const email = document.getElementById('email').value;
        const name = document.getElementById('name').value;

        if(!email || !name) {
            alert('Please fill in all the required fields.');
            return;
        }

        let phone = null;
        if(document.getElementById('receive-sms').checked) {
            phone = document.getElementById('phone').value;
        }

        const data = { email: email, name: name, phone: phone };

        // Send the data to the server
        fetch('/newsletter/signup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
            .then(response => {
                if(response.status !== 200) {
                    alert('There was an error signing you up.')
                    return;
                }

                return response.json();
            })
            .then(data => {
                console.log(data)
                confirm(`${data.message}. Are you okay if we redirect you to the home page?`) ? window.location.href = '/' : null;
            });
    });
});