// Using Document.on ensures SPA buttons work perfectly regardless of when they are injected
$(document).ready(function() {
    const consultProcessorUrl = '/rimax/application/dripend/systemSetup/consultation/processManageConsultationFields.php';

    window.initManageConsultationFields = function() {
        if ($.fn.DataTable.isDataTable('#registryTable')) {
            $('#registryTable').DataTable().destroy();
        }

        window.registryTable = $('#registryTable').DataTable({
            pageLength: 25,
            ordering: false,
            ajax: {
                url: consultProcessorUrl + '?action=fetch',
                dataSrc: 'data',
                error: function(xhr, error, thrown) {
                    console.error("DataTables Error:", xhr.responseText);
                    $('#alertError').html('<i class="fa-solid fa-triangle-exclamation"></i> Could not load table data.').show();
                }
            },
            columns: [
                { data: 'mapped_department', render: data => `<span class="badge-dept badge">${data}</span>` },
                { data: 'section_name', render: data => `<span style="color:#075985; font-weight:800;">${data}</span>` },
                { data: 'field_label', render: (data, type, row) => `<strong>${data}</strong><br><span style="font-size:10px; color:#94a3b8; font-family:monospace;">Key: ${row.field_name}</span>` },
                { data: 'field_type', render: data => `<span class="badge">${data}</span>` },
                { data: 'is_required', render: data => data == 1 ? `<i class="fa-solid fa-asterisk" style="color:#dc2626;" title="Required"></i>` : `<span style="color:#cbd5e1;">-</span>` },
                { data: 'is_active', render: data => data == 1 ? `<span style="color:#059669;"><i class="fa-solid fa-circle-check"></i> Active</span>` : `<span style="color:#64748b;"><i class="fa-solid fa-circle-xmark"></i> Inactive</span>` },
                { 
                    data: null, 
                    render: function(data, type, row) {
                        const rowData = encodeURIComponent(JSON.stringify(row));
                        return `
                            <button type="button" class="btn-edit-consult" data-row="${rowData}" style="background:#0284c7; color:#fff; padding:6px 10px; border-radius:6px; border:none; cursor:pointer; font-size:12px; margin-right:5px;" title="Edit Parameters"><i class="fa-solid fa-pen"></i></button>
                            <button type="button" class="btn-delete-consult" data-id="${row.id}" style="background:#dc2626; color:#fff; padding:6px 10px; border-radius:6px; border:none; cursor:pointer; font-size:12px;" title="Remove Form Field"><i class="fa-solid fa-trash"></i></button>
                        `;
                    } 
                }
            ],
            language: { search: "Search Fields:", emptyTable: "No dynamic fields have been mapped yet." }
        });

        window.toggleConsultOptionsBox();
    };

    $(document).on('input', '#field_label', function() {
        const isEdit = $('#formAction').val() === 'edit';
        if (!isEdit || $('#field_name').val() === '') {
            const slug = $(this).val().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/(^_|_$)/g, '');
            $('#field_name').val(slug);
        }
    });

    $(document).on('change', '#field_type', function() {
        window.toggleConsultOptionsBox();
    });

    $(document).off('click', '#btnSubmitConsultForm').on('click', '#btnSubmitConsultForm', function(e) {
        e.preventDefault(); 
        
        $('#alertSuccess, #alertError').hide();
        
        if (!$('#field_label').val() || !$('#section_name').val()) {
            $('#alertError').html('<i class="fa-solid fa-triangle-exclamation"></i> Please fill in the required fields.').slideDown();
            return;
        }

        const submitBtn = $(this);
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fa-solid fa-spinner fa-spin"></i> Processing Map...');
        submitBtn.prop('disabled', true);

        $.ajax({
            url: consultProcessorUrl,
            type: 'POST',
            data: $('#setupConsultForm').serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    $('#alertSuccess').html(`<i class="fa-solid fa-check-circle"></i> ${response.message}`).slideDown();
                    window.resetConsultForm();
                    if(window.registryTable) window.registryTable.ajax.reload(null, false);
                    setTimeout(() => $('#alertSuccess').slideUp(), 4000);
                } else {
                    $('#alertError').html(`<i class="fa-solid fa-triangle-exclamation"></i> ${response.message}`).slideDown();
                }
            },
            error: function(xhr) {
                console.error("AJAX Error:", xhr.responseText);
                $('#alertError').html('<i class="fa-solid fa-triangle-exclamation"></i> Critical Server Error. Check Network Console.').slideDown();
            },
            complete: function() {
                submitBtn.html(originalText);
                submitBtn.prop('disabled', false);
            }
        });
    });

    $(document).on('click', '.btn-edit-consult', function() {
        const data = JSON.parse(decodeURIComponent($(this).attr('data-row')));
        
        $('#formHeader').html('<i class="fa-solid fa-pen-to-square"></i> Modify Field Mapping');
        $('#formAction').val('edit');
        $('#field_id').val(data.id);
        $('#department_id').val(data.department_id || '');
        $('#section_name').val(data.section_name);
        $('#field_label').val(data.field_label);
        $('#field_name').val(data.field_name);
        $('#field_type').val(data.field_type).trigger('change');
        $('#field_options').val(data.field_options);
        $('#display_order').val(data.display_order);
        $('#is_required').prop('checked', data.is_required == 1);
        $('#is_active').prop('checked', data.is_active == 1);
        
        $('#btnSubmitConsultForm').html('<i class="fa-solid fa-sync"></i> Update Map Configuration');
        $('#btnCancelConsultEdit').show();
        
        document.querySelector('.content-scroll').scrollTo({ top: 0, behavior: 'smooth' });
    });

    $(document).on('click', '.btn-delete-consult', function() {
        const id = $(this).attr('data-id');
        if (confirm("WARNING: Are you sure you want to permanently delete this field?")) {
            $.ajax({
                url: consultProcessorUrl,
                type: 'POST',
                data: { action: 'delete', delete_id: id },
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        if(window.registryTable) window.registryTable.ajax.reload(null, false);
                    } else {
                        alert(response.message);
                    }
                }
            });
        }
    });

    $(document).on('click', '#btnCancelConsultEdit', function() {
        window.resetConsultForm();
    });

    window.toggleConsultOptionsBox = function() {
        const type = $('#field_type').val();
        if (type === 'select' || type === 'radio' || type === 'checkbox') {
            $('#optionsBox').show();
        } else {
            $('#optionsBox').hide();
        }
    };

    window.resetConsultForm = function() {
        $('#formHeader').html('<i class="fa-solid fa-wand-magic-sparkles"></i> Field Builder & Mapper');
        $('#setupConsultForm')[0].reset();
        $('#formAction').val('add');
        $('#field_id').val('');
        $('#field_name').val('');
        $('#btnSubmitConsultForm').html('<i class="fa-solid fa-link"></i> Save & Map to Form');
        $('#btnCancelConsultEdit').hide();
        $('#field_type').trigger('change');
    };
});