let dtPending, dtHistory;
let pendingFiltered = false;
let historyFiltered = false;

const apiDischarge = '/rimax/application/dripend/includes/ipd/processDischargeManager.php';

$(document).ready(function() {
    fetchKPIs();
    initDataTables();
});

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 fetchKPIs() {
    $.post(apiDischarge, { action: 'fetch_kpis' }, function(res) {
        if(res.status === 'success') {
            $('#kpi_pending').text(res.data.pending_discharge);
            $('#kpi_today').text(res.data.today_discharged);
            $('#kpi_cleaning').text(res.data.housekeeping_beds);
            $('#kpi_male').text(res.data.male_pending);
            $('#kpi_female').text(res.data.female_pending);

            let wardHtml = '';
            if(res.data.ward_breakdown.length > 0) {
                res.data.ward_breakdown.forEach(w => {
                    wardHtml += `<div class="d-flex justify-content-between border-bottom pb-1 mb-1"><span>${w.ward_name}</span><span class="badge bg-primary rounded-pill">${w.cnt}</span></div>`;
                });
            } else {
                wardHtml = 'No pending discharges.';
            }
            $('#kpi_wards_list').html(wardHtml);
        }
    }, 'json');
}

function initDataTables() {
    dtPending = $('#tblPendingDischarges').DataTable({
        ajax: {
            url: apiDischarge,
            type: 'POST',
            data: function(d) { 
                d.action = 'fetch_pending_discharges'; 
                d.is_filtered = pendingFiltered;
                d.start_date = $('#pending_start_date').val();
                d.end_date = $('#pending_end_date').val();
                d.ward_id = $('#pending_ward_id').val();
            },
            dataSrc: function (json) {
                if (json.status === 'error') { showAppResponse("System Error", json.message, 'error'); return []; }
                return json.data || [];
            }
        },
        pageLength: 10,
        columnDefs: [ { searchable: false, orderable: false, targets: 0 } ],
        order: [[ 1, 'asc' ]], 
        columns: [
            { data: null, defaultContent: '', className: 'dt-serial' },
            {
                data: null,
                render: function(data, type, row) {
                    return `
                    <div>
                        <b class="text-primary fs-6">${row.patient_name}</b> 
                        <span class="badge bg-secondary ms-1">${row.patient_no}</span>
                        <div class="small fw-bold mt-1">${row.provisional_diagnosis}</div>
                    </div>`;
                }
            },
            { data: null, render: r => `<span class="badge bg-dark px-3 py-2 fs-6 shadow-sm"><i class="fa-solid fa-bed text-primary me-2"></i>${r.location_str}</span>` },
            {
                data: null,
                render: function(data, type, row) {
                    return `<b class="text-danger"><i class="fa-solid fa-user-doctor me-1"></i>${row.doctor_outcome}</b><br><span class="small text-muted fw-bold"><i class="fa-regular fa-calendar-check me-1"></i> Review: ${row.next_review_date_fmt}</span>`;
                }
            },
            { data: 'status', render: d => `<span class="badge badge-pending px-3 py-2 shadow-sm">${d}</span>` },
            {
                data: null, className: 'text-end', orderable: false,
                render: function(data, type, row) {
                    return `<button class="btn btn-sm btn-dark fw-bold px-3 shadow-sm" onclick="openDischargeModal(${row.episode_id})"><i class="fa-solid fa-clipboard-check me-1"></i> Clear & Discharge</button>`;
                }
            }
        ]
    });

    dtPending.on('order.dt search.dt', function () {
        let i = 1; dtPending.cells(null, 0, { search: 'applied', order: 'applied' }).every(function (cell) { this.data(i++); });
    }).draw();

    dtHistory = $('#tblDischargedHistory').DataTable({
        ajax: {
            url: apiDischarge,
            type: 'POST',
            data: function(d) {
                d.action = 'fetch_discharged_history';
                d.is_filtered = historyFiltered;
                d.start_date = $('#history_start_date').val();
                d.end_date = $('#history_end_date').val();
                d.ward_id = $('#history_ward_id').val();
            },
            dataSrc: function (json) {
                if (json.status === 'error') return [];
                return json.data || [];
            }
        },
        pageLength: 10,
        columnDefs: [ { searchable: false, orderable: false, targets: 0 } ],
        order: [[ 1, 'desc' ]], 
        columns: [
            { data: null, defaultContent: '', className: 'dt-serial' },
            { data: 'formatted_date', className: 'fw-bold text-muted small' },
            { data: null, render: r => `<b class="text-dark">${r.patient_name}</b> <br><span class="small text-muted">${r.patient_no}</span>` },
            { data: 'discharge_outcome', render: (d, t, r) => `<span class="badge bg-success shadow-sm mb-1">${d}</span><br><span class="small text-muted fw-bold"><i class="fa-regular fa-calendar-check me-1"></i> Review: ${r.next_review_date_fmt}</span>` },
            { data: 'discharge_notes', render: d => `<span class="small text-muted">${d}</span>` },
            {
                data: null, className: 'text-end', orderable: false,
                render: function(data, type, row) {
                    let encoded = btoa(unescape(encodeURIComponent(row.discharge_notes)));
                    return `<button class="btn btn-sm btn-light border fw-bold text-dark shadow-sm" onclick="openUpdateNotes(${row.episode_id}, '${encoded}')"><i class="fa-solid fa-pen text-warning me-1"></i> Amend Notes</button>`;
                }
            }
        ]
    });

    dtHistory.on('order.dt search.dt', function () {
        let i = 1; dtHistory.cells(null, 0, { search: 'applied', order: 'applied' }).every(function (cell) { this.data(i++); });
    }).draw();

    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
        $.fn.dataTable.tables({ visible: true, api: true }).columns.adjust();
    });

    // Execute Discharge Action
    $('#frmExecuteDischarge').on('submit', function(e) {
        e.preventDefault();
        let btn = $('#btnSubmitDischarge'); let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Validating & Executing...');

        $.post(apiDischarge, $(this).serialize(), function(res) {
            btn.prop('disabled', false).html(orig);
            if (res.status === 'success') {
                $('#dischargeClearanceModal').modal('hide');
                showAppResponse("Discharge Successful", res.message, 'success');
                reloadAllTables();
            } else {
                showAppResponse("Discharge Blocked", res.message, 'error');
            }
        }, 'json').fail(function() {
            btn.prop('disabled', false).html(orig);
            showAppResponse("Server Error", "A critical error occurred while attempting to execute the discharge.", 'error');
        });
    });

    // Amend Notes Action
    $('#frmUpdateNotes').on('submit', function(e) {
        e.preventDefault();
        let btn = $('#btnSubmitUpdate'); let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Updating...');

        $.post(apiDischarge, $(this).serialize(), function(res) {
            btn.prop('disabled', false).html(orig);
            if (res.status === 'success') {
                $('#updateNotesModal').modal('hide');
                showAppResponse("Notes Updated", res.message, 'success');
                dtHistory.ajax.reload(null, false);
            } else {
                showAppResponse("Update Failed", res.message, 'error');
            }
        }, 'json');
    });
}

window.reloadAllTables = function() {
    fetchKPIs();
    if(dtPending && pendingFiltered) dtPending.ajax.reload(null, false);
    if(dtHistory && historyFiltered) dtHistory.ajax.reload(null, false);
};

window.applyPendingFilter = function() {
    let sd = $('#pending_start_date').val(); let ed = $('#pending_end_date').val();
    if(sd && ed && new Date(sd) > new Date(ed)) { showAppResponse("Date Error", "Start Date cannot be greater than End Date.", 'error'); return; }
    
    pendingFiltered = true;
    $('#pending_empty_state').hide();
    $('#pending_table_wrapper').fadeIn();
    dtPending.ajax.reload();
};

window.resetPendingFilter = function() {
    $('#pending_start_date').val(''); $('#pending_end_date').val(''); $('#pending_ward_id').val('ALL');
    pendingFiltered = false;
    $('#pending_table_wrapper').hide();
    $('#pending_empty_state').fadeIn();
    dtPending.clear().draw();
};

window.applyHistoryFilter = function() {
    let sd = $('#history_start_date').val(); let ed = $('#history_end_date').val();
    if(sd && ed && new Date(sd) > new Date(ed)) { showAppResponse("Date Error", "Start Date cannot be greater than End Date.", 'error'); return; }
    
    historyFiltered = true;
    $('#history_empty_state').hide();
    $('#history_table_wrapper').fadeIn();
    dtHistory.ajax.reload();
};

window.resetHistoryFilter = function() {
    $('#history_start_date').val(''); $('#history_end_date').val(''); $('#history_ward_id').val('ALL');
    historyFiltered = false;
    $('#history_table_wrapper').hide();
    $('#history_empty_state').fadeIn();
    dtHistory.clear().draw();
};

window.openUpdateNotes = function(episodeId, encodedNotes) {
    $('#edit_episode_id').val(episodeId);
    $('#edit_discharge_notes').val(decodeURIComponent(escape(atob(encodedNotes))));
    $('#updateNotesModal').modal('show');
};

window.openDischargeModal = function(episodeId) {
    $('#frmExecuteDischarge')[0].reset();
    $('#m_diagnoses_list').html('<i class="fa fa-spinner fa-spin text-muted"></i>');
    $('#m_latest_records').html('<i class="fa fa-spinner fa-spin text-muted"></i>');
    
    $('#modalClearanceTitle').html('<i class="fa fa-spinner fa-spin me-2"></i> Loading Patient Clearance Summary...');
    $('#dischargeClearanceModal').modal('show');

    $.post(apiDischarge, { action: 'get_discharge_clearance_details', episode_id: episodeId }, function(res) {
        if(res.status === 'success') {
            let p = res.patient;
            let c = res.clearance;

            $('#modalClearanceTitle').html(`<i class="fa-solid fa-clipboard-check me-2"></i> Clinical Discharge Clearance - ${p.patient_name}`);
            $('#m_episode_id').val(p.episode_id);
            $('#m_visit_id').val(p.visit_id);
            $('#m_bed_id').val(p.bed_id);

            $('#m_patient_name').text(p.patient_name);
            $('#m_patient_sub').text(`ID: ${p.patient_no} | Admission: ${p.admission_date} | Payer: ${p.payer_type}`);
            $('#m_bed_location').text(p.location);

            $('#m_doc_outcome').val(p.doctor_outcome);
            $('#m_next_review_date').val(p.next_review_date);

            $('#m_total_billed').text(`GHS ${c.total_unpaid_bills}`);
            $('#m_tto_status').text(`${c.dispensed_prescriptions} / ${c.total_prescriptions} Dispensed`);
            
            if(c.pending_labs > 0) {
                $('#m_labs_status').html(`<span class="badge bg-warning text-dark shadow-sm">${c.pending_labs} Pending Orders</span>`);
            } else {
                $('#m_labs_status').html(`<span class="badge bg-success shadow-sm">All Completed</span>`);
            }

            let dHtml = '';
            if(res.diagnoses.length > 0) {
                res.diagnoses.forEach(d => {
                    let princ = d.is_principal == 1 ? '<span class="badge bg-primary me-2">Principal</span>' : '';
                    let gdrg = d.gdrg_mapped_code ? `<span class="small fw-bold text-success ms-2">[G-DRG: ${d.gdrg_mapped_code}]</span>` : `<span class="small fw-bold text-danger ms-2">[G-DRG: Unmapped]</span>`;
                    dHtml += `<div class="diag-item">${princ}<span class="fw-bold text-dark">${d.code}</span> - <span class="small text-muted">${d.description}</span> ${gdrg}</div>`;
                });
            } else {
                dHtml = '<span class="text-danger fw-bold"><i class="fa fa-triangle-exclamation"></i> No Diagnosis Entered. Discharge will be blocked.</span>';
            }
            $('#m_diagnoses_list').html(dHtml);

            let tHtml = '';
            if(res.latest_records.length > 0) {
                res.latest_records.forEach(r => {
                    tHtml += `
                    <div class="timeline-item">
                        <div class="small fw-bold text-primary mb-1">${r.time_fmt} - ${r.author}</div>
                        <div class="fw-bold text-dark small" style="font-size:10px;">${r.field_name}</div>
                        <div class="small text-muted">${r.field_value}</div>
                    </div>`;
                });
            } else {
                tHtml = '<span class="text-muted small">No recent ward entries found.</span>';
            }
            $('#m_latest_records').html(tHtml);

        } else {
            $('#dischargeClearanceModal').modal('hide');
            showAppResponse("Data Retrieval Error", res.message, 'error');
        }
    }, 'json');
};