let dtWards, dtRooms, dtBeds, dtWardCats, dtRoomCats, dtSvcCats, dtFreqCats, dtFloors, dtCharges, dtIpdServices;

window.dbInsurances = []; 

window.initRoomWardManagement = function() {
    const apiUrl = '/rimax/application/dripend/systemSetup/ipd/processRoomWard.php';

    const renderIndex = (data, type, row, meta) => `<strong>${meta.row + 1}</strong>`;
    const renderStatus = (data) => data == 1 ? '<span class="badge bg-success bg-opacity-10 text-success border border-success">Active</span>' : '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger">Inactive</span>';
    
    const renderActions = (table, id, isActive) => {
        let toggleClass = isActive == 1 ? 'btn-outline-warning' : 'btn-outline-success';
        let toggleText = isActive == 1 ? '<i class="fa fa-pause"></i> Freeze' : '<i class="fa fa-play"></i> Unfreeze';
        let toggleStatus = isActive == 1 ? 0 : 1;
        
        let editBtn = '';
        if(table !== 'ipd_beds' && table !== 'ipd_billing_rules') {
            editBtn = `<button class="btn btn-sm btn-primary" onclick="editRecord('${table}', ${id})" title="Update Record"><i class="fa fa-edit"></i> Edit</button>`;
        }

        return `
            <div class="btn-group shadow-sm">
                ${editBtn}
                <button class="btn btn-sm ${toggleClass}" onclick="toggleStatus('${table}', ${id}, ${toggleStatus})" title="Change Status">${toggleText}</button>
                <button class="btn btn-sm btn-danger" onclick="deleteRecord('${table}', ${id})" title="Delete Record"><i class="fa fa-trash"></i></button>
            </div>
        `;
    };

    window.loadKPIs = function() {
        $.post(apiUrl, { action: 'fetch_kpis' }, function(res) {
            if(res && res.status === 'success') {
                $('#kpi-wards').text(res.data.wards);
                $('#kpi-rooms').text(res.data.rooms);
                $('#kpi-beds').text(res.data.beds);
                $('#kpi-rules').text(res.data.rules);
            }
        }, 'json');
    };

    window.loadDynamicDropdowns = function() {
        $.post(apiUrl, { action: 'fetch_dynamic_dropdowns' }, function(res) {
            if(res && res.status === 'success') {
                window.dbInsurances = res.data.insurances; 

                let wOpts = '<option value="">Select Ward</option>';
                res.data.wards.forEach(w => wOpts += `<option value="${w.id}">${w.ward_name}</option>`);
                $('#room_ward_id, #bed_ward_id, #charge_ward_id').html(wOpts);

                let wcOpts = '<option value="">Select Category</option>';
                res.data.ward_cats.forEach(c => wcOpts += `<option value="${c.id}">${c.type_name}</option>`);
                $('#ward_type_id').html(wcOpts);

                let rcOpts = '<option value="">Select Category</option>';
                res.data.room_cats.forEach(c => rcOpts += `<option value="${c.id}">${c.type_name}</option>`);
                $('#room_type_id').html(rcOpts);

                let scOpts = '<option value="">Select Service Category</option>';
                res.data.svc_cats.forEach(c => scOpts += `<option value="${c.id}">${c.category_name}</option>`);
                $('#ipd_svc_cat').html(scOpts);

                let fOpts = '<option value="">Select Frequency</option>';
                res.data.freqs.forEach(c => fOpts += `<option value="${c.id}">${c.frequency_name} (${c.interval_days} Days)</option>`);
                $('#charge_freq_id').html(fOpts);

                let bOpts = '<option value="">Select Building / Block</option>';
                res.data.blocks.forEach(c => bOpts += `<option value="${c.id}">${c.block_name}</option>`);
                $('#dict_block').html(bOpts);

                let floorOpts = '<option value="">Select Floor/Location</option>';
                for (const [blockName, floors] of Object.entries(res.data.grouped_floors)) {
                    floorOpts += `<optgroup label="${blockName}">`;
                    floors.forEach(f => {
                        floorOpts += `<option value="${f.id}">${f.floor_name}</option>`;
                    });
                    floorOpts += `</optgroup>`;
                }
                $('#ward_floor_id').html(floorOpts);

                let sOpts = '<option value="">Select IPD Service...</option>';
                res.data.ipd_services.forEach(s => {
                    sOpts += `<option value="${s.id}">[${s.category_name}] ${s.service_name} (Cash: ${s.cash_price_adult})</option>`;
                });
                $('#charge_service_id').html(sOpts);
            }
        }, 'json');
    };

    // DATATABLES
    dtWards = $('#tblWards').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_wards' } }, columns: [{ data: null, render: renderIndex }, { data: 'ward_name', render: d => `<b>${d}</b>` }, { data: 'clinic_name' }, { data: 'location_name', render: d => `<span class='text-muted small'><i class='fa fa-map-marker-alt'></i> ${d}</span>` }, { data: 'category_name' }, { data: 'physical_bed_capacity', render: d => `<span class='badge bg-secondary'>${d} Beds</span>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_wards', r.id, r.is_active) }]});
    dtRooms = $('#tblRooms').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_rooms' } }, columns: [{ data: null, render: renderIndex }, { data: 'room_number_or_name', render: d => `<b>${d}</b>` }, { data: 'ward_name' }, { data: 'category_name' }, { data: 'room_nightly_rate', render: d => parseFloat(d).toFixed(2) }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_rooms', r.id, r.is_active) }]});
    dtBeds = $('#tblBeds').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_beds' } }, columns: [{ data: null, render: renderIndex }, { data: 'bed_number', render: d => `<b><i class='fa fa-bed'></i> ${d}</b>` }, { data: 'room_name', render: d => `<span class='badge bg-light text-dark border'>${d}</span>` }, { data: 'ward_name' }, { data: 'status_name', render: d => `<span class='badge bg-info text-dark'>${d}</span>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_beds', r.id, r.is_active) }]});
    
    dtIpdServices = $('#tblIpdServices').DataTable({
        ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_ipd_services' } },
        columns: [
            { data: null, render: renderIndex }, 
            { data: 'service_name', render: d => `<b>${d}</b>` }, 
            { data: 'category_name' },
            { data: null, render: (d,t,r) => `Ad: ${parseFloat(r.cash_price_adult).toFixed(2)}<br><span class="text-muted small">Ch: ${parseFloat(r.cash_price_child).toFixed(2)}</span>` }, 
            { data: null, render: (d,t,r) => r.is_nhis_covered == 1 ? `<span class="badge bg-success">NHIS Covered</span>` : '<span class="badge bg-secondary">Cash Only</span>' },
            { data: 'is_active', render: renderStatus }, 
            { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_services', r.id, r.is_active) }
        ]
    });

    dtCharges = $('#tblWardCharges').DataTable({
        ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_ward_charges' } },
        columns: [
            { data: null, render: renderIndex }, { data: 'ward_name' }, { data: 'room_name', render: d => `<span class='badge bg-light text-dark border'>${d}</span>` }, 
            { data: 'service_name', render: d => `<b>${d}</b>` }, { data: 'category_name' }, { data: 'frequency_name' },
            { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_billing_rules', r.id, r.is_active) }
        ]
    });

    // Master Dictionaries
    dtWardCats = $('#tblWardCategories').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'ward_cat' } }, columns: [{ data: null, render: renderIndex }, { data: 'name' }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_ward_types', r.id, r.is_active) }]});
    dtRoomCats = $('#tblRoomCategories').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'room_cat' } }, columns: [{ data: null, render: renderIndex }, { data: 'name' }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_room_types', r.id, r.is_active) }]});
    dtSvcCats = $('#tblSvcCategories').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'svc_cat' } }, columns: [{ data: null, render: renderIndex }, { data: 'name' }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_service_categories', r.id, r.is_active) }]});
    dtFreqCats = $('#tblFreqCategories').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'freq_cat' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: (d,t,r) => `${d} <span class="badge bg-secondary">${r.interval_days} Days</span>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_charge_frequencies', r.id, r.is_active) }]});
    dtFloors = $('#tblFloors').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_floors' } }, columns: [{ data: null, render: renderIndex }, { data: 'floor_name' }, { data: 'block_name' }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_facility_floors', r.id, r.is_active) }]});

    // =====================================
    // UI DYNAMIC TOGGLES
    // =====================================
    
    $('#bed_assignment_type').on('change', function() {
        if ($(this).val() === 'room') { 
            $('#div_bed_room').slideDown(); 
            $('#bed_room_id').prop('required', true);
            $('#bed_ward_id').trigger('change');
        } else { 
            $('#div_bed_room').slideUp(); 
            $('#bed_room_id').prop('required', false).html('<option value="">Select Ward First</option>');
        }
    });

    $('#bed_ward_id').on('change', function() {
        if($('#bed_assignment_type').val() !== 'room') return;
        let ward_id = $(this).val();
        if(!ward_id) { $('#bed_room_id').html('<option value="">Select Ward First</option>'); return; }
        
        $.post(apiUrl, { action: 'get_ward_rooms', ward_id: ward_id }, function(res) { 
            let html = '<option value="">Select Room</option>';
            if(res.status === 'success' && res.data.length > 0) {
                res.data.forEach(r => html += `<option value="${r.id}">${r.room_number_or_name}</option>`);
            } else {
                html = '<option value="">-- No Rooms Configured For This Ward --</option>';
            }
            $('#bed_room_id').html(html); 
        }, 'json');
    });

    $('#charge_ward_id').on('change', function() {
        let ward_id = $(this).val();
        if(!ward_id) { 
            $('#charge_room_id').html('<option value="">-- Apply to Entire Ward --</option>'); 
            return; 
        }
        $.post(apiUrl, { action: 'get_ward_rooms', ward_id: ward_id }, function(res) { 
            let html = '<option value="">-- Apply to Entire Ward --</option>';
            if(res.status === 'success' && res.data.length > 0) {
                res.data.forEach(r => html += `<option value="${r.id}">${r.room_number_or_name}</option>`);
            }
            $('#charge_room_id').html(html); 
        }, 'json');
    });

    $('#dict_type').on('change', function() {
        let v = $(this).val();
        
        if (v === 'freq_cat') { $('#div_interval_days').slideDown(); $('#dict_interval').prop('required', true); } 
        else { $('#div_interval_days').slideUp(); $('#dict_interval').prop('required', false); }
        
        if (v === 'floor') { $('#div_block_id').slideDown(); $('#dict_block').prop('required', true); } 
        else { $('#div_block_id').slideUp(); $('#dict_block').prop('required', false); }
    });

    $('#ipd_svc_nhis').on('change', function() {
        if($(this).is(':checked')) { $('#div_nhis_pricing').slideDown(); } else { $('#div_nhis_pricing').slideUp(); }
    });

    window.addCorporateRow = function(ins_id = '', tariff = '0.00', cp_a = '0.00', cp_c = '0.00') {
        let options = '<option value="">Select Insurance</option>';
        if(window.dbInsurances && window.dbInsurances.length > 0) {
            window.dbInsurances.forEach(i => {
                let selected = (i.id == ins_id) ? 'selected' : '';
                options += `<option value="${i.id}" ${selected}>${i.insurance_name}</option>`;
            });
        }
        
        let rowId = 'corp_row_' + Date.now() + Math.floor(Math.random() * 100);
        let row = `
        <div class="card bg-white border border-info mb-2 corp-row" id="${rowId}">
            <div class="card-header bg-info bg-opacity-10 py-2 px-3 d-flex justify-content-between align-items-center">
                <span class="small text-info fw-bold"><i class="fa-solid fa-shield-halved"></i> Corporate Policy Override</span>
                <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2" onclick="$('#${rowId}').remove()"><i class="fa fa-times"></i></button>
            </div>
            <div class="card-body p-3">
                <div class="row g-2">
                    <div class="col-12">
                        <select name="corp_insurance_id[]" class="form-select form-select-sm" required>${options}</select>
                    </div>
                    <div class="col-4">
                        <label class="small text-muted mb-1">Flat Tariff</label>
                        <input type="number" step="0.01" name="corp_tariff[]" class="form-control form-control-sm" value="${tariff}">
                    </div>
                    <div class="col-4">
                        <label class="small text-muted mb-1">Adult Copay</label>
                        <input type="number" step="0.01" name="corp_copay_adult[]" class="form-control form-control-sm" value="${cp_a}">
                    </div>
                    <div class="col-4">
                        <label class="small text-muted mb-1">Child Copay</label>
                        <input type="number" step="0.01" name="corp_copay_child[]" class="form-control form-control-sm" value="${cp_c}">
                    </div>
                </div>
            </div>
        </div>`;
        $('#corporate_container').append(row);
    };

    // FORM SUBMISSIONS
    $('form').on('submit', function(e) {
        e.preventDefault();
        let form = $(this);
        let formId = form.attr('id');

        if(formId === 'frmCategory') { $('#dict_type').prop('disabled', false); }

        $.post(apiUrl, form.serialize(), function(res) {
            if(res && res.status === 'success') {
                
                if (formId === 'frmIpdService') { resetServiceForm(); $('.modal').modal('hide'); } 
                else if (formId === 'frmCategory') { form[0].reset(); $('#dict_id').val(''); $('.modal').modal('hide'); }
                else { form[0].reset(); form.find('input[name="id"]').val(''); $('.modal').modal('hide'); }
                
                dtWards.ajax.reload(null, false); dtRooms.ajax.reload(null, false); dtBeds.ajax.reload(null, false);
                dtWardCats.ajax.reload(null, false); dtRoomCats.ajax.reload(null, false); dtFloors.ajax.reload(null, false);
                dtSvcCats.ajax.reload(null, false); dtFreqCats.ajax.reload(null, false);
                dtCharges.ajax.reload(null, false); dtIpdServices.ajax.reload(null, false);
                
                loadKPIs(); loadDynamicDropdowns(); 
            } else { 
                alert('Database Error: ' + (res.message || 'Unknown Error')); 
                if(formId === 'frmCategory' && $('#dict_id').val() !== '') { $('#dict_type').prop('disabled', true); }
            }
        }, 'json').fail(function() {
            alert('Failed to process. Check network console for JSON response errors.');
        });
    });

    loadKPIs();
    loadDynamicDropdowns();
};

window.resetServiceForm = function() {
    $('#frmIpdService')[0].reset(); 
    $('#ipd_service_id').val(''); 
    $('#ipd_svc_nhis').trigger('change'); 
    $('#corporate_container').empty();
};

window.openModal = function(type) {
    if(type === 'Dictionary') {
        $('#frmCategory')[0].reset();
        $('#dict_id').val('');
        $('#dict_type').prop('disabled', false).trigger('change');
        $('#modalDictionary').modal('show');
    } else {
        let frmId = (type === 'BedGen' || type === 'BillingRule') ? 'frm' : 'frm' + type;
        if($('#'+frmId).length > 0) $('#'+frmId)[0].reset();
        $('#' + type.toLowerCase() + '_id').val('');
        $('#modal' + type).modal('show');
    }
}

window.editRecord = function(table, id) {
    if(table === 'ipd_setup_ward_types' || table === 'ipd_setup_room_types' || table === 'ipd_service_categories' || table === 'ipd_charge_frequencies' || table === 'ipd_facility_floors') { 
        let dictType = '';
        if(table === 'ipd_setup_ward_types') dictType = 'ward_cat';
        if(table === 'ipd_setup_room_types') dictType = 'room_cat';
        if(table === 'ipd_service_categories') dictType = 'svc_cat';
        if(table === 'ipd_charge_frequencies') dictType = 'freq_cat';
        if(table === 'ipd_facility_floors') dictType = 'floor';

        $.post('/rimax/application/dripend/systemSetup/ipd/processRoomWard.php', { action: 'fetch_dictionaries', dict_type: dictType }, function(res) {
            if(res.status === 'success') {
                let rec = res.data.find(x => x.id == id);
                if(rec) {
                    $('#dict_id').val(rec.id); 
                    $('#dict_type').val(dictType).trigger('change').prop('disabled', true);
                    $('#dict_name').val(rec.name);
                    
                    if (dictType === 'freq_cat') {
                        $('#dict_interval').val(rec.interval_days);
                        $('#div_interval_days').show();
                    } else if (dictType === 'floor') {
                        $('#dict_block').val(rec.block_id);
                        $('#div_block_id').show();
                    }
                    
                    $('#modalDictionary').modal('show');
                }
            }
        }, 'json');
    }
    else if(table === 'ipd_wards' || table === 'ipd_rooms') {
        $.post('/rimax/application/dripend/systemSetup/ipd/processRoomWard.php', { action: 'get_record', table: table, id: id }, function(res) {
            if(res.status === 'success') {
                let data = res.data;
                if(table === 'ipd_wards') {
                    $('#ward_id').val(data.id); $('#ward_name').val(data.ward_name); 
                    $('#ward_type_id').val(data.ward_type_id); $('#ward_floor_id').val(data.floor_id);
                    $('#wardModalTitle').text('Edit Ward Details'); $('#modalWard').modal('show');
                } else {
                    $('#room_id').val(data.id); $('#room_name').val(data.room_number_or_name); 
                    $('#room_ward_id').val(data.ward_id); $('#room_type_id').val(data.room_type_id); $('#room_nightly_rate').val(data.room_nightly_rate);
                    $('#roomModalTitle').text('Edit Room Details'); $('#modalRoom').modal('show');
                }
            }
        }, 'json');
    }
    else if(table === 'ipd_services') {
        $.post('/rimax/application/dripend/systemSetup/ipd/processRoomWard.php', { action: 'get_record', table: table, id: id }, function(res) {
            if(res.status === 'success') {
                let data = res.data;
                resetServiceForm();
                
                $('#ipd_service_id').val(data.id);
                $('#ipd_svc_name').val(data.service_name);
                $('#ipd_svc_cat').val(data.category_id);
                $('#ipd_svc_cash_a').val(data.cash_price_adult);
                $('#ipd_svc_cash_c').val(data.cash_price_child);
                
                if(data.is_nhis_covered == 1) { 
                    $('#ipd_svc_nhis').prop('checked', true).trigger('change'); 
                    $('#ipd_svc_nhis_t_a').val(data.nhis_tariff_adult); 
                    $('#ipd_svc_nhis_t_c').val(data.nhis_tariff_child); 
                    $('#ipd_svc_nhis_cp_a').val(data.nhis_copay_adult);
                    $('#ipd_svc_nhis_cp_c').val(data.nhis_copay_child);
                }
                
                if(data.corporate_tariffs && data.corporate_tariffs.length > 0) {
                    data.corporate_tariffs.forEach(c => {
                        addCorporateRow(c.insurance_type_id, c.tariff_amount, c.copay_amount_adult, c.copay_amount_child);
                    });
                }

                $('#modalIpdService').modal('show');
            }
        }, 'json');
    }
}

window.toggleStatus = function(table, id, newStatus) {
    $.post('/rimax/application/dripend/systemSetup/ipd/processRoomWard.php', { action: 'toggle_status', table: table, id: id, status: newStatus }, function(res) {
        if(res && res.status === 'success') { 
            dtWards.ajax.reload(null, false); dtRooms.ajax.reload(null, false); dtBeds.ajax.reload(null, false);
            dtWardCats.ajax.reload(null, false); dtRoomCats.ajax.reload(null, false); dtSvcCats.ajax.reload(null, false); 
            dtFreqCats.ajax.reload(null, false); dtFloors.ajax.reload(null, false);
            dtCharges.ajax.reload(null, false); dtIpdServices.ajax.reload(null, false);
            window.loadKPIs(); window.loadDynamicDropdowns();
        } 
    }, 'json');
}

window.deleteRecord = function(table, id) {
    if(!confirm("WARNING: This will permanently delete the record. If it has been used in transactions, the system will block the deletion and require you to 'Freeze' it instead. Proceed?")) return;
    $.post('/rimax/application/dripend/systemSetup/ipd/processRoomWard.php', { action: 'delete_record', table: table, id: id }, function(res) {
        if(res && res.status === 'success') { 
            dtWards.ajax.reload(null, false); dtRooms.ajax.reload(null, false); dtBeds.ajax.reload(null, false);
            dtWardCats.ajax.reload(null, false); dtRoomCats.ajax.reload(null, false); dtSvcCats.ajax.reload(null, false); 
            dtFreqCats.ajax.reload(null, false); dtFloors.ajax.reload(null, false);
            dtCharges.ajax.reload(null, false); dtIpdServices.ajax.reload(null, false);
            window.loadKPIs(); window.loadDynamicDropdowns();
        } else { alert('Cannot Delete: ' + res.message); }
    }, 'json');
}