$(document).ready(function() {
    $('#patientSelect').select2({
        placeholder: "-- View All Pending or Select Specific Patient --",
        allowClear: true
    });
    evaluateBatchButton();
});

// Navigation & Filtering
function applyFilters() {
    const d = document.getElementById('filterDate').value;
    const p = document.getElementById('patientSelect').value;
    let url = `?filter_date=${d ? d : 'ALL'}`;
    if (p) url += `&patient_no=${p}`;
    window.location.href = url;
}

function clearFilters() {
    window.location.href = `?filter_date=ALL`;
}

function switchTest(itemId) {
    document.querySelectorAll('.test-tab').forEach(tab => tab.classList.remove('active'));
    const activeTab = document.getElementById(`tab-${itemId}`);
    if(activeTab) activeTab.classList.add('active');

    document.querySelectorAll('.test-card').forEach(card => card.classList.remove('active'));
    const activeCard = document.getElementById(`card-${itemId}`);
    if(activeCard) activeCard.classList.add('active');
}

function filterTabs() {
    const searchVal = document.getElementById('tabSearch').value.toLowerCase();
    const tabs = document.querySelectorAll('.test-tab');
    
    let firstVisibleId = null;
    let visibleCount = 0;

    tabs.forEach(tab => {
        const tSearch = tab.getAttribute('data-search');
        if (tSearch.includes(searchVal)) {
            tab.style.display = 'flex';
            visibleCount++;
            if(!firstVisibleId) firstVisibleId = tab.id.replace('tab-', '');
        } else {
            tab.style.display = 'none';
            tab.querySelector('.verify-check').checked = false;
        }
    });

    const emptyCanvas = document.getElementById('emptyCanvas');
    if(visibleCount === 0) {
        document.querySelectorAll('.test-card').forEach(card => card.classList.remove('active'));
        emptyCanvas.style.display = 'flex';
        emptyCanvas.classList.add('active');
    } else {
        emptyCanvas.style.display = 'none';
        emptyCanvas.classList.remove('active');
        
        const currentActive = document.querySelector('.test-tab.active');
        if(currentActive && currentActive.style.display === 'none' && firstVisibleId) {
            switchTest(firstVisibleId);
        } else if (!currentActive && firstVisibleId) {
            switchTest(firstVisibleId);
        }
    }
    syncMasterCheckbox();
}

// Batch Checkbox Logic
function toggleAllVerify(masterCheckbox) {
    const visibleCheckboxes = document.querySelectorAll('.test-tab[style="display: flex;"] .verify-check, .test-tab:not([style*="display: none"]) .verify-check');
    visibleCheckboxes.forEach(cb => cb.checked = masterCheckbox.checked);
    evaluateBatchButton();
}

function syncMasterCheckbox() {
    const visibleCheckboxes = document.querySelectorAll('.test-tab[style="display: flex;"] .verify-check, .test-tab:not([style*="display: none"]) .verify-check');
    const checkedCheckboxes = document.querySelectorAll('.test-tab[style="display: flex;"] .verify-check:checked, .test-tab:not([style*="display: none"]) .verify-check:checked');
    const master = document.getElementById('masterVerifyCheck');
    
    if(visibleCheckboxes.length === 0) {
        master.checked = false;
        master.indeterminate = false;
    } else {
        master.checked = (visibleCheckboxes.length === checkedCheckboxes.length);
        master.indeterminate = (checkedCheckboxes.length > 0 && checkedCheckboxes.length < visibleCheckboxes.length);
    }
    evaluateBatchButton();
}

function evaluateBatchButton() {
    const checkedCount = document.querySelectorAll('.verify-check:checked').length;
    const btn = document.getElementById('btnBatchVerify');
    btn.disabled = (checkedCount === 0);
}

// Modals & UI Feedback
function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

function showToast(message, type = 'success') {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-circle-exclamation';
    toast.innerHTML = `<i class="fa-solid ${iconClass} toast-icon"></i><span class="toast-msg">${message}</span>`;
    container.appendChild(toast);
    setTimeout(() => toast.classList.add('show'), 10);
    setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 3500);
}

// API Interactions (Verification & Rejection)
function openAuthModal(itemIdsArray, patientSet) {
    document.getElementById('authTargetData').value = JSON.stringify(itemIdsArray);
    document.getElementById('authTestCount').innerText = itemIdsArray.length;
    document.getElementById('authPatientCount').innerText = patientSet.size;
    
    document.getElementById('authStep1').style.display = 'block';
    document.getElementById('authModal').style.display = 'flex';
}

function initiateSingleAuth(itemId) {
    const tab = document.getElementById(`tab-${itemId}`);
    const patientName = tab.getAttribute('data-patient');
    let patientSet = new Set([patientName]);
    openAuthModal([itemId], patientSet);
}

function initiateBatchAuth() {
    const checkedBoxes = document.querySelectorAll('.verify-check:checked');
    if(checkedBoxes.length === 0) return;
    
    let itemIds = [];
    let patientSet = new Set();
    
    checkedBoxes.forEach(cb => {
        itemIds.push(cb.value);
        const tab = document.getElementById(`tab-${cb.value}`);
        patientSet.add(tab.getAttribute('data-patient'));
    });
    openAuthModal(itemIds, patientSet);
}

function executeAuth() {
    const targetData = JSON.parse(document.getElementById('authTargetData').value);
    
    let payload = {
        action: 'VERIFY',
        requests: []
    };

    targetData.forEach(id => {
        const notes = document.getElementById(`review-notes-${id}`).value;
        payload.requests.push({ request_id: id, pathologist_remarks: notes });
    });

    fetch('../../dripend/includes/lab/processVerifyLabTest.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
    .then(async res => {
        if(!res.ok) throw new Error('HTTP error ' + res.status);
        return res.json();
    })
    .then(data => {
        if(data.status === 'success') {
            showToast(`${targetData.length} result(s) successfully verified and released.`, "success");
            setTimeout(() => window.location.reload(), 1500);
        } else {
            showToast(data.message, 'error');
        }
        closeModal('authModal');
    })
    .catch(err => {
        showToast('Network error processing verification.', 'error');
        console.error(err);
        closeModal('authModal');
    });
}

function initiateRejection(itemId) {
    const notes = document.getElementById(`review-notes-${itemId}`).value;
    if(notes.trim() === '') {
        showToast("Please provide a reason in the Reviewer Conclusion box before rejecting.", "error");
        document.getElementById(`review-notes-${itemId}`).focus();
        return;
    }
    
    if(confirm("Are you sure you want to reject these results? The testing scientist will be notified.")) {
        
        let payload = {
            action: 'REJECT',
            requests: [{ request_id: itemId, pathologist_remarks: notes }]
        };

        fetch('../../dripend/includes/lab/processVerifyLabTest.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        })
        .then(async res => {
            if(!res.ok) throw new Error('HTTP error ' + res.status);
            return res.json();
        })
        .then(data => {
            if(data.status === 'success') {
                showToast("Test rejected and routed back to Testing Phase.", "success");
                setTimeout(() => window.location.reload(), 1500);
            } else {
                showToast(data.message, 'error');
            }
        })
        .catch(err => {
            showToast('Network error processing rejection.', 'error');
            console.error(err);
        });
    }
}