let orderCart = [];

$(document).ready(function() {
    
    // ---------------------------------------------------------
    // 1. WALK-IN: PATIENT & VISIT SETUP
    // ---------------------------------------------------------
    if ($('#walkinPatientSearch').length) {
        $('#walkinPatientSearch').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search by Name, Phone, or ID...',
            minimumInputLength: 2,
            ajax: {
                url: '/rimax/application/dripend/clinical/ajaxSearchPatient.php',
                dataType: 'json',
                delay: 250,
                data: function (params) { return { q: params.term }; },
                processResults: function (data) { return { results: data.results }; }
            }
        });

        $('#walkinPatientSearch').on('select2:select', function (e) {
            const data = e.params.data;
            currentPatientNo = data.id;
            
            // Auto-select insurance logic based on patient profile
            $('#visitPaymentCategory').val(data.default_payer).trigger('change');
            if(data.default_payer === 'Corporate' && data.insurance_id) {
                $('#visitCorpProvider').val(data.insurance_id);
                if(data.insurance_no) {
                    $('#visitCorpNo').val(data.insurance_no).prop('readonly', true);
                    currentCorpNo = data.insurance_no;
                } else {
                    $('#visitCorpNo').val('').prop('readonly', false);
                    currentCorpNo = '';
                }
            }
            
            $('#patientSelectionCard').slideUp(); 
            $('#visitConfigCard').fadeIn();
            
            $.get('/rimax/application/dripend/statpages/patientProfileHeader.php', { patient_no: currentPatientNo })
            .done(function(html) { $('#patientHeaderContainer').html(html); });
        });

        // Toggle Fields dynamically based on Payer
        $('#visitPaymentCategory').on('change', function() {
            const val = $(this).val();
            if (val === 'NHIS') {
                $('#nhisCCCContainer').slideDown();
                $('#corpProviderContainer').slideUp();
                $('#corpPolicyContainer').slideUp();
            } else if (val === 'Corporate') {
                $('#corpProviderContainer').slideDown();
                $('#corpPolicyContainer').slideDown();
                $('#nhisCCCContainer').slideUp();
                $('#visitCCC').val('');
                currentCCC = '';
            } else {
                $('#nhisCCCContainer').slideUp();
                $('#corpProviderContainer').slideUp();
                $('#corpPolicyContainer').slideUp();
                $('#visitCCC').val('');
                $('#visitCorpProvider').val('');
                $('#visitCorpNo').val('');
                currentCCC = '';
                currentInsuranceId = 0;
                currentCorpNo = '';
            }
        });

        $('#btnGenerateCCC').on('click', function() {
            const btn = $(this);
            btn.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);
            $.post('/rimax/application/dripend/nhisClaimCheckCode/nhisCCC.php', { patient_no: currentPatientNo })
            .done(function(response) {
                if(response.status === 'success') {
                    $('#visitCCC').val(response.ccc);
                    currentCCC = response.ccc;
                    Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: 'CCC Fetched', showConfirmButton: false, timer: 2000 });
                } else {
                    Swal.fire('Error', 'Failed to generate CCC.', 'error');
                }
            })
            .fail(function() {
                Swal.fire('Warning', 'CCC Endpoint unreachable. Enter manually.', 'warning');
            })
            .always(function() {
                btn.html('<i class="fas fa-sync-alt me-2"></i> Fetch CCC').prop('disabled', false);
            });
        });

        // Finalize Setup and Open Cart
        $('#btnProceedToCart').on('click', function() {
            currentPaymentCat = $('#visitPaymentCategory').val();
            
            if (currentPaymentCat === 'NHIS') {
                currentCCC = $('#visitCCC').val().trim();
                currentInsuranceId = 0;
                currentCorpNo = '';
                if(currentCCC === '') {
                    Swal.fire('Required', 'Please generate or enter the NHIS CCC Code.', 'warning');
                    return;
                }
            } else if (currentPaymentCat === 'Corporate') {
                currentInsuranceId = $('#visitCorpProvider').val();
                currentCorpNo = $('#visitCorpNo').val().trim();
                currentCCC = '';
                if(!currentInsuranceId || currentCorpNo === '') {
                    Swal.fire('Required', 'Please select a Provider and enter the Policy Number.', 'warning');
                    return;
                }
            }

            let badgeText = currentPaymentCat;
            if(currentPaymentCat === 'Corporate') {
                badgeText = "Corporate (" + $("#visitCorpProvider option:selected").text() + ")";
            }

            $('#paymentBadge').html(`<i class="fas fa-wallet me-1"></i> Payer: ${badgeText}`);
            $('#visitConfigCard').slideUp();
            $('#clinicalCartCard').fadeIn();
        });
    }

    // ---------------------------------------------------------
    // 2. CLINICAL CART LOGIC
    // ---------------------------------------------------------
    $('#serviceSearch').select2({
        theme: 'bootstrap-5',
        placeholder: 'Search catalog for labs, imaging, procedures...',
        allowClear: true,
        minimumInputLength: 2,
        ajax: {
            url: '/rimax/application/dripend/clinical/ajaxSearchServices.php',
            dataType: 'json',
            delay: 250,
            data: function (params) { 
                return { 
                    q: params.term,
                    patient_no: currentPatientNo,
                    payment_cat: currentPaymentCat,
                    insurance_id: currentInsuranceId
                }; 
            },
            processResults: function (data) { return { results: data.results }; }
        }
    });

    $('#serviceSearch').on('select2:select', function (e) {
        const data = e.params.data;
        
        if(orderCart.find(item => item.id === data.id)) {
            Swal.fire({ toast: true, position: 'top-end', icon: 'warning', title: 'Already added', showConfirmButton: false, timer: 2000 });
            $(this).val(null).trigger('change');
            return;
        }

        orderCart.push({
            id: data.id,
            name: data.service_name,
            department: data.department,
            price: parseFloat(data.payable_amount), 
            priority: 'Routine',
            notes: ''
        });

        renderCart();
        $(this).val(null).trigger('change'); 
    });

    $('#btnSubmitOrders').on('click', submitClinicalOrders);
});

function renderCart() {
    const tbody = document.getElementById('cartBody');
    const tfoot = document.getElementById('cartFooter');
    const btnSubmit = document.getElementById('btnSubmitOrders');

    if (orderCart.length === 0) {
        tbody.innerHTML = `<tr id="emptyCartRow"><td colspan="5" class="text-center py-5"><i class="fas fa-shopping-basket fa-3x text-muted mb-3" style="opacity: 0.3;"></i><h6 class="fw-bold text-secondary">Your request cart is empty</h6></td></tr>`;
        tfoot.style.display = 'none';
        btnSubmit.disabled = true;
        return;
    }

    btnSubmit.disabled = false;
    let html = '';
    let cartTotal = 0.00;
    
    orderCart.forEach((item, index) => {
        cartTotal += item.price;
        html += `
        <tr>
            <td>
                <div class="fw-bold text-dark"><i class="fas fa-check-circle text-success me-2"></i> ${item.name}</div>
                <div class="text-muted small mt-1 ms-4">${item.department}</div>
            </td>
            <td>
                <select class="form-select border-2" onchange="updatePriority(${index}, this.value)">
                    <option value="Routine" ${item.priority === 'Routine' ? 'selected' : ''}>Routine</option>
                    <option value="Urgent" ${item.priority === 'Urgent' ? 'selected' : ''}>Urgent</option>
                    <option value="STAT" ${item.priority === 'STAT' ? 'selected' : ''}>STAT</option>
                </select>
            </td>
            <td class="text-end fw-bold text-dark align-middle fs-6">
                ${item.price.toFixed(2)}
            </td>
            <td>
                <input type="text" class="form-control border-2" placeholder="Optional notes..." 
                       value="${item.notes}" oninput="updateNote(${index}, this.value)">
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-outline-danger border-2" onclick="removeItem(${index})" title="Remove Item">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>`;
    });
    
    tbody.innerHTML = html;
    document.getElementById('cartTotalDisplay').innerText = 'GHS ' + cartTotal.toFixed(2);
    tfoot.style.display = 'table-footer-group';
}

window.updatePriority = function(index, value) { orderCart[index].priority = value; };
window.updateNote = function(index, value) { orderCart[index].notes = value; };
window.removeItem = function(index) { orderCart.splice(index, 1); renderCart(); };

function submitClinicalOrders() {
    if(orderCart.length === 0 || !currentPatientNo) return;

    const btn = document.getElementById('btnSubmitOrders');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Routing & Saving Bill...';
    btn.disabled = true;

    fetch('/rimax/application/dripend/clinical/saveClinicalOrders.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            visit_id: currentVisitId,
            patient_no: currentPatientNo,
            payment_category: currentPaymentCat,
            ccc_code: currentCCC,
            insurance_id: currentInsuranceId,
            corp_no: currentCorpNo, // Passes the policy number
            orders: orderCart
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            Swal.fire({ title: 'Success!', text: 'Orders routed and billed. Audit logged.', icon: 'success', confirmButtonColor: '#2563eb' })
            .then(() => {
                if(currentVisitId == "0" || !currentVisitId) { window.location.reload(); }
                else { orderCart = []; renderCart(); }
            });
        } else {
            Swal.fire('Error', data.message, 'error');
            btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i> Route Orders & Save Bill';
            btn.disabled = false;
        }
    })
    .catch(err => {
        Swal.fire('Error', 'Network connection failed.', 'error');
        btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i> Route Orders & Save Bill';
        btn.disabled = false;
    });
}