let dtQueue;
const apiTransfer = '/rimax/application/dripend/includes/ipd/processWardTransferManager.php';
let currentStatusTab = 'Pending';
let isDataLoaded = false;

$(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);

    loadDependencies();
    initDataTable();
    fetchKPIs();
    
    $('.select2-modal').select2({ dropdownParent: $('#initiateTransferModal'), width: '100%' });
});

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() {
    let payload = {
        action: 'fetch_kpis',
        date_from: $('#flt_start').val(),
        date_to: $('#flt_end').val(),
        ward_id: $('#flt_ward').val()
    };
    $.post(apiTransfer, payload, function(res) {
        if(res.status === 'success') {
            $('#kpi_incoming').text(res.data.incoming_pending);
            $('#kpi_outgoing').text(res.data.outgoing_pending);
            $('#kpi_completed').text(res.data.completed_transfers);
            $('#kpi_rejected').text(res.data.rejected_transfers);
        }
    }, 'json');
}

function loadDependencies() {
    $.post(apiTransfer, { action: 'fetch_dependencies' }, function(res) {
        if(res.status === 'success') {
            let pOpts = '<option value="">-- Search & Select Active Patient --</option>';
            res.patients.forEach(p => {
                pOpts += `<option value="${p.visit_master_id}">[${p.patient_no}] ${p.patient_name} - Current: ${p.ward_name} (Bed ${p.bed_number})</option>`;
            });
            $('#init_visit_id').html(pOpts);

            let wOpts = '<option value="">-- Select Destination Ward --</option>';
            res.wards.forEach(w => wOpts += `<option value="${w.id}">${w.ward_name}</option>`);
            $('#init_target_ward').html(wOpts);
        }
    }, 'json');
}

$('#init_target_ward').change(function() {
    let w_id = $(this).val();
    let bedSel = $('#init_target_bed');
    
    if(!w_id) { bedSel.html('<option value="">Select Ward First</option>').prop('disabled', true); return; }

    bedSel.html('<option value="">Loading beds...</option>').prop('disabled', true);
    
    $.post(apiTransfer, { action: 'fetch_vacant_beds', ward_id: w_id }, function(res) {
        if(res.status === 'success') {
            let bOpts = '<option value="">-- Leave empty for Pending Queue --</option>';
            if(res.data.length > 0) {
                res.data.forEach(b => bOpts += `<option value="${b.id}">${b.display_name}</option>`);
            } else {
                bOpts = '<option value="">No Vacant Beds (Will Queue)</option>';
            }
            bedSel.html(bOpts).prop('disabled', false);
        }
    }, 'json');
});

window.switchTab = function(status) {
    currentStatusTab = status;
    $('.nav-link').removeClass('active');
    
    if(status === 'Pending') $('#pending-tab').addClass('active');
    if(status === 'Completed') $('#history-tab').addClass('active');
    if(status === 'Rejected') $('#rejected-tab').addClass('active');
    
    if(isDataLoaded) applyFilter();
};

window.applyFilter = function() {
    let sd = $('#flt_start').val(); let ed = $('#flt_end').val();
    if(sd && ed && new Date(sd) > new Date(ed)) { 
        showAppResponse("Date Error", "Start Date cannot be greater than End Date.", 'error'); return; 
    }
    
    isDataLoaded = true;
    $('#empty_state').hide();
    $('#table_wrapper').fadeIn();
    
    fetchKPIs();
    dtQueue.ajax.reload();
};

function initDataTable() {
    dtQueue = $('#tblTransferQueue').DataTable({
        ajax: {
            url: apiTransfer,
            type: 'POST',
            data: function(d) {
                d.action = 'fetch_transfer_queue';
                d.is_filtered = isDataLoaded;
                d.date_from = $('#flt_start').val();
                d.date_to = $('#flt_end').val();
                d.ward_id = $('#flt_ward').val();
                d.direction = $('#flt_direction').val();
                d.status_filter = currentStatusTab;
            },
            dataSrc: function (json) {
                if (json.status === 'error') { showAppResponse("System Error", json.message, 'error'); return []; }
                return json.data || [];
            }
        },
        pageLength: 15,
        columnDefs: [ { searchable: false, orderable: false, targets: 0 } ],
        order: [[ 1, 'desc' ]], 
        columns: [
            { data: null, defaultContent: '', className: 'dt-serial' },
            { data: 'req_date_fmt', className: 'fw-bold text-muted small' },
            {
                data: null,
                render: function(data, type, row) {
                    return `<b class="text-primary fs-6">${row.patient_name}</b><br><span class="small fw-bold text-muted">${row.patient_no} | ${row.gender_name}</span>`;
                }
            },
            { 
                data: null, 
                render: function(r) {
                    let badge = r.transfer_type === 'Theatre Transfer' ? 'badge-theatre' : 'badge-ward';
                    let icon = r.transfer_type === 'Theatre Transfer' ? 'fa-scalpel-line-dashed' : 'fa-bed';
                    let tIcon = r.transfer_type === 'Theatre Transfer' ? 'fa-procedures' : 'fa-hospital-user';
                    return `
                        <div class="d-flex align-items-center gap-2 mb-1">
                            <span class="badge ${badge} px-2 py-1 shadow-sm"><i class="fa-solid ${icon} me-1"></i> ${r.from_location}</span>
                            <i class="fa-solid fa-arrow-right text-muted"></i>
                            <span class="badge bg-dark px-2 py-1 shadow-sm"><i class="fa-solid ${tIcon} me-1 text-info"></i> ${r.target_location}</span>
                        </div>
                        <span class="small text-muted fw-bold">By: Dr/Nurse ${r.req_doctor}</span>`;
                }
            },
            { 
                data: null, 
                render: function(r) {
                    let notes = r.notes || 'No notes provided.';
                    let sBadge = '';
                    if(r.mapped_status === 'Pending') sBadge = `<span class="badge bg-warning text-dark shadow-sm">Pending Acceptance</span>`;
                    if(r.mapped_status === 'Admitted') sBadge = `<span class="badge bg-success shadow-sm">Transfer Completed</span>`;
                    if(r.mapped_status === 'Rejected') sBadge = `<span class="badge bg-danger shadow-sm">Rejected: ${r.rejection_reason}</span>`;
                    
                    return `<div class="mb-1">${sBadge}</div><span class="small text-muted">${notes}</span>`;
                }
            },
            {
                data: null, className: 'text-end', orderable: false,
                render: function(data, type, row) {
                    if (row.mapped_status === 'Pending') {
                        return `
                        <button class="btn btn-sm btn-success fw-bold px-3 shadow-sm mb-1" onclick="openAcceptModal(${row.id}, ${row.target_ward_id || 0}, '${escape(row.target_location)}', '${row.transfer_type}', ${row.visit_master_id})"><i class="fa-solid fa-check me-1"></i> Accept</button>
                        <button class="btn btn-sm btn-danger fw-bold px-3 shadow-sm mb-1 ms-1" onclick="openRejectModal(${row.id}, '${row.transfer_type}')"><i class="fa-solid fa-times me-1"></i> Reject</button>`;
                    } else {
                        return `<span class="text-muted small fw-bold"><i class="fa-solid fa-lock me-1"></i> Locked</span>`;
                    }
                }
            }
        ]
    });

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

window.openInitiateModal = function() {
    $('#frmInitiateTransfer')[0].reset();
    $('#init_visit_id, #init_target_ward').val('').trigger('change');
    $('#initiateTransferModal').modal('show');
};

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

    $.post(apiTransfer, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res.status === 'success') {
            $('#initiateTransferModal').modal('hide');
            showAppResponse("Transfer Initiated", res.message, 'success');
            fetchKPIs(); if(isDataLoaded) dtQueue.ajax.reload(null, false); loadDependencies();
        } else {
            showAppResponse("Initiation Failed", res.message, 'error');
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Server Error", "A critical error occurred while attempting to initiate the transfer. Database transaction rolled back.", 'error');
    });
});

window.openAcceptModal = function(req_id, ward_id, ward_name, transfer_type, visit_id) {
    $('#frmAcceptTransfer')[0].reset();
    $('#accept_req_id').val(req_id);
    $('#accept_transfer_type').val(transfer_type);
    $('#lbl_accept_ward').text(unescape(ward_name));
    
    // Fetch Clinical Summary Data for Left Pane
    $('#transfer_clinical_summary').html('<div class="text-center py-4"><i class="fa fa-spinner fa-spin fa-2x text-muted"></i></div>');
    $.post(apiTransfer, { action: 'fetch_transfer_summary', visit_id: visit_id }, function(res) {
        if(res.status === 'success') {
            let sHtml = '';
            
            // Vitals
            if(res.vitals) {
                sHtml += `<h6 class="text-dark fw-bold small text-uppercase mt-2"><i class="fa-solid fa-heart-pulse text-danger me-1"></i> Latest Vitals</h6>`;
                sHtml += `<div class="mb-3">`;
                if(res.vitals.bp_systolic) sHtml += `<span class="vital-pill">BP: ${res.vitals.bp_systolic}/${res.vitals.bp_diastolic}</span>`;
                if(res.vitals.pulse_rate) sHtml += `<span class="vital-pill">Pulse: ${res.vitals.pulse_rate} bpm</span>`;
                if(res.vitals.temperature) sHtml += `<span class="vital-pill">Temp: ${res.vitals.temperature} °C</span>`;
                if(res.vitals.spo2) sHtml += `<span class="vital-pill">SpO2: ${res.vitals.spo2}%</span>`;
                sHtml += `</div>`;
            }

            // Diagnostics
            if(res.labs.length > 0) {
                sHtml += `<h6 class="text-dark fw-bold small text-uppercase mt-2"><i class="fa-solid fa-microscope text-info me-1"></i> Recent Diagnostics</h6><ul class="mb-3 ps-3">`;
                res.labs.forEach(l => { sHtml += `<li class="small fw-bold text-muted">${l.test_name} <span class="badge bg-light text-dark border ms-1">${l.status}</span></li>`; });
                sHtml += `</ul>`;
            }

            // Meds
            if(res.meds.length > 0) {
                sHtml += `<h6 class="text-dark fw-bold small text-uppercase mt-2"><i class="fa-solid fa-pills text-warning me-1"></i> Active Prescriptions</h6><ul class="mb-3 ps-3">`;
                res.meds.forEach(m => { sHtml += `<li class="small fw-bold text-muted">${m.drug_name} <span class="badge bg-light text-dark border ms-1">${m.status}</span></li>`; });
                sHtml += `</ul>`;
            }

            // Notes
            if(res.notes.length > 0) {
                sHtml += `<h6 class="text-dark fw-bold small text-uppercase mt-2"><i class="fa-solid fa-file-lines text-secondary me-1"></i> Recent Clinical Notes</h6><div class="clinical-summary-box mb-3">`;
                res.notes.forEach(n => { sHtml += `<b class="text-primary">${n.time_fmt} - ${n.field_name}</b><p class="mb-2 text-dark">${n.field_value}</p>`; });
                sHtml += `</div>`;
            }

            if(sHtml === '') sHtml = '<p class="text-muted small">No significant clinical data found prior to this transfer.</p>';
            $('#transfer_clinical_summary').html(sHtml);
        }
    }, 'json');
    
    // UI logic for Right Pane (Bed Selection)
    if (transfer_type === 'Theatre Transfer') {
        $('#lblAcceptTitle').html('<i class="fa-solid fa-scalpel me-2"></i> Accept into Theatre');
        $('#bed_allocation_box').hide();
        $('#accept_bed_id').prop('required', false);
        $('#acceptTransferModal').modal('show');
    } else {
        $('#lblAcceptTitle').html('<i class="fa-solid fa-bed me-2"></i> Accept Transfer & Allocate Bed');
        $('#bed_allocation_box').show();
        let bedSel = $('#accept_bed_id');
        bedSel.prop('required', true).html('<option value="">Loading beds...</option>').prop('disabled', true);
        
        $.post(apiTransfer, { action: 'fetch_vacant_beds', ward_id: ward_id }, function(res) {
            if(res.status === 'success') {
                let bOpts = '<option value="">-- Select Bed to Allocate --</option>';
                if(res.data.length > 0) {
                    res.data.forEach(b => bOpts += `<option value="${b.id}">${b.display_name}</option>`);
                    bedSel.html(bOpts).prop('disabled', false);
                    $('#acceptTransferModal').modal('show');
                } else {
                    showAppResponse("No Beds Available", "The target ward currently has no vacant beds. Please clear beds before accepting.", "error");
                }
            }
        }, 'json').fail(function() {
            showAppResponse("Server Error", "Failed to retrieve vacant beds.", "error");
        });
    }
};

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

    $.post(apiTransfer, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res.status === 'success') {
            $('#acceptTransferModal').modal('hide');
            showAppResponse("Transfer Accepted", res.message, 'success');
            fetchKPIs(); if(isDataLoaded) dtQueue.ajax.reload(null, false); loadDependencies();
        } else {
            showAppResponse("Acceptance Failed", res.message, 'error');
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Server Error", "A critical error occurred while allocating the bed. Database transaction rolled back.", 'error');
    });
});

window.openRejectModal = function(req_id, transfer_type) {
    $('#frmRejectTransfer')[0].reset();
    $('#reject_req_id').val(req_id);
    $('#reject_transfer_type').val(transfer_type);
    $('#rejectTransferModal').modal('show');
};

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

    $.post(apiTransfer, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res.status === 'success') {
            $('#rejectTransferModal').modal('hide');
            showAppResponse("Transfer Rejected", res.message, 'success');
            fetchKPIs(); if(isDataLoaded) dtQueue.ajax.reload(null, false);
        } else {
            showAppResponse("Rejection Failed", res.message, 'error');
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Server Error", "A critical error occurred while attempting to reject the transfer. Database transaction rolled back.", 'error');
    });
});