const apiUrl = '/rimax/application/dripend/includes/ipd/processAdmissionManager.php';
const apiFormUrl = '/rimax/application/dripend/includes/ipd/processIPDFormEngine.php';
const apiDataUrl = '/rimax/application/dripend/includes/ipd/processPatientIPDRecords.php';
let activeView = 'tile';
window.FORM_MAP = {};

$(document).ready(function() {
    let today = new Date();
    let firstDay = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
    let lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0];
    $('#flt_start').val(firstDay);
    $('#flt_end').val(lastDay);

    loadFilters();
    loadStats();
    loadAdmissions();
});

window.showAppResponse = function(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');
};

function loadFilters() {
    $.post(apiUrl, { action: 'fetch_filters' }, function(res) {
        if (res.status === 'success') {
            let wOpts = '<option value="ALL">All Wards / Units</option>';
            res.wards.forEach(w => wOpts += `<option value="${w.id}">${w.ward_name}</option>`);
            $('#flt_ward').html(wOpts);

            let dOpts = '<option value="ALL">All Providers</option>';
            res.doctors.forEach(d => dOpts += `<option value="${d.staff_id}">Dr. ${d.doc_name}</option>`);
            $('#flt_doctor').html(dOpts);
        }
    }, 'json');
}

function loadStats() {
    $.post(apiUrl, { action: 'fetch_stats', date_from: $('#flt_start').val(), date_to: $('#flt_end').val() }, function(res) {
        if(res.status === 'success') {
            $('#stat_active').text(res.active_total);
            $('#stat_discharged').text(res.discharged_period);
            $('#stat_disc_demo').text(`(M: ${res.discharged_male}, F: ${res.discharged_female})`);
            $('#stat_male').text(res.male_active);
            $('#stat_female').text(res.female_active);
            $('#stat_child').text(res.child_active);
            $('#stat_adult').text(res.adult_active);
        }
    }, 'json');
}

window.loadAdmissions = function() {
    $('#tile_view, #list_view, #empty_state').hide();
    $('#loading_state').show();

    let payload = {
        action: 'fetch_admissions',
        date_from: $('#flt_start').val(),
        date_to: $('#flt_end').val(),
        ward_id: $('#flt_ward').val(),
        doctor_id: $('#flt_doctor').val(),
        status: $('#flt_status').val()
    };

    $.post(apiUrl, payload, function(res) {
        $('#loading_state').hide();
        loadStats();

        if(res.status === 'success' && res.data.length > 0) {
            window.FORM_MAP = res.form_map;
            renderTileView(res.data);
            renderListView(res.data);
            
            if(activeView === 'tile') $('#tile_view').fadeIn();
            else $('#list_view').fadeIn();
        } else {
            $('#empty_state').fadeIn();
        }
    }, 'json');
};

function renderTileView(data) {
    let html = '';
    data.forEach(r => {
        let statusBadge = '';
        let borderClass = 'status-active';

        if(r.status === 'Pending Discharge') {
            borderClass = 'status-pending';
            statusBadge = `<span class="badge badge-outcome bg-warning text-dark position-absolute top-0 end-0 m-3 shadow-sm"><i class="fa-solid fa-person-walking-arrow-right me-1"></i> Pending Discharge</span>`;
        } else if(r.status === 'Transferred') {
            statusBadge = `<span class="badge badge-outcome bg-info text-dark position-absolute top-0 end-0 m-3 shadow-sm"><i class="fa-solid fa-right-left me-1"></i> Transferred</span>`;
        } else if(r.status === 'In Theatre') {
            borderClass = 'status-theatre';
            statusBadge = `<span class="badge badge-outcome bg-danger position-absolute top-0 end-0 m-3 shadow-sm"><i class="fa-solid fa-scalpel-line-dashed me-1"></i> In Theatre</span>`;
        } else if(r.status === 'Discharged') {
            borderClass = 'status-closed';
            statusBadge = `<span class="badge badge-outcome bg-success position-absolute top-0 end-0 m-3 shadow-sm"><i class="fa-solid fa-house-medical-circle-check me-1"></i> Discharged</span>`;
        } else {
            statusBadge = `<span class="badge badge-outcome bg-primary position-absolute top-0 end-0 m-3 shadow-sm"><i class="fa-solid fa-bed-pulse me-1"></i> Admitted</span>`;
        }

        let ageStr = r.age + ' yrs';
        let genderIcon = r.gender_id == 1 ? '<i class="fa-solid fa-mars text-primary"></i>' : '<i class="fa-solid fa-venus" style="color:#db2777;"></i>';

        html += `
        <div class="tile-card ${borderClass}">
            ${statusBadge}
            <div class="tile-header">
                <div class="patient-avatar shadow-sm">${r.initials}</div>
                <div class="ms-3 flex-grow-1" style="padding-top:4px;">
                    <h5 class="fw-bold text-dark mb-1" style="font-size:17px;">${r.full_name}</h5>
                    <span class="badge bg-light text-secondary border mb-1">${r.patient_no}</span>
                </div>
            </div>
            <div class="tile-info">
                <p><i class="fa-solid fa-user"></i> ${ageStr} &nbsp;|&nbsp; ${genderIcon} ${r.gender_name}</p>
                <p><i class="fa-solid fa-bed"></i> <b>${r.location_str}</b></p>
                <p><i class="fa-solid fa-calendar-check"></i> Admitted: ${r.admission_date.substring(0,16)}</p>
                <p><i class="fa-solid fa-user-doctor"></i> Attending: <b>Dr. ${r.doc_name || 'Unassigned'}</b></p>
            </div>
            <div class="tile-actions">
                <div class="d-flex gap-2">
                    <button class="quick-btn" title="Log Vitals" onclick="openUniversalModal(${window.FORM_MAP.vitals}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-heart-pulse text-danger"></i></button>
                    <button class="quick-btn" title="Fluid Chart" onclick="openUniversalModal(${window.FORM_MAP.fluids}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-droplet text-info"></i></button>
                    <button class="quick-btn" title="Medications" onclick="openUniversalModal(${window.FORM_MAP.meds}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-pills text-warning"></i></button>
                    <button class="quick-btn" title="Nurse Notes" onclick="openUniversalModal(${window.FORM_MAP.notes}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-user-nurse text-primary"></i></button>
                </div>
                <a href="patientIPDRecords.php?visit_id=${r.visit_master_id}" class="full-chart-btn shadow-sm">Command Center <i class="fa-solid fa-arrow-right ms-1"></i></a>
            </div>
        </div>`;
    });
    $('#tile_view').html(html);
}

function renderListView(data) {
    let html = '';
    data.forEach(r => {
        let statusBadge = '';
        if(r.status === 'Pending Discharge') statusBadge = `<span class="badge bg-warning text-dark fw-bold px-2 py-1"><i class="fa-solid fa-person-walking-arrow-right me-1"></i> Pending Discharge</span>`;
        else if(r.status === 'Transferred') statusBadge = `<span class="badge bg-info text-dark fw-bold px-2 py-1"><i class="fa-solid fa-right-left me-1"></i> Transferred</span>`;
        else if(r.status === 'In Theatre') statusBadge = `<span class="badge bg-danger fw-bold px-2 py-1"><i class="fa-solid fa-scalpel-line-dashed me-1"></i> In Theatre</span>`;
        else if(r.status === 'Discharged') statusBadge = `<span class="badge bg-success fw-bold px-2 py-1">Discharged</span>`;
        else statusBadge = `<span class="badge bg-primary fw-bold px-2 py-1">Admitted</span>`;

        html += `
        <tr class="list-row">
            <td>
                <div class="d-flex flex-column">
                    <span class="fw-bold text-primary" style="font-size:15px;">${r.full_name}</span>
                    <span class="text-muted small fw-bold">${r.patient_no} | ${r.age} Yrs</span>
                </div>
            </td>
            <td><b class="text-dark"><i class="fa-solid fa-bed text-muted me-2"></i> ${r.location_str}</b></td>
            <td><span class="text-muted fw-bold">${r.admission_date.substring(0,16)}</span></td>
            <td><span class="text-dark fw-bold"><i class="fa-solid fa-user-doctor text-muted me-1"></i> Dr. ${r.doc_name || 'Unassigned'}</span></td>
            <td>${statusBadge}</td>
            <td class="text-end">
                <button class="btn btn-sm btn-light border text-danger shadow-sm py-1 px-2" title="Vitals" onclick="openUniversalModal(${window.FORM_MAP.vitals}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-heart-pulse"></i></button>
                <button class="btn btn-sm btn-light border text-info shadow-sm py-1 px-2 ms-1" title="Fluids" onclick="openUniversalModal(${window.FORM_MAP.fluids}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-droplet"></i></button>
                <button class="btn btn-sm btn-light border text-warning shadow-sm py-1 px-2 ms-1" title="Meds" onclick="openUniversalModal(${window.FORM_MAP.meds}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-pills"></i></button>
                <button class="btn btn-sm btn-light border text-primary shadow-sm py-1 px-2 ms-1" title="Notes" onclick="openUniversalModal(${window.FORM_MAP.notes}, ${r.visit_master_id}, '${r.patient_no}')"><i class="fa-solid fa-user-nurse"></i></button>
                <a href="patientIPDRecords.php?visit_id=${r.visit_master_id}" class="btn btn-sm btn-dark fw-bold px-3 py-1 shadow-sm ms-2">Open Chart</a>
            </td>
        </tr>`;
    });
    $('#list_view_body').html(html);
}

window.toggleView = function(view) {
    activeView = view;
    $('.view-toggle-btn').removeClass('active');
    if (view === 'tile') {
        $('#btnViewTile').addClass('active');
        $('#list_view').hide();
        if($('#tile_view').html() !== '') $('#tile_view').fadeIn();
    } else {
        $('#btnViewList').addClass('active');
        $('#tile_view').hide();
        if($('#list_view_body').html() !== '') $('#list_view').fadeIn();
    }
};

// ===============================================
// UNIVERSAL MODAL ENGINE WITH LIVE HISTORY
// ===============================================

window.openUniversalModal = function(form_id, visitId, patientNo, editTime = null) {
    if(!form_id) { showAppResponse("Configuration Error", "This module is not correctly mapped in the System Settings.", "error"); return; }
    
    window.P_VISIT_ID = visitId;
    window.P_NO = patientNo;
    window.CURRENT_FORM_ID = form_id;

    $('#uModalTitle').html('<i class="fa fa-spinner fa-spin"></i> Loading Form...');
    $('#uModalBody').html('<div class="text-center py-5"><i class="fa-solid fa-spinner fa-spin fa-3x text-primary"></i></div>');
    $('#uModalHistory').html('<div class="text-center py-3"><i class="fa fa-spinner fa-spin text-muted"></i></div>');
    $('#universalActionModal').modal('show');

    $.post(apiFormUrl, { action: 'get_action_interface', visit_id: visitId, patient_no: patientNo, form_id: form_id, edit_timestamp: editTime || '' }, function(res) {
        if(res.status === 'success') {
            $('#uModalTitle').html(res.title);
            $('#uModalBody').html(res.html);
            
            setTimeout(() => {
                $('.select2-basic').select2({ dropdownParent: $('#universalActionModal'), width: '100%' });
                
                $('.rich-text-editor').summernote({
                    height: 150,
                    toolbar: [
                        ['style', ['bold', 'italic', 'underline', 'clear']],
                        ['font', ['strikethrough', 'superscript', 'subscript']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['view', ['fullscreen']]
                    ]
                });

                $('.dispensary-select').on('change', function() {
                    if($(this).val()) {
                        $('.rx-add-btn').prop('disabled', false);
                        $('#dispensary_lock_notice').slideUp();
                    }
                });
                
                // Always fetch the history for the modal bottom viewer
                loadQuickHistory(form_id, visitId);

                if(editTime) {
                    $('#edit_timestamp').val(editTime);
                    $('#uModalTitle').append(' <span class="badge bg-warning text-dark ms-2"><i class="fa-solid fa-pen"></i> EDITING RECORD</span>');
                    
                    $.post(apiFormUrl, { action: 'get_edit_data', form_id: form_id, visit_id: visitId, recorded_at: editTime }, function(editRes) {
                        if(editRes.status === 'success') {
                            for(let key in editRes.data) {
                                if (key === 'NATIVE_FLUID') {
                                    $('#fluid_dynamic_container').empty();
                                    editRes.data[key].forEach(f => {
                                        let btn = $('#fluid_dynamic_container').siblings('button');
                                        let optsStr = btn.attr('onclick').match(/'([^']+)'/)[1];
                                        addFluidRow(optsStr);
                                        let lastRow = $('.fluid-row').last();
                                        lastRow.find('select[name="fluid_chart_type[]"]').val(f.fluid_type);
                                        lastRow.find('input[name="fluid_chart_vol[]"]').val(f.volume_ml);
                                        lastRow.find('input[name="fluid_chart_remarks[]"]').val(f.remarks);
                                    });
                                } else if (key === 'NATIVE_MED') {
                                    editRes.data[key].forEach(m => {
                                        let row = $(`input[name='med_chart_id[]'][value='${m.prescription_id}']`).closest('tr');
                                        if(row.length) {
                                            row.find('.med-chart-checkbox').prop('checked', true).trigger('change');
                                            row.find(`input[name='med_chart_dose[${m.prescription_id}]']`).val(m.administered_dose || row.find(`input[name='med_chart_dose[${m.prescription_id}]']`).val());
                                            row.find(`select[name='med_chart_status[${m.prescription_id}]']`).val($.trim(m.status));
                                            row.find(`input[name='med_chart_time[${m.prescription_id}]']`).val(m.administered_at.substring(0,16));
                                            row.find(`input[name='med_chart_remarks[${m.prescription_id}]']`).val(m.remarks);
                                        }
                                    });
                                } else {
                                    let fld = $('[data-field="'+key+'"]');
                                    if(fld.length > 0) {
                                        if(fld.attr('type') === 'radio' || fld.attr('type') === 'checkbox') {
                                            fld.filter(`[value="${editRes.data[key]}"]`).prop('checked', true);
                                        } else if(fld.hasClass('rich-text-editor')) {
                                            fld.summernote('code', editRes.data[key]);
                                        } else {
                                            fld.val(editRes.data[key]).trigger('change');
                                        }
                                    }
                                }
                            }
                        }
                    }, 'json');
                }
            }, 100);
        }
    }, 'json');
};

function loadQuickHistory(form_id, visitId) {
    // Harnesses the existing History Builder API without needing new code
    $.post(apiDataUrl, { action: 'fetch_tab_data', visit_id: visitId, tab: form_id }, function(res) {
        if(res.status === 'success') {
            $('#uModalHistory').html(res.html);
        } else {
            $('#uModalHistory').html('<div class="text-muted small">Could not load history.</div>');
        }
    }, 'json');
}

// Redirect edit calls in history back to the modal
window.editRecord = function(form_id, editTime) {
    openUniversalModal(form_id, window.P_VISIT_ID, window.P_NO, editTime);
};

window.deleteRecord = function(form_id, editTime) {
    alert("Record voiding must be done through the Full Command Center.");
};

window.addFluidRow = function(encodedData) {
    let obj = JSON.parse(atob(encodedData));
    let html = `
        <div class='row g-2 mb-2 align-items-center fluid-row bg-white p-2 border border-info rounded'>
            <div class='col-md-2'><select class='form-select border-info fluid-cat-selector'><option value='IN'>Intake (IN)</option><option value='OUT'>Output (OUT)</option></select></div>
            <div class='col-md-3'><select name='fluid_chart_type[]' class='form-select border-info fluid-type-selector' required><option value=''>-- Select Fluid --</option>${obj.IN}</select></div>
            <div class='col-md-3'><div class='input-group'><input type='number' name='fluid_chart_vol[]' class='form-control border-info fw-bold text-info' placeholder='Volume' required><span class='input-group-text bg-info text-white border-info fw-bold'>ml</span></div></div>
            <div class='col-md-3'><input type='text' name='fluid_chart_remarks[]' class='form-control border-info' placeholder='Remarks / Additives...'></div>
            <div class='col-md-1 text-end'><button type='button' class='btn btn-sm btn-danger shadow-sm' onclick='$(this).closest(".fluid-row").remove()'><i class='fa fa-times'></i></button></div>
        </div>`;
    let $row = $(html);
    $('#fluid_dynamic_container').append($row);
    $row.find('.fluid-cat-selector').on('change', function() {
        let val = $(this).val();
        $(this).closest('.fluid-row').find('.fluid-type-selector').html('<option value="">-- Select Fluid --</option>' + obj[val]);
    });
};

$(document).on('change', '.med-chart-checkbox', function() {
    let row = $(this).closest('tr');
    let id = $(this).val();
    if($(this).is(':checked')) {
        row.addClass('bg-info bg-opacity-10');
        $(`.med-input-${id}`).prop('disabled', false);
    } else {
        row.removeClass('bg-info bg-opacity-10');
        $(`.med-input-${id}`).prop('disabled', true);
    }
});

window.addDynamicRxRow = function(encodedOpts, encodedFreqOpts) {
    let opts = encodedOpts ? atob(encodedOpts) : '';
    let fOpts = encodedFreqOpts ? atob(encodedFreqOpts) : '';
    let today = new Date().toISOString().split('T')[0];
    
    const wrapper = document.createElement('div');
    wrapper.className = 'p-3 bg-white border shadow-sm rounded-3 mb-3 position-relative rx-wrapper-box';
    wrapper.innerHTML = `
        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-2 py-0 px-2 shadow-sm" onclick="this.closest('.rx-wrapper-box').remove()"><i class="fa-solid fa-times"></i></button>
        <div class="row g-2 align-items-end mb-2">
            <div class="col-md-4"><label class="small fw-bold text-muted mb-1">Search Drug <span class="text-danger">*</span></label><select name="rx_drug[]" class="form-select select2-drug-dyn" required><option value="">-- Select --</option>${opts}</select></div>
            <div class="col-md-2"><label class="small fw-bold text-muted mb-1">Formulation</label><input type="text" name="rx_form[]" class="form-control fw-bold text-dark rx-form-fld" readonly></div>
            <div class="col-md-3"><label class="small fw-bold text-muted mb-1">Strength</label><input type="text" name="rx_strength[]" class="form-control fw-bold text-dark rx-str-fld" readonly></div>
            <div class="col-md-3"><label class="small fw-bold text-muted mb-1">Dose <span class="text-danger">*</span></label><input type="text" name="rx_dose[]" class="form-control fw-bold border-primary rx-dose-fld" placeholder="e.g. 500 mg" required></div>
        </div>
        <div class="row g-2 align-items-end">
            <div class="col-md-2"><label class="small fw-bold text-muted mb-1">Frequency <span class="text-danger">*</span></label><select name="rx_freq[]" class="form-select fw-bold rx-freq-fld" required>${fOpts}</select></div>
            <div class="col-md-2"><label class="small fw-bold text-primary mb-1">Start Date</label><input type="date" name="rx_start[]" class="form-control fw-bold border-primary rx-start-fld" min="${today}" value="${today}" required></div>
            <div class="col-md-2"><label class="small fw-bold text-muted mb-1">Days <span class="text-danger">*</span></label><input type="number" name="rx_dur[]" class="form-control fw-bold rx-dur-fld" value="5" required></div>
            <div class="col-md-2"><label class="small fw-bold text-success mb-1">End Date</label><input type="date" name="rx_end[]" class="form-control fw-bold text-success rx-end-fld" style="background:#f0fdf4;" readonly></div>
            <div class="col-md-2"><label class="small fw-bold text-dark mb-1">Total Dispense</label><input type="number" name="rx_qty_doses[]" class="form-control fw-bold text-dark rx-qty-doses-fld" style="background:#f1f5f9;" readonly></div>
            <div class="col-md-2"><label class="small fw-bold text-primary mb-1">Total Qty (Nos)</label><input type="number" name="rx_qty[]" class="form-control fw-bold text-primary rx-qty-fld" style="background:#e0f2fe;" readonly></div>
            <div class="col-12 mt-2"><label class="small fw-bold text-muted mb-1">Remarks</label><input type="text" name="rx_remarks[]" class="form-control" placeholder="Notes..."></div>
        </div>`;
    document.getElementById('rx_dynamic_container').appendChild(wrapper);
    $(wrapper).find('.select2-drug-dyn').select2({ dropdownParent: $('#universalActionModal'), width: '100%' });
    calculateRowRx(wrapper);
};

$(document).on('change', '.select2-drug-dyn', function (e) {
    const row = $(this).closest('.rx-wrapper-box');
    const selected = $(this).find(':selected');
    row.find('.rx-form-fld').val(selected.attr('data-form') || '');
    row.find('.rx-str-fld').val(selected.attr('data-strength') || '');
    calculateRowRx(row);
});

$(document).on('input change', '.rx-dose-fld, .rx-dur-fld, .rx-freq-fld, .rx-start-fld', function() {
    calculateRowRx($(this).closest('.rx-wrapper-box'));
});

function calculateRowRx(rowElem) {
    const row = $(rowElem);
    let doseStr = row.find('.rx-dose-fld').val() || '';
    let strStr = row.find('.rx-str-fld').val() || ''; 
    let doseVal = parseFloat(doseStr.replace(/[^0-9.]/g, '')) || 0; 
    let strVal = parseFloat(strStr.replace(/[^0-9.]/g, '')) || 0;
    
    let multiplier = 1;
    if (doseVal > 0) {
        if (strVal > 0 && doseStr.match(/(mg|ml|g|mcg|iu)/i)) { multiplier = doseVal / strVal; } 
        else { multiplier = doseVal; }
    }
    
    const days = parseInt(row.find('.rx-dur-fld').val()) || 1;
    const freq_mult = parseFloat(row.find('.rx-freq-fld option:selected').attr('data-mult')) || 1;
    
    let totalDoses = Math.ceil(days * freq_mult);
    let totalQtyNos = Math.ceil(multiplier * days * freq_mult);
    if (totalQtyNos < 1) totalQtyNos = 1;
    
    row.find('.rx-qty-doses-fld').val(totalDoses);
    row.find('.rx-qty-fld').val(totalQtyNos);
    
    let startStr = row.find('.rx-start-fld').val();
    let startDate = startStr ? new Date(startStr) : new Date();
    let endDate = new Date(startDate);
    endDate.setDate(endDate.getDate() + (days > 0 ? days - 1 : 0));
    row.find('.rx-end-fld').val(endDate.toISOString().split('T')[0]);
}

window.submitUniversalAction = function() {
    let form = $('#universalActionForm');
    if(!form[0].checkValidity()) { form[0].reportValidity(); return; }

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

    $.post(apiFormUrl, form.serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if(res.status === 'success') {
            showAppResponse("Saved", "Record securely added to the patient's file.", 'success');
            loadQuickHistory(window.CURRENT_FORM_ID, window.P_VISIT_ID);
            $('#universalActionForm')[0].reset();
        } else {
            showAppResponse("Save Error", res.message, 'error');
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Server Error", "A critical server error occurred.", 'error');
    });
};