const apiTheatre = '/rimax/application/dripend/includes/ipd/processTheatreManager.php';
let dtHistory;
let hFiltered = false;
let activeView = 'tile';

$(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];
    
    $('#q_start_date').val(firstDay);
    $('#q_end_date').val(lastDay);
    $('#h_start_date').val(firstDay);
    $('#h_end_date').val(lastDay);

    fetchKPIs();
    initHistoryTable();
    loadStaffDependencies();
    loadTheatreQueue(); // Load initially

    $('.rich-text-editor').summernote({
        height: 250,
        toolbar: [
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['font', ['strikethrough', 'superscript', 'subscript']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['view', ['fullscreen']]
        ]
    });
    
    $('.select2-modal').select2({ dropdownParent: $('#scheduleModal'), 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() {
    $.post(apiTheatre, { action: 'fetch_kpis' }, function(res) {
        if(res.status === 'success') {
            $('#kpi_pending').text(res.data.pending);
            $('#kpi_scheduled_today').text(res.data.scheduled_today);
            $('#kpi_completed_today').text(res.data.completed_today);
            $('#kpi_emergencies').text(res.data.emergencies);
        }
    }, 'json');
}

function loadStaffDependencies() {
    $.post(apiTheatre, { action: 'get_theatre_staff' }, function(res) {
        if (res.status === 'success') {
            let sOpts = '<option value="">-- Select Surgeon --</option>';
            res.surgeons.forEach(s => sOpts += `<option value="${s.id}">${s.name}</option>`);
            $('#sch_surgeon').html(sOpts);

            let aOpts = '<option value="">-- No Anesthetist Needed --</option>';
            res.anesthetists.forEach(a => aOpts += `<option value="${a.id}">${a.name}</option>`);
            $('#sch_anes').html(aOpts);
        }
    }, 'json');
}

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

    let payload = {
        action: 'fetch_active_queue',
        is_filtered: true,
        start_date: $('#q_start_date').val(),
        end_date: $('#q_end_date').val(),
        urgency: $('#q_urgency').val()
    };

    $.post(apiTheatre, payload, function(res) {
        $('#loading_state').hide();
        fetchKPIs();

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

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

        if(r.status === 'Scheduled') {
            borderClass = 'status-scheduled';
            statusBadge = `<span class="badge badge-outcome bg-primary position-absolute top-0 end-0 m-3 shadow-sm"><i class="fa-solid fa-calendar-check me-1"></i> Scheduled</span>`;
        } else if(r.status === 'In Progress') {
            borderClass = 'status-progress';
            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-spinner fa-spin me-1"></i> In Progress</span>`;
        } else {
            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-clock me-1"></i> Pending Schedule</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>';
        let uBadge = r.urgency === 'Emergency' ? '<span class="badge bg-danger shadow-sm ms-2">STAT</span>' : '';

        let procEsc = escape(r.procedure_name);
        let nameEsc = escape(r.patient_name);

        let actionBtns = `<div class="d-flex gap-2">`;
        if (r.status === 'Pending' || r.status === 'Scheduled') {
            actionBtns += `<button class="quick-btn" title="Schedule Surgery" onclick="openScheduleModal(${r.id}, '${nameEsc}', '${procEsc}', '${r.surgeon_id}', '${r.anesthetist_id}', '${r.scheduled_date}')"><i class="fa-solid fa-calendar text-primary"></i></button>`;
        }
        actionBtns += `<button class="quick-btn" title="Complete Surgery" onclick="openCompleteModal(${r.id}, '${nameEsc}', '${procEsc}')"><i class="fa-solid fa-check-double text-success"></i></button></div>`;

        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.patient_name}</h5>
                    <span class="badge bg-light text-secondary border mb-1">${r.patient_no}</span> ${uBadge}
                </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-hospital-user text-info"></i> <b>${r.safe_room}</b></p>
                <p><i class="fa-solid fa-scalpel text-danger"></i> <b>${r.procedure_name}</b></p>
                <p><i class="fa-solid fa-user-doctor"></i> Surg: Dr. ${r.surgeon_name || 'Unassigned'}</p>
            </div>
            <div class="tile-actions">
                ${actionBtns}
                <button onclick="window.location.href='theatrePatientRecords.php?visit_id=${r.visit_id}&req_id=${r.id}'" class="full-chart-btn shadow-sm">Theatre Chart <i class="fa-solid fa-arrow-right ms-1"></i></button>
            </div>
        </div>`;
    });
    $('#tile_view').html(html);
}

function renderListView(data) {
    let html = '';
    data.forEach(r => {
        let uBadge = r.urgency === 'Emergency' ? 'bg-danger' : (r.urgency === 'Urgent' ? 'bg-warning text-dark' : 'bg-secondary');
        let sBadge = r.status === 'Scheduled' ? 'bg-primary' : (r.status === 'In Progress' ? 'bg-info text-dark' : 'bg-secondary');
        
        let procEsc = escape(r.procedure_name);
        let nameEsc = escape(r.patient_name);

        let actionBtns = `<button onclick="window.location.href='theatrePatientRecords.php?visit_id=${r.visit_id}&req_id=${r.id}'" class="btn btn-sm btn-dark fw-bold px-3 py-1 shadow-sm"><i class="fa-solid fa-folder-open me-1"></i> Open Chart</button> `;
        
        if (r.status === 'Pending' || r.status === 'Scheduled') {
            actionBtns += `<button class="btn btn-sm btn-light border text-primary shadow-sm py-1 px-2" title="Schedule" onclick="openScheduleModal(${r.id}, '${nameEsc}', '${procEsc}', '${r.surgeon_id}', '${r.anesthetist_id}', '${r.scheduled_date}')"><i class="fa-solid fa-calendar"></i></button> `;
        }
        actionBtns += `<button class="btn btn-sm btn-light border text-success shadow-sm py-1 px-2" title="Complete" onclick="openCompleteModal(${r.id}, '${nameEsc}', '${procEsc}')"><i class="fa-solid fa-check-double"></i></button>`;

        html += `
        <tr class="list-row">
            <td>
                <div class="d-flex flex-column">
                    <span class="fw-bold text-primary" style="font-size:15px;">${r.patient_name}</span>
                    <span class="text-muted small fw-bold">${r.patient_no} | ${r.gender_name}</span>
                </div>
            </td>
            <td>
                <b class="text-dark"><i class="fa-solid fa-scalpel text-muted me-1"></i> ${r.procedure_name}</b><br>
                <span class="small text-muted fw-bold">By: Dr. ${r.surgeon_name || 'Unassigned'}</span>
            </td>
            <td>
                <span class="badge bg-dark px-3 py-2 shadow-sm"><i class="fa-solid fa-hospital-user text-info me-1"></i> ${r.safe_room}</span><br>
                <span class="small text-muted fw-bold mt-1 d-block">Origin: ${r.location_str}</span>
            </td>
            <td><span class="badge ${uBadge} shadow-sm px-2 py-1">${r.urgency}</span></td>
            <td>
                <span class="badge ${sBadge} shadow-sm px-2 py-1 mb-1">${r.status}</span><br>
                <span class="small fw-bold text-muted">${r.scheduled_on}</span>
            </td>
            <td class="text-end">${actionBtns}</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();
    }
};

window.applyQueueFilter = function() {
    loadTheatreQueue();
};

function initHistoryTable() {
    dtHistory = $('#tblTheatreHistory').DataTable({
        ajax: {
            url: apiTheatre,
            type: 'POST',
            data: function(d) {
                d.action = 'fetch_surgical_history';
                d.is_filtered = hFiltered;
                d.start_date = $('#h_start_date').val();
                d.end_date = $('#h_end_date').val();
            },
            dataSrc: function(json) { return json.data || []; }
        },
        pageLength: 15,
        order: [[ 0, 'desc' ]],
        columns: [
            { data: 'completed_on', className: 'fw-bold text-muted small' },
            { data: null, render: r => `<b class="text-primary">${r.patient_name}</b><br><span class="small text-muted">${r.patient_no}</span>` },
            { data: 'procedure_name', className: 'fw-bold text-dark' },
            { data: 'surgeon_name', render: d => `<span class="small fw-bold">Dr. ${d}</span>` },
            { data: 'surgical_notes', render: d => `<div style="max-height:80px; overflow:hidden; font-size:12px;" class="text-muted border rounded p-2 bg-light">${d || 'No notes.'}</div>` }
        ]
    });
}

window.applyHistoryFilter = function() {
    let sd = $('#h_start_date').val(); let ed = $('#h_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; 
    }
    hFiltered = true;
    $('#history_empty_state').hide();
    $('#history_table_wrapper').fadeIn();
    dtHistory.ajax.reload();
};

window.openScheduleModal = function(req_id, patient_name, procedure, surg_id, anes_id, sch_date) {
    $('#frmScheduleSurgery')[0].reset();
    $('#sch_req_id').val(req_id);
    $('#sch_patient_name').text(unescape(patient_name));
    $('#sch_procedure').text(unescape(procedure));
    
    if (surg_id && surg_id !== 'null') $('#sch_surgeon').val(surg_id).trigger('change');
    if (anes_id && anes_id !== 'null') $('#sch_anes').val(anes_id).trigger('change');
    if (sch_date && sch_date !== 'null') {
        let sd = new Date(sch_date);
        let iso = new Date(sd.getTime() - (sd.getTimezoneOffset() * 60000)).toISOString().slice(0,16);
        $('#sch_date').val(iso);
    }
    
    $('#scheduleModal').modal('show');
};

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

    $.post(apiTheatre, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res.status === 'success') {
            $('#scheduleModal').modal('hide');
            showAppResponse("Scheduled", res.message, 'success');
            loadTheatreQueue();
        } else {
            showAppResponse("Scheduling Failed", res.message, 'error');
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Server Error", "A critical error occurred while saving.", 'error');
    });
});

window.openCompleteModal = function(req_id, patient_name, procedure) {
    $('#frmCompleteSurgery')[0].reset();
    $('#comp_notes').summernote('code', '');
    $('#comp_req_id').val(req_id);
    $('#comp_patient_name').text(unescape(patient_name));
    $('#comp_procedure').text(unescape(procedure));
    
    $('#completeModal').modal('show');
};

$('#frmCompleteSurgery').on('submit', function(e) {
    e.preventDefault();
    
    if ($('#comp_notes').summernote('isEmpty')) {
        showAppResponse("Validation Error", "Surgical notes cannot be empty.", 'error');
        return;
    }

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

    $.post(apiTheatre, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res.status === 'success') {
            $('#completeModal').modal('hide');
            showAppResponse("Surgery Completed", res.message, 'success');
            loadTheatreQueue();
            if(hFiltered) dtHistory.ajax.reload(null, false);
        } else {
            showAppResponse("Action Failed", res.message, 'error');
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Server Error", "A critical error occurred while completing the surgery. Transaction rolled back.", 'error');
    });
});