window.initTheatreManagerConfig = function() {
    let dtConfig;
    let currentActiveTab = 'rooms';
    const apiConfig = '/rimax/application/dripend/systemSetup/ipd/processTheatreManagerConfig.php';
    const apiAccess = '/rimax/application/dripend/systemSetup/ipd/processTheatreManagerConfigAccess.php';
    let pendingDeleteId = null;
    let globalInsurances = [];

    function loadDependencies() {
        $.post(apiConfig, { action: 'fetch_dependencies' }, function(res) {
            if(res.status === 'success') {
                let sOpts = '<option value="">-- Select Staff --</option>';
                if(res.staff && Array.isArray(res.staff)) res.staff.forEach(d => sOpts += `<option value="${d.id}">${d.name}</option>`);
                $('#cfg_staff_id').html(sOpts);

                let rOpts = '<option value="">-- Select Role --</option>';
                if(res.roles && Array.isArray(res.roles)) res.roles.forEach(r => rOpts += `<option value="${r.id}">${r.name}</option>`);
                $('#cfg_role_id').html(rOpts);

                let cOpts = '<option value="">-- Select Category --</option>';
                if(res.categories && Array.isArray(res.categories)) res.categories.forEach(c => cOpts += `<option value="${c.id}">${c.name}</option>`);
                $('#cfg_category_id').html(cOpts);

                let gOpts = '<option value="">-- Search & Map G-DRG --</option>';
                if(res.gdrgs && Array.isArray(res.gdrgs)) res.gdrgs.forEach(g => gOpts += `<option value="${g.id}">${g.name}</option>`);
                $('#cfg_gdrg_proc').html(gOpts);

                let dOpts = '<option value="">-- Select Department --</option>';
                if(res.departments && Array.isArray(res.departments)) res.departments.forEach(d => dOpts += `<option value="${d.id}">${d.name}</option>`);
                $('#cfg_dept_id').html(dOpts);

                let pOpts = '<option value="">-- No Procedure Linked --</option>';
                if(res.procedures && Array.isArray(res.procedures)) res.procedures.forEach(p => pOpts += `<option value="${p.id}">${p.name}</option>`);
                $('#cfg_procedure_id_anes').html(pOpts);
                $('#cfg_target_procedure_id').html(pOpts);

                let rmOpts = '<option value="">-- Select Room --</option>';
                if(res.theatre_rooms && Array.isArray(res.theatre_rooms)) res.theatre_rooms.forEach(r => rmOpts += `<option value="${r.id}">${r.name}</option>`);
                $('#cfg_bed_room_id, #cfg_target_room_id').html(rmOpts);

                let bdOpts = '<option value="">-- Select Bed --</option>';
                if(res.theatre_beds && Array.isArray(res.theatre_beds)) res.theatre_beds.forEach(b => bdOpts += `<option value="${b.id}">${b.name}</option>`);
                $('#cfg_target_bed_id').html(bdOpts);

                let svcOpts = '<option value="">-- Select Service to Charge --</option>';
                if(res.ipd_services && Array.isArray(res.ipd_services)) res.ipd_services.forEach(s => svcOpts += `<option value="${s.id}">${s.name}</option>`);
                $('#cfg_charge_service_id').html(svcOpts);

                let freqOpts = '<option value="">-- Select Frequency --</option>';
                if(res.frequencies && Array.isArray(res.frequencies)) res.frequencies.forEach(f => freqOpts += `<option value="${f.id}">${f.name}</option>`);
                $('#cfg_charge_frequency_id').html(freqOpts);

                globalInsurances = res.insurances || [];
                $('.select2-modal').select2({ dropdownParent: $('#configModal'), width: '100%' });
            }
        }, 'json');
    }

    loadDependencies();

    // Auto-Fetch Tariff Pricing and Description when GDRG changes
    $('#cfg_gdrg_proc').on('change', function() {
        let code = $(this).val();
        if(code && currentActiveTab === 'procedures') {
            $.post(apiConfig, { action: 'fetch_gdrg_details', gdrg_code: code }, function(res) {
                if(res.status === 'success' && !$('#cfg_name').val()) {
                    $('#cfg_name').val(res.data.description);
                }
            }, 'json');
        }
    });

    // Handle Billing Target Logic
    $('#cfg_rule_target_type').change(function() {
        $('.target-room, .target-bed, .target-proc').hide();
        $('#cfg_target_room_id, #cfg_target_bed_id, #cfg_target_procedure_id').prop('required', false);
        
        let v = $(this).val();
        if(v === 'Room') { $('.target-room').show(); $('#cfg_target_room_id').prop('required', true); }
        else if(v === 'Bed') { $('.target-bed').show(); $('#cfg_target_bed_id').prop('required', true); }
        else if(v === 'Procedure') { $('.target-proc').show(); $('#cfg_target_procedure_id').prop('required', true); }
    });

    function showAppResponse(title, msg, type = 'success') {
        if(type === 'success') {
            $('#appResIcon').attr('class', 'fa-solid fa-circle-check text-success fa-4x mb-3');
            $('#appResBtn').attr('class', 'btn btn-success fw-bold px-4 mt-2');
        } else {
            $('#appResIcon').attr('class', 'fa-solid fa-circle-xmark text-danger fa-4x mb-3');
            $('#appResBtn').attr('class', 'btn btn-dark fw-bold px-4 mt-2');
        }
        $('#appResTitle').text(title);
        $('#appResMsg').text(msg);
        $('#appResponseModal').modal('show');
    }

    $('#cfg_nhis_covered').change(function() {
        if($(this).is(':checked')) $('#nhis_section').slideDown();
        else { $('#nhis_section').slideUp(); $('#cfg_copay_req').prop('checked', false).trigger('change'); }
    });

    $('#cfg_copay_req').change(function() {
        if($(this).is(':checked')) $('.copay-fld').slideDown();
        else $('.copay-fld').slideUp();
    });

    $('#cfg_corp_covered').change(function() {
        if($(this).is(':checked')) $('#corp_section').slideDown();
        else $('#corp_section').slideUp();
    });

    function renderCorporateRows(corporateData = {}) {
        let html = '';
        globalInsurances.forEach((ins, idx) => {
            let rowData = corporateData[ins.id] || { tariff_amount_adult: '0.00', tariff_amount_child: '0.00', is_copay_required: 0, copay_amount_adult: '0.00', copay_amount_child: '0.00' };
            let isChecked = rowData.is_copay_required == 1 ? 'checked' : '';
            
            html += `
            <div class="row g-2 mb-3 bg-info bg-opacity-10 p-3 rounded border border-info border-opacity-25">
                <div class="col-12"><h6 class="fw-bold text-info m-0"><i class="fa-solid fa-shield-halved me-1"></i> ${ins.name}</h6></div>
                <input type="hidden" name="corp_insurance_id[${idx}]" value="${ins.id}">
                
                <div class="col-md-6">
                    <label class="small fw-bold text-dark mb-1">Adult Tariff (GHS)</label>
                    <input type="number" step="any" name="corp_tariff_adult[${idx}]" class="form-control fw-bold border-info" value="${rowData.tariff_amount_adult}">
                </div>
                <div class="col-md-6">
                    <label class="small fw-bold text-dark mb-1">Child Tariff (GHS)</label>
                    <input type="number" step="any" name="corp_tariff_child[${idx}]" class="form-control fw-bold border-info" value="${rowData.tariff_amount_child}">
                </div>
                
                <div class="col-12 mt-2">
                    <div class="form-check form-switch border p-2 bg-white rounded shadow-sm">
                        <input class="form-check-input ms-1 corp-copay-switch" type="checkbox" data-idx="${idx}" name="corp_is_copay[${idx}]" value="1" ${isChecked} style="transform:scale(1.2); cursor:pointer;">
                        <label class="form-check-label ms-2 fw-bold text-warning small" style="cursor:pointer;">Requires Co-Payment</label>
                    </div>
                </div>

                <div class="col-md-6 corp-copay-target-${idx}" style="display:${isChecked ? 'block' : 'none'};">
                    <label class="small fw-bold text-warning mb-1">Adult Co-Pay (GHS)</label>
                    <input type="number" step="any" name="corp_copay_adult[${idx}]" class="form-control fw-bold border-warning" value="${rowData.copay_amount_adult}">
                </div>
                <div class="col-md-6 corp-copay-target-${idx}" style="display:${isChecked ? 'block' : 'none'};">
                    <label class="small fw-bold text-warning mb-1">Child Co-Pay (GHS)</label>
                    <input type="number" step="any" name="corp_copay_child[${idx}]" class="form-control fw-bold border-warning" value="${rowData.copay_amount_child}">
                </div>
            </div>`;
        });
        $('#corporate_tariffs_container').html(html);

        $('.corp-copay-switch').change(function() {
            let targetClass = `.corp-copay-target-${$(this).data('idx')}`;
            if($(this).is(':checked')) $(targetClass).slideDown();
            else $(targetClass).slideUp();
        });
    }

    window.loadConfigTab = function(tabName) {
        currentActiveTab = tabName;
        $('.config-tab-btn').removeClass('active');
        $(`button[onclick="loadConfigTab('${tabName}')"]`).addClass('active');

        if (tabName === 'access_rules') {
            $('#table_wrapper, #btnAddNew').hide();
            $('#access_rules_wrapper').fadeIn();
            loadAccessRules();
            return;
        }

        $('#access_rules_wrapper').hide();
        $('#table_wrapper, #btnAddNew').fadeIn();

        let titles = {
            'rooms': 'Operating Rooms Configuration',
            'beds': 'Theatre / Recovery Beds Configuration',
            'anesthesia': 'Anesthesia Billing Packages',
            'roles': 'Surgical Roles Configuration',
            'categories': 'Surgery Categories Configuration',
            'staff': 'Mapped Theatre Staff Directory',
            'procedures': 'Surgical Procedures & G-DRG Mapping',
            'billing_rules': 'Automated Theatre & Bed Charges'
        };
        $('#current_tab_title').text(titles[tabName]);
        
        initDataTable();
    };

    function loadAccessRules() {
        $.post(apiAccess, { action: 'fetch_access_rules' }, function(res) {
            if(res.status === 'success' && res.data) {
                $('#rl_new_dis').prop('checked', res.data.block_new_ipd_on_discharge == 1);
                $('#rl_edit_dis').prop('checked', res.data.block_edit_ipd_on_discharge == 1);
                $('#rl_new_th_req').prop('checked', res.data.block_new_ipd_on_theatre_req == 1);
                $('#rl_edit_th_req').prop('checked', res.data.block_edit_ipd_on_theatre_req == 1);
                $('#rl_new_th_rev').prop('checked', res.data.block_new_ipd_on_theatre_revert == 1);
                $('#rl_new_th_post').prop('checked', res.data.block_new_theatre_post_surgery == 1);
                $('#rl_edit_th_post').prop('checked', res.data.block_edit_theatre_post_surgery == 1);
            }
        }, 'json');
    }

    window.saveAccessRules = function() {
        let btn = $('#btnSaveRules'); let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
        
        $.post(apiAccess, $('#frmAccessRules').serialize(), function(res) {
            btn.prop('disabled', false).html(orig);
            if(res.status === 'success') {
                showAppResponse("Rules Updated", res.message, 'success');
            } else {
                showAppResponse("Save Failed", res.message, 'error');
            }
        }, 'json');
    };

    function initDataTable() {
        if ($.fn.DataTable.isDataTable('#tblConfig')) {
            $('#tblConfig').DataTable().destroy();
            $('#tblConfig').empty();
        }

        let columns = [];
        if (['rooms', 'roles', 'categories'].includes(currentActiveTab)) {
            columns = [
                { data: 'id', title: 'ID', className: 'fw-bold text-muted', width: '10%' },
                { data: 'name', title: 'Configuration Label', className: 'fw-bold text-dark' },
                { data: 'status_badge', title: 'Status', width: '15%' }
            ];
        } else if (currentActiveTab === 'beds') {
            columns = [
                { data: 'id', title: 'ID', className: 'fw-bold text-muted', width: '10%' },
                { data: 'name', title: 'Bed Name / Number', className: 'fw-bold text-dark' },
                { data: 'room_name', title: 'Linked Operating Room', className: 'text-primary' },
                { data: 'status_badge', title: 'Status', width: '15%' }
            ];
        } else if (currentActiveTab === 'billing_rules') {
            columns = [
                { data: 'service_name', title: 'Service Billed', className: 'fw-bold text-danger' },
                { 
                    data: null, title: 'Execution Scope', 
                    render: function(r) {
                        if(r.rule_target_type === 'Global') return '<span class="badge bg-secondary shadow-sm">Global - All Theatres</span>';
                        if(r.rule_target_type === 'Room') return `<span class="badge bg-primary shadow-sm">Room: ${r.room_name}</span>`;
                        if(r.rule_target_type === 'Bed') return `<span class="badge bg-info text-dark shadow-sm">Bed: ${r.bed_name}</span>`;
                        if(r.rule_target_type === 'Procedure') return `<span class="badge bg-dark shadow-sm">Procedure: ${r.procedure_name}</span>`;
                        return r.rule_target_type;
                    } 
                },
                { data: 'frequency_name', title: 'Frequency', render: d => d || 'One-Time' },
                { data: 'status_badge', title: 'Status', width: '10%' }
            ];
        } else if (currentActiveTab === 'staff') {
            columns = [
                { data: 'id', title: 'ID', className: 'fw-bold text-muted', width: '10%' },
                { data: 'staff_name', title: 'Doctor / Staff Name', className: 'fw-bold text-primary' },
                { data: 'role_name', title: 'Theatre Role', className: 'fw-bold text-dark' },
                { data: 'status_badge', title: 'Status', width: '15%' }
            ];
        } else if (currentActiveTab === 'procedures') {
            columns = [
                { data: 'name', title: 'Procedure Name', className: 'fw-bold text-dark' },
                { data: 'department_name', title: 'Department', render: d => d || 'Uncategorized' },
                { data: 'category_name', title: 'Category', render: d => d || 'Uncategorized' },
                { data: 'gdrg_code', title: 'G-DRG Mapping', render: (d, t, r) => d ? `<span class="badge bg-success shadow-sm">[${d}]</span><br><span class="small text-muted">${r.gdrg_desc || ''}</span>` : `<span class="badge bg-secondary shadow-sm">Unmapped</span>` },
                { data: 'status_badge', title: 'Status', width: '10%' }
            ];
        } else if (currentActiveTab === 'anesthesia') {
            columns = [
                { data: 'name', title: 'Anesthesia Type', className: 'fw-bold text-dark' },
                { data: 'linked_procedure', title: 'Linked Procedure', render: d => d ? `<b class="text-primary">${d}</b>` : `<span class="text-muted">Global / Unlinked</span>` },
                {
                    data: null, title: 'Pricing & Coverages',
                    render: function(r) {
                        let cash = `A: <span class="text-danger">GHS ${parseFloat(r.cash_price_adult || 0).toFixed(2)}</span> | C: <span class="text-danger">GHS ${parseFloat(r.cash_price_child || 0).toFixed(2)}</span>`;
                        let nhis = r.nhis_covered == 1 ? `<span class="badge bg-success mt-1 shadow-sm"><i class="fa fa-check"></i> NHIS</span>` : '';
                        let corp = r.corp_covered == 1 ? `<span class="badge bg-info text-dark mt-1 shadow-sm"><i class="fa fa-check"></i> CORP</span>` : '';
                        return `<span class="small fw-bold">${cash}<br>${nhis} ${corp}</span>`;
                    }
                },
                { data: 'status_badge', title: 'Status', width: '10%' }
            ];
        }

        columns.push({
            data: null, title: 'Action', className: 'text-end', width: '15%', orderable: false,
            render: function(data, type, row) {
                let toggleClass = row.is_active == 1 ? 'text-warning' : 'text-success';
                let toggleIcon = row.is_active == 1 ? 'fa-ban' : 'fa-check';
                let toggleAction = row.is_active == 1 ? 0 : 1;
                let payload = btoa(unescape(encodeURIComponent(JSON.stringify(row))));

                return `
                <button class="btn btn-sm btn-light border text-primary shadow-sm" onclick="editConfig('${payload}')" title="Edit"><i class="fa-solid fa-pen"></i></button>
                <button class="btn btn-sm btn-light border ${toggleClass} shadow-sm ms-1" onclick="toggleStatus(${row.id}, ${toggleAction})" title="Toggle Status"><i class="fa-solid ${toggleIcon}"></i></button>
                <button class="btn btn-sm btn-light border text-danger shadow-sm ms-1" onclick="deleteConfig(${row.id})" title="Delete Permanently"><i class="fa-solid fa-trash"></i></button>`;
            }
        });

        dtConfig = $('#tblConfig').DataTable({
            ajax: {
                url: apiConfig,
                type: 'POST',
                data: function(d) { d.action = 'fetch_config'; d.config_type = currentActiveTab; },
                dataSrc: function (json) {
                    if (json.status === 'error') { showAppResponse("System Error", json.message, 'error'); return []; }
                    return json.data || [];
                }
            },
            pageLength: 10,
            autoWidth: false,
            columns: columns
        });
    }

    window.openConfigModal = function() {
        $('#frmConfig')[0].reset();
        $('#cfg_id').val('');
        $('#cfg_type').val(currentActiveTab);
        $('.select2-modal').val('').trigger('change');
        
        setupModalUI();
        if (currentActiveTab === 'anesthesia') {
            renderCorporateRows({}); 
            $('#cfg_nhis_covered').prop('checked', false).trigger('change');
            $('#cfg_corp_covered').prop('checked', false).trigger('change');
        }
        $('#configModal').modal('show');
    };

    window.editConfig = function(payloadBase64) {
        let row = JSON.parse(decodeURIComponent(escape(atob(payloadBase64))));
        $('#frmConfig')[0].reset();
        $('#cfg_id').val(row.id);
        $('#cfg_type').val(currentActiveTab);
        
        setupModalUI();

        if (['rooms', 'roles', 'categories'].includes(currentActiveTab)) {
            $('#cfg_name').val(row.name);
            $('#configModal').modal('show');
        } else if (currentActiveTab === 'beds') {
            $('#cfg_name').val(row.name);
            $('#cfg_bed_room_id').val(row.room_id).trigger('change');
            $('#configModal').modal('show');
        } else if (currentActiveTab === 'billing_rules') {
            $('#cfg_rule_target_type').val(row.rule_target_type).trigger('change');
            $('#cfg_target_room_id').val(row.room_id).trigger('change');
            $('#cfg_target_bed_id').val(row.bed_id).trigger('change');
            $('#cfg_target_procedure_id').val(row.procedure_id).trigger('change');
            $('#cfg_charge_service_id').val(row.service_id).trigger('change');
            $('#cfg_charge_frequency_id').val(row.frequency_id).trigger('change');
            $('#configModal').modal('show');
        } else if (currentActiveTab === 'staff') {
            $('#cfg_staff_id').val(row.staff_id).trigger('change');
            $('#cfg_role_id').val(row.role_id).trigger('change');
            $('#configModal').modal('show');
        } else if (currentActiveTab === 'procedures') {
            $('#cfg_name').val(row.name);
            $('#cfg_dept_id').val(row.department_id).trigger('change');
            $('#cfg_category_id').val(row.category_id).trigger('change');
            $('#cfg_gdrg_proc').val(row.gdrg_code).trigger('change');
            $('#configModal').modal('show');
        } else if (currentActiveTab === 'anesthesia') {
            $('#cfg_name').val(row.name);
            $('#cfg_procedure_id_anes').val(row.procedure_id).trigger('change');
            
            if(row.service_id) {
                $('#btnSaveConfig').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Loading Billing Map...');
                $.post(apiConfig, { action: 'get_service_pricing', service_id: row.service_id }, function(res) {
                    $('#btnSaveConfig').prop('disabled', false).html('Save Master Catalog Record');
                    if(res.status === 'success') {
                        let svc = res.service;
                        $('#cfg_age').val(svc.target_age_group || 'All Ages');
                        $('#cfg_gender').val(svc.applicable_gender || 'Both');
                        $('#cfg_cash_adult').val(svc.cash_price_adult || '0.00');
                        $('#cfg_cash_child').val(svc.cash_price_child || '0.00');
                        
                        $('#cfg_nhis_covered').prop('checked', svc.nhis_covered == 1).trigger('change');
                        $('#cfg_tariff_adult').val(svc.tariff_adult || '0.00');
                        $('#cfg_tariff_child').val(svc.tariff_child || '0.00');

                        $('#cfg_copay_req').prop('checked', svc.is_copay_required == 1).trigger('change');
                        $('#cfg_copay_adult').val(svc.nhis_copay_adult || '0.00');
                        $('#cfg_copay_child').val(svc.nhis_copay_child || '0.00');

                        $('#cfg_corp_covered').prop('checked', svc.corp_covered == 1).trigger('change');
                        renderCorporateRows(res.corporate);
                    }
                    $('#configModal').modal('show');
                }, 'json').fail(function() {
                    $('#btnSaveConfig').prop('disabled', false).html('Save Master Catalog Record');
                    showAppResponse("Server Error", "Could not load the pricing data. Check your network.", 'error');
                });
            } else {
                $('#cfg_cash_adult').val('0.00'); $('#cfg_cash_child').val('0.00');
                renderCorporateRows({}); 
                $('#configModal').modal('show');
            }
        }
    };

    function setupModalUI() {
        $('#grp_name, .pricing-fld, #grp_cat, #grp_gdrg_proc, #grp_staff, #grp_role, #grp_proc_link, #grp_dept, #grp_bed_room, .billing-fld').hide();
        $('#cfg_name, #cfg_staff_id, #cfg_role_id, #cfg_category_id, #cfg_gdrg_proc, #cfg_dept_id, #cfg_bed_room_id, #cfg_charge_service_id').prop('required', false);

        if (['rooms', 'roles', 'categories'].includes(currentActiveTab)) {
            $('#grp_name').show();
            $('#lbl_name').html(`Configuration Name <span class="text-danger">*</span>`);
            $('#cfg_name').prop('required', true);
        } else if (currentActiveTab === 'beds') {
            $('#grp_name, #grp_bed_room').show();
            $('#lbl_name').html(`Bed Name / Number <span class="text-danger">*</span>`);
            $('#cfg_name, #cfg_bed_room_id').prop('required', true);
        } else if (currentActiveTab === 'billing_rules') {
            $('.billing-fld').show();
            $('#cfg_charge_service_id').prop('required', true);
            $('#cfg_rule_target_type').trigger('change');
        } else if (currentActiveTab === 'staff') {
            $('#grp_staff, #grp_role').show();
            $('#cfg_staff_id, #cfg_role_id').prop('required', true);
        } else if (currentActiveTab === 'procedures') {
            $('#grp_name, #grp_dept, #grp_cat, #grp_gdrg_proc').show();
            $('#cfg_name, #cfg_dept_id, #cfg_category_id, #cfg_gdrg_proc').prop('required', true);
            $('#lbl_name').html(`Surgical Procedure Name <span class="text-danger">*</span>`);
        } else if (currentActiveTab === 'anesthesia') {
            $('#grp_name, #grp_proc_link, .pricing-fld').show();
            $('#cfg_name').prop('required', true);
            $('#lbl_name').html(`Anesthesia Billing Name <span class="text-danger">*</span>`);
        }
    }

    $('#frmConfig').off('submit').on('submit', function(e) {
        e.preventDefault();
        let btn = $('#btnSaveConfig'); let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Saving...');

        $.post(apiConfig, $(this).serialize(), function(res) {
            btn.prop('disabled', false).html(orig);
            if(res.status === 'success') {
                $('#configModal').modal('hide');
                showAppResponse("Saved", res.message, 'success');
                loadDependencies();
                if (dtConfig) dtConfig.ajax.reload(null, false);
            } else {
                showAppResponse("Save Error", res.message, 'error');
            }
        }, 'json').fail(function(xhr, status, error) {
            btn.prop('disabled', false).html(orig);
            showAppResponse("Server Error", "A fatal server error occurred during the save operation.", 'error');
            console.error("AJAX Error:", status, error, xhr.responseText);
        });
    });

    window.toggleStatus = function(id, newStatus) {
        $.post(apiConfig, { action: 'toggle_status', config_type: currentActiveTab, id: id, new_status: newStatus }, function(res) {
            if(res.status === 'success') {
                if (dtConfig) dtConfig.ajax.reload(null, false);
            } else {
                showAppResponse("Toggle Error", res.message, 'error');
            }
        }, 'json');
    };

    window.deleteConfig = function(id) {
        pendingDeleteId = id;
        $('#deleteModal').modal('show');
    };

    $('#btnConfirmDelete').off('click').on('click', function() {
        if(!pendingDeleteId) return;
        
        let btn = $(this); let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

        $.post(apiConfig, { action: 'delete_config', config_type: currentActiveTab, id: pendingDeleteId }, function(res) {
            $('#deleteModal').modal('hide');
            btn.prop('disabled', false).html(orig);

            if(res.status === 'success') {
                showAppResponse("Deleted", res.message, 'success');
                loadDependencies();
                if (dtConfig) dtConfig.ajax.reload(null, false);
            } else {
                showAppResponse("Cannot Delete", res.message, 'error');
            }
            pendingDeleteId = null;
        }, 'json');
    });

    loadConfigTab('rooms');
};