/**
 * pwa_event_controller.js
 * Auto binds forms/buttons to OfflineQueue logic.
 */

window.PWAEvents = (function(){

    function bindForm(formSelector, apiEndpoint, method = 'POST') {
        const form = document.querySelector(formSelector);
        if (!form) {
            console.warn("Form not found:", formSelector);
            return;
        }

        form.addEventListener('submit', function(e){
            e.preventDefault();

            const payload = {};
            new FormData(form).forEach((v,k)=>payload[k]=v);

            if (!navigator.onLine) {
                OfflineQueue.enqueue(apiEndpoint, payload, method);
                return;
            }

            // online — do normal request
            fetch(apiEndpoint, {
                method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            })
            .then(r=>r.json())
            .then(res=>{
                if (res.error) alert(res.msg);
                else {
                    alert("Saved successfully.");
                    history.back();
                }
            })
            .catch(err=>alert("Network error: " + err));
        });
    }

    return { bindForm };

})();
