document.addEventListener('DOMContentLoaded', function() {
    // Check if the form and config exist
    const form = document.getElementById('customer-form');
    if (!form || !window.customerFormConfig) {
        return;
    }

    const {
        apiUrl,
        base_url,
        csrfToken,
        customerId
    } = window.customerFormConfig;
    const toast = document.getElementById('toast');

    function showToast(message, isError = false) {
        if (!toast) return;
        toast.textContent = message;
        toast.style.backgroundColor = isError ? '#ef4444' : '#22c55e';
        toast.style.display = 'block';
        toast.style.opacity = 1;
        setTimeout(() => {
            toast.style.opacity = 0;
            setTimeout(() => toast.style.display = 'none', 500);
        }, 5000);
    }

    async function handleFormSubmit(event) {
        event.preventDefault();
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        data.credit_limit = parseFloat(data.credit_limit) || 0;

        // Se o CPF estiver desabilitado (edição), não o envie.
        if (document.getElementById('cpf').disabled) {
            delete data.cpf;
        }

        const url = customerId ? `${apiUrl}/update/${customerId}` : `${apiUrl}/create`;
        const method = 'POST'; // Usando POST para ambos para simplicidade

        try {
            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (response.ok && result.success) {
                showToast(result.message);
                // Redireciona para a lista após um curto delay
                setTimeout(() => {
                    window.location.href = base_url + '/customer';
                }, 1000);
            } else {
                showToast(result.message || 'Ocorreu um erro.', true);
            }
        } catch (error) {
            showToast('Erro de conexão ao salvar os dados.', true);
        }
    }

    form.addEventListener('submit', handleFormSubmit);
});
