// Disable Dropzone's auto-discover feature
Dropzone.autoDiscover = false;

document.addEventListener('DOMContentLoaded', function () {
    // Select all forms with the Dropzone class
    const dropzones = document.querySelectorAll('.dropzone');

    dropzones.forEach((form) => {
        // Check if Dropzone is already attached
        if (form.dropzone) return;

        // Get the form type from the data attribute
        const formType = form.getAttribute('data-form-type');
        const associatedTable = document.querySelector(`table[data-table-type="${formType}"] tbody`);

        const dz = new Dropzone(form, {
            url: form.getAttribute('action'),
            paramName: 'file',
            autoProcessQueue: true,
            maxFilesize: 600,
            acceptedFiles: '.pdf,.rom'
        });

        dz.on('success', function (file, response) {
            const parsedResponse = typeof response === 'string'
                ? JSON.parse(response)
                : response;

            if (parsedResponse.status === 'success') {
                if (associatedTable) {
                    const newRow = document.createElement('tr');
                    const newCell = document.createElement('td');

                    newCell.textContent = parsedResponse.file_name;
                    newRow.appendChild(newCell);
                    associatedTable.appendChild(newRow);
                }
            }
        });

        dz.on('error', function (file, errorMessage) {
            console.error('Error uploading file:', errorMessage);
        });
    });
});