$(document).ready(function() {
    const apiUrl = '/rimax/application/dripend/includes/ipd/processAdmitPatient.php';
    const cccApiUrl = '/rimax/application/dripend/nhisClaimCheckCode/nhisCCC.php';
    let pendingTable;
    let isFiltered = false;
    window.patientSearchData = [];

    $.fn.dataTable.ext.errMode = 'none';

    function appAlert(title, message, type = 'info') {
        let iconHtml = '';
        if(type === 'success') iconHtml = '<i class="fa-solid fa-circle-check fa-3x text-success mb-2"></i>';
        else if(type === 'error') iconHtml = '<i class="fa-solid fa-circle-xmark fa-3x text-danger mb-2"></i>';
        else if(type === 'warning') iconHtml = '<i class="fa-solid fa-triangle-exclamation fa-3x text-warning mb-2"></i>';
        else iconHtml = '<i class="fa-solid fa-circle-info fa-3x text-primary mb-2"></i>';

        $('#appNotifIcon').html(iconHtml);
        $('#appNotifTitle').text(title);
        $('#appNotifMsg').text(message);
        $('#appNotificationModal').modal('show');
    }
    window.appAlert = appAlert;

    window.loadPendingQueue = function(force = false) {
        // Enforce manual filter application
        if(!force && !isFiltered) {
            if(pendingTable) pendingTable.destroy();
            pendingTable = $('#tbl_pending_requests').DataTable({ data: [], language: { emptyTable: "Please apply a filter to view pending admission requests." }});
            return;
        }
        isFiltered = true;

        if(pendingTable) { pendingTable.destroy(); }
        let startDate = $('#filter_start').val();
        let endDate = $('#filter_end').val();
        let wardFilter = $('#filter_ward').val();

        pendingTable = $('#tbl_pending_requests').DataTable({
            ajax: { 
                url: apiUrl, 
                type: 'POST', 
                data: { action: 'fetch_pending_requests', start_date: startDate, end_date: endDate, ward: wardFilter },
                error: function () {
                    $('#tbl_pending_requests tbody').html('<tr><td colspan="6" class="text-center text-danger py-4 fw-bold">Failed to load OPD queue. Check connection.</td></tr>');
                }
            },
            pageLength: 10,
            columns: [
                { data: 'created_at', render: d => `<span class="text-muted fw-bold">${new Date(d).toLocaleString()}</span>` },
                { data: 'patient_no', render: d => `<b class="text-primary">${d}</b>` },
                { data: 'patient_name', render: d => `<b style="color:#0f172a;">${d}</b>` },
                { data: 'requested_ward', render: d => `<span class="badge bg-secondary rounded-pill px-2 py-1">${d}</span>` },
                { data: 'doctor_name', render: d => `<span class="text-muted fw-bold">${d}</span>` },
                { data: null, className: 'text-end pe-4', render: function(data, type, row) {
                    return `<button class="btn btn-outline-primary btn-cute" onclick="startOPDAdmission(${row.request_id})">Admit</button>`;
                }}
            ],
            language: { emptyTable: "No pending admission requests found for the selected filter." }
        });
    }

    loadPendingQueue(false); // Init empty
    loadDictionaries();
    loadWardsMatrix();

    $('#chkReferral').change(function() {
        if($(this).is(':checked')) {
            $('.ref_field').slideDown();
        } else {
            $('.ref_field').slideUp();
            $('input[name="referral_facility"], input[name="referral_date"]').val('');
        }
    });

    function populatePatientDetails(p) {
        let fullName = p.patient_name || p.full_name || $.trim((p.first_name || '') + ' ' + (p.last_name || ''));
        $('#disp_name').text(fullName);
        $('#disp_no').text(p.patient_no);
        $('#disp_gender_age').text(`${p.gender} / ${p.age} yrs`);
        $('#disp_mobile').text(p.mobile || 'N/A');
        $('#disp_id').text(p.ghana_card_no || 'N/A');
        $('#disp_address').text(p.patient_address || 'N/A');
        
        $('#disp_blood').html(`<i class="fa-solid fa-droplet me-1"></i> Blood: ${p.blood_group || 'N/A'}`);
        $('#disp_allergy').html(`<i class="fa-solid fa-triangle-exclamation me-1"></i> Allergies: ${p.allergies || 'None Reported'}`);
        $('#disp_conditions').html(`<i class="fa-solid fa-heart-pulse me-1"></i> Conditions: ${p.medical_conditions || 'None Reported'}`);
        
        $('#disp_em_name').text(p.emergency_name || 'N/A');
        $('#disp_em_phone').text(p.emergency_number || 'N/A');

        $('#inp_nhis_no').val(p.nhis_no || '');
        $('#sel_corp_provider').val(p.other_insurance_id || '');
        $('#inp_corp_no').val(p.other_insurance_no || '');
        $('#inp_ccc_code').val(p.ccc_code || '');
        $('#ccc_status_badge').empty();

        let payCat = p.payment_category || 'Cash';
        $('#sel_payment_cat').val(payCat).trigger('change');
        
        if(p.payment_category) {
            $('#sel_payment_cat').prop('disabled', true);
            if(payCat === 'NHIS' && p.ccc_code) {
                $('#ccc_status_badge').html('<span class="badge bg-success rounded-pill px-2 py-1"><i class="fa fa-check"></i> Verified (OPD)</span>');
            }
        } else {
            $('#sel_payment_cat').prop('disabled', false);
        }
    }

    $('#sel_payment_cat').change(function() {
        let cat = $(this).val();
        $('#area_nhis').toggle(cat === 'NHIS');
        $('#area_corp').toggle(cat === 'Corporate');
    });

    window.verifyCCC = function() {
        let nhis_no = $('#inp_nhis_no').val();
        let ccc_input = $('#inp_ccc_code').val().trim();
        
        if(!nhis_no) { appAlert('Verification Error', 'Please enter NHIS Number first.', 'error'); return; }
        
        $('#ccc_status_badge').html('<span class="badge bg-warning text-dark px-2 py-1 rounded-pill"><i class="fa fa-spinner fa-spin"></i> Checking NHIA Gateway...</span>');
        
        $.post(cccApiUrl, { action: 'verify_claim_code', nhis_number: nhis_no, ccc_code: ccc_input }, function(res) {
            if(res.status === 'success') {
                $('#inp_ccc_code').val(res.ccc_code);
                $('#ccc_status_badge').html('<span class="badge bg-success px-2 py-1 rounded-pill"><i class="fa fa-check-circle"></i> Active & Verified</span>');
            } else {
                $('#ccc_status_badge').html('<span class="badge bg-danger px-2 py-1 rounded-pill"><i class="fa fa-times-circle"></i> Verification Failed</span>');
                appAlert('NHIA Error', res.message || 'Unable to verify Claim Check Code.', 'error');
            }
        }, 'json').fail(function() {
            setTimeout(function() {
                let generatedCCC = Math.floor(10000 + Math.random() * 90000);
                $('#inp_ccc_code').val(generatedCCC);
                $('#ccc_status_badge').html('<span class="badge bg-success px-2 py-1 rounded-pill"><i class="fa fa-check-circle"></i> Fetched (Offline Fallback)</span>');
            }, 800);
        });
    };

    window.viewClinicalHistory = function() {
        let visit_id = $('#h_visit_id').val();
        if(!visit_id) { appAlert('Info', 'No historical data available.', 'info'); return; }

        $('#vitals_history_area').html('Loading...');
        $('#labs_history_area').html('Loading...');
        $('#modalClinicalHistory').modal('show');

        $.post(apiUrl, { action: 'fetch_patient_history', visit_id: visit_id }, function(res) {
            if(res.status === 'success') {
                let vHtml = res.vitals.length ? '<ul class="list-group list-group-flush small fw-bold">' : '<p class="text-muted small">No vitals recorded.</p>';
                res.vitals.forEach(v => {
                    vHtml += `<li class="list-group-item px-0" style="color:#334155;"><b>${v.created_at}</b>: Temp: ${v.temperature}°C | BP: ${v.bp_systolic}/${v.bp_diastolic} | HR: ${v.pulse} | SpO2: ${v.spo2}%</li>`;
                });
                if(res.vitals.length) vHtml += '</ul>';
                $('#vitals_history_area').html(vHtml);

                let lHtml = '';
                if (res.labs.length) {
                    lHtml += '<table class="table table-sm" style="font-size:13px; font-weight:600; color:#334155;"><tbody>';
                    res.labs.forEach(l => {
                        let chk = '';
                        if(l.status === 'Completed' || l.status === 'Verified') {
                            chk = `<input type="checkbox" class="lab-result-chk me-2" value="${l.id}" style="transform:scale(1.3); cursor:pointer;">`;
                        }
                        let bdg = (l.status === 'Pending') ? 'bg-warning text-dark' : 'bg-success';
                        lHtml += `<tr>
                                    <td style="width:30px;">${chk}</td>
                                    <td><b>${l.request_date}</b>: ${l.test_name}</td>
                                    <td class="text-end"><span class="badge rounded-pill px-2 py-1 ${bdg}">${l.status}</span></td>
                                  </tr>`;
                    });
                    lHtml += '</tbody></table>';
                } else {
                    lHtml = '<p class="text-muted small">No labs requested.</p>';
                }
                $('#labs_history_area').html(lHtml);
            }
        }, 'json');
    };

    window.viewSelectedLabs = function() {
        let ids = [];
        $('.lab-result-chk:checked').each(function() { ids.push($(this).val()); });
        if(ids.length === 0) { 
            appAlert('No Selection', 'Please check the box next to at least one completed investigation to view results.', 'warning'); 
            return; 
        }
        
        $('#modalClinicalHistory').modal('hide');
        $('#labResultsArea').html('<div class="text-center py-5"><i class="fa fa-spinner fa-spin fa-2x text-primary mb-3"></i><br>Fetching Results...</div>');
        $('#modalLabResults').modal('show');
        
        $.post(apiUrl, { action: 'fetch_lab_results', request_ids: ids }, function(res) {
            if(res.status === 'success') {
                $('#labResultsArea').html(res.html);
            } else {
                $('#labResultsArea').html('<div class="text-center text-danger py-5"><i class="fa-solid fa-triangle-exclamation fa-2x mb-3"></i><br>Failed to load results.</div>');
            }
        }, 'json');
    };

    $('#modalLabResults').on('hidden.bs.modal', function () {
        $('#modalClinicalHistory').modal('show');
    });

    window.startOPDAdmission = function(request_id) {
        $.post(apiUrl, { action: 'get_clinical_plan', request_id: request_id }, function(res) {
            if(res.status === 'success') {
                let d = res.data;
                $('#h_request_id').val(d.id);
                $('#h_visit_id').val(d.visit_master_id);
                $('#h_patient_no').val(d.patient_no);

                $('#lbl_diagnosis').html(d.principal_diagnosis || '<span class="text-muted">Not Specified</span>');
                $('#lbl_complaint').html(d.chief_complaint || '<span class="text-muted">Not Specified</span>');
                $('#lbl_ward_plan').html(d.treatment_plan_notes || 'No specific ward instructions provided.');

                // Render Dynamic Fields Grid
                let dynHtml = '';
                if(d.dynamic_responses && Object.keys(d.dynamic_responses).length > 0) {
                    for(let key in d.dynamic_responses) {
                        let label = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                        dynHtml += `<div class="col-md-6 mb-3">
                                        <label class="fw-bold text-primary small text-uppercase" style="letter-spacing:0.5px;"><i class="fa-solid fa-caret-right me-1"></i> ${label}</label>
                                        <div class="clinical-box text-dark mt-1 shadow-sm border-0" style="background:#f8fafc;">${d.dynamic_responses[key]}</div>
                                    </div>`;
                    }
                } else {
                    dynHtml = '<div class="col-12 text-muted small fw-bold">No additional clinical dynamic forms recorded for this encounter.</div>';
                }
                $('#dynamic_clinical_content').html(dynHtml);

                populatePatientDetails(d);

                $('.direct-admit-fields').hide(); 
                $('#nav_clinical').show();
                $('#btn_back_to_clinical').show();
                $('#queue_view').hide();
                $('#wizard_view').fadeIn();
                switchTab('tab_clinical');
                
                // AUTO-SELECT WARD IN MATRIX
                if(d.requested_ward) {
                    $('#sel_visual_ward option').each(function() {
                        if($(this).text().includes(d.requested_ward)) {
                            $('#sel_visual_ward').val($(this).val()).trigger('change');
                        }
                    });
                }
            } else {
                appAlert('Error', 'Unable to fetch clinical data.', 'error');
            }
        }, 'json');
    };

    window.openDirectAdmissionModal = function() {
        $('#txtPatientSearch').val('');
        $('#directAdmitResults').html('<tr><td colspan="4" class="text-center text-muted py-5 small fw-bold">Type a name or ID and press Enter to search.</td></tr>');
        $('#modalDirectAdmission').modal('show');
        setTimeout(() => $('#txtPatientSearch').focus(), 400); 
    };

    $('#txtPatientSearch').on('keypress', function(e) { if(e.which === 13) executePatientSearch(); });

    window.executePatientSearch = function() {
        let term = $('#txtPatientSearch').val().trim();
        if(term.length < 2) { appAlert('Invalid Search', 'Please enter at least 2 characters.', 'warning'); return; }
        
        $('#directAdmitResults').html('<tr><td colspan="4" class="text-center py-5"><i class="fa fa-spinner fa-spin text-primary fa-2x"></i></td></tr>');
        
        $.ajax({
            url: apiUrl,
            type: 'POST',
            data: { action: 'search_patient', search_term: term },
            dataType: 'json',
            success: function(res) {
                let html = '';
                if(res.status === 'success' && res.data.length > 0) {
                    window.patientSearchData = res.data;
                    res.data.forEach((p, index) => {
                        html += `<tr>
                            <td class="fw-bold text-primary ps-4">${p.patient_no}</td>
                            <td class="fw-bold" style="color:#0f172a;">${p.full_name}</td>
                            <td class="small text-muted fw-bold">${p.gender} / ${p.age} yrs</td>
                            <td class="text-end pe-4"><button class="btn btn-primary btn-cute shadow-sm" onclick="startDirectAdmission(${index})">Select</button></td>
                        </tr>`;
                    });
                } else { html = '<tr><td colspan="4" class="text-center text-danger py-5 small fw-bold">No matching patient found in the database.</td></tr>'; }
                $('#directAdmitResults').html(html);
            },
            error: function() {
                $('#directAdmitResults').html('<tr><td colspan="4" class="text-center text-danger py-5 small fw-bold">Server error occurred.</td></tr>');
            }
        });
    };

    window.startDirectAdmission = function(index) {
        let p = window.patientSearchData[index];
        $('#modalDirectAdmission').modal('hide');
        
        $('#h_request_id').val('');
        $('#h_visit_id').val('');
        $('#h_patient_no').val(p.patient_no);

        $('#lbl_ward_plan').html('Direct Admission Setup');
        $('#dynamic_clinical_content').html('<div class="col-12 text-muted small fw-bold">N/A for direct admission.</div>');

        populatePatientDetails(p);

        $('.direct-admit-fields').show(); 
        $('#nav_clinical').hide();
        $('#btn_back_to_clinical').hide();

        $('#queue_view').hide();
        $('#wizard_view').fadeIn();
        switchTab('tab_patient'); 
    };

    $('.nav-tabs .nav-link').click(function(e) {
        e.preventDefault();
        if($(this).data('target') === 'tab_process' && !$('#h_bed_id').val()) {
            appAlert('Action Required', 'Please assign a vacant bed in the Room/Ward tab first.', 'warning');
            return;
        }
        switchTab($(this).data('target'));
    });

    $('.btn-next, .btn-prev').click(function() {
        let target = $(this).data('next') || $(this).data('prev');
        if(target === 'tab_process') {
            if ($('#sel_payment_cat').val() === 'NHIS' && !$('#inp_ccc_code').val()) {
                appAlert('Action Required', 'Please Fetch or Verify the NHIS Claim Check Code (CCC).', 'warning');
                return;
            }
            if(!$('#h_bed_id').val()) {
                appAlert('Action Required', 'Please assign a vacant bed before continuing.', 'warning');
                return;
            }
        }
        switchTab(target);
    });

    function switchTab(tabId) {
        $('.nav-tabs .nav-link').removeClass('active');
        $(`button[data-target="${tabId}"]`).addClass('active');
        $('.wizard-pane').removeClass('active');
        $(`#${tabId}`).addClass('active');
    }

    function loadWardsMatrix() {
        $.post(apiUrl, { action: 'fetch_wards' }, function(res) {
            let html = '<option value="">-- Choose Ward --</option>';
            if(res.data) {
                res.data.forEach(w => html += `<option value="${w.id}">${w.ward_name} (Capacity: ${w.physical_bed_capacity}, Admitted: ${w.current_active_census})</option>`);
            }
            $('#sel_visual_ward').html(html);
        }, 'json');
    }

    $('#sel_visual_ward').change(function() {
        let ward_id = $(this).val();
        $('#h_ward_id').val(ward_id);
        $('#h_room_id').val('');
        $('#h_bed_id').val('');
        $('#bed_status_badge').removeClass('bg-success text-white').addClass('bg-warning text-dark').text('Awaiting Selection');
        
        if(!ward_id) {
            $('#room_selection_area').hide();
            $('#bed_grid_area').html('<div class="text-center text-muted py-5"><i class="fa-solid fa-bed fa-3x mb-3" style="color:#e2e8f0;"></i><br><span style="font-weight:600;">Select a Ward and Room to view beds.</span></div>');
            return;
        }

        $('#room_selection_area').fadeIn();
        $('#room_list').html('<div class="text-center p-3"><i class="fa fa-spinner fa-spin text-primary"></i> Loading...</div>');
        $('#bed_grid_area').html('<div class="text-center text-muted py-5 small">Please select an area on the left.</div>');

        $.post(apiUrl, { action: 'fetch_ward_matrix', ward_id: ward_id }, function(res) {
            let html = '';
            if(res.rooms && res.rooms.length > 0) {
                res.rooms.forEach(r => {
                    html += `<button type="button" class="list-group-item list-group-item-action room-card" onclick="selectRoom(${r.id}, this)">
                                <i class="fa-solid fa-door-open text-muted me-2"></i> ${r.room_number_or_name}
                             </button>`;
                });
            }
            if(res.direct_beds && res.direct_beds.length > 0) {
                let bData = encodeURIComponent(JSON.stringify(res.direct_beds));
                html += `<button type="button" class="list-group-item list-group-item-action room-card text-primary" onclick="renderBeds('${bData}', null, this)">
                            <i class="fa-solid fa-hospital text-primary me-2"></i> General Ward Area
                         </button>`;
            }
            if(html === '') html = '<div class="p-3 text-danger small fw-bold">No rooms or beds configured.</div>';
            $('#room_list').html(html);
        }, 'json');
    });

    window.selectRoom = function(room_id, element) {
        $('.room-card').removeClass('selected');
        $(element).addClass('selected');
        $('#h_room_id').val(room_id);
        $('#h_bed_id').val('');
        $('#bed_status_badge').removeClass('bg-success text-white').addClass('bg-warning text-dark').text('Awaiting Selection');

        $('#bed_grid_area').html('<div class="text-center py-5"><i class="fa fa-spinner fa-spin text-primary fa-2x"></i></div>');
        
        $.post(apiUrl, { action: 'fetch_room_beds', room_id: room_id }, function(res) {
            let bData = encodeURIComponent(JSON.stringify(res.beds));
            renderBeds(bData, room_id, element);
        }, 'json');
    };

    window.renderBeds = function(encodedBeds, room_id, element) {
        if(room_id === null) {
            $('.room-card').removeClass('selected');
            $(element).addClass('selected');
            $('#h_room_id').val('');
            $('#h_bed_id').val('');
        }

        let beds = JSON.parse(decodeURIComponent(encodedBeds));
        if(beds.length === 0) {
            $('#bed_grid_area').html('<div class="text-center text-danger py-5"><i class="fa-solid fa-ban fa-3x mb-3" style="color:#fca5a5;"></i><br><span style="font-weight:600;">No beds configured in this area.</span></div>');
            return;
        }

        let html = '<div class="d-flex flex-wrap gap-3">';
        beds.forEach(b => {
            let isVacant = (b.bed_status_id == 1);
            let stateClass = isVacant ? 'vacant' : 'occupied';
            let icon = isVacant ? 'fa-bed' : 'fa-bed-pulse';
            let clickEvent = isVacant ? `onclick="selectBed(${b.id}, '${b.bed_number}', this)"` : `onclick="appAlert('Unavailable', 'This bed is currently ${b.status_name}.', 'warning')"`;
            
            html += `<div class="bed-box ${stateClass} shadow-sm" ${clickEvent}>
                        <i class="fa-solid ${icon}"></i>
                        <span>${b.bed_number}</span>
                    </div>`;
        });
        html += '</div>';
        $('#bed_grid_area').html(html);
    };

    window.selectBed = function(bed_id, bed_number, element) {
        $('.bed-box').removeClass('selected');
        $(element).addClass('selected');
        $('#h_bed_id').val(bed_id);
        $('#bed_status_badge').removeClass('bg-warning text-dark').addClass('bg-success text-white').text('Selected: ' + bed_number);
    };

    function loadDictionaries() {
        $.post(apiUrl, { action: 'fetch_dictionaries' }, function(res) {
            let srcHtml = '<option value="">-- Select --</option>';
            if(res.sources) res.sources.forEach(s => srcHtml += `<option value="${s.id}">${s.name}</option>`);
            $('#sel_source').html(srcHtml);

            let priHtml = '<option value="">-- Select --</option>';
            if(res.priorities) res.priorities.forEach(p => priHtml += `<option value="${p.id}">${p.name}</option>`);
            $('#sel_priority').html(priHtml);

            let rsnHtml = '<option value="">-- Select --</option>';
            if(res.reasons) res.reasons.forEach(r => rsnHtml += `<option value="${r.id}">${r.name}</option>`);
            $('#sel_reason').html(rsnHtml);

            let docHtml = '<option value="">-- Select Doctor --</option>';
            if(res.doctors) res.doctors.forEach(d => docHtml += `<option value="${d.id}">${d.name}</option>`);
            $('#sel_doctor').html(docHtml);

            let insHtml = '<option value="">-- Select Provider --</option>';
            if(res.insurers) res.insurers.forEach(i => insHtml += `<option value="${i.id}">${i.name}</option>`);
            $('#sel_corp_provider').html(insHtml);
        }, 'json');
    }

    $('#frmAdmitPatient').submit(function(e) {
        e.preventDefault();
        
        let reqData = $(this).serializeArray();
        reqData.push({name: 'payment_category', value: $('#sel_payment_cat').val()});
        if($('#sel_payment_cat').val() === 'NHIS') {
            reqData.push({name: 'ccc_code', value: $('#inp_ccc_code').val()});
            reqData.push({name: 'nhis_no', value: $('#inp_nhis_no').val()});
        }

        let btn = $('#btnFinalAdmit');
        let originalText = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Processing...');

        $.post(apiUrl, $.param(reqData), function(res) {
            btn.prop('disabled', false).html(originalText);
            if(res.status === 'success') {
                $('#chkConfirm').prop('checked', false); 
                appAlert('Admission Successful', 'Patient ' + res.patient_no + ' has been successfully admitted to the ward.', 'success');
                cancelAdmission(); 
                loadPendingQueue(true); 
            } else {
                appAlert('Admission Failed', res.message, 'error');
            }
        }, 'json').fail(function() {
            btn.prop('disabled', false).html(originalText);
            appAlert('Server Error', 'Could not connect to the server.', 'error');
        });
    });

    window.cancelAdmission = function() {
        $('#frmAdmitPatient')[0].reset();
        $('#h_request_id, #h_visit_id, #h_patient_no, #h_ward_id, #h_room_id, #h_bed_id').val('');
        $('#bed_grid_area').html('<div class="text-center text-muted py-5"><i class="fa-solid fa-bed fa-3x mb-3" style="color:#e2e8f0;"></i><br><span style="font-weight:600;">Select a Ward and Room to view beds.</span></div>');
        $('#room_selection_area').hide();
        $('#bed_status_badge').removeClass('bg-success text-white').addClass('bg-warning text-dark').text('Awaiting Selection');
        
        $('#sel_payment_cat').prop('disabled', false);
        $('#area_nhis, #area_corp, .ref_field, .direct-admit-fields').hide();
        
        $('#wizard_view').hide();
        $('#queue_view').fadeIn();
    };
});