// --- Navigation & Filtering ---
function applyDateFilter() {
    const dFrom = document.getElementById('dateFrom').value;
    const dTo = document.getElementById('dateTo').value;
    
    if(!dFrom || !dTo) {
        showToast("Please select both From and To dates.", "error");
        return;
    }
    
    window.location.href = `?date_from=${dFrom}&date_to=${dTo}`;
}

function viewAllBacklog() {
    window.location.href = `?date_from=ALL`;
}

// --- Table Selections ---
function toggleAll(masterCheckbox) {
    const checkboxes = document.querySelectorAll('.row-check');
    checkboxes.forEach(cb => cb.checked = masterCheckbox.checked);
    evaluateActionBtn();
}

function evaluateActionBtn() {
    const total = document.querySelectorAll('.row-check').length;
    const checked = document.querySelectorAll('.row-check:checked').length;
    const master = document.getElementById('masterCheck');
    const btn = document.getElementById('btnAccept');

    if(total === 0) return;
    
    master.checked = (total === checked);
    master.indeterminate = (checked > 0 && checked < total);
    btn.disabled = (checked === 0);
}

document.querySelectorAll('.row-check').forEach(cb => {
    cb.addEventListener('change', evaluateActionBtn);
});

// --- API Interactions ---
function acceptSelected() {
    const checkedBoxes = document.querySelectorAll('.row-check:checked');
    if(checkedBoxes.length === 0) return;
    
    let requestIds = [];
    checkedBoxes.forEach(cb => requestIds.push(cb.value));
    
    const btn = document.getElementById('btnAccept');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> Processing...';

    const payload = {
        action: 'ACCEPT_INTO_LAB',
        requests: requestIds
    };

    fetch('../../dripend/includes/lab/processLabQueue.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(`${requestIds.length} request(s) formally accepted. Routing to Sample Collection...`, "success");
            
            // Route them straight to the sample collection page so they don't lose workflow momentum
            setTimeout(() => {
                window.location.href = 'collect_sample.php';
            }, 1500);
        } else {
            showToast(data.message, 'error');
            btn.disabled = false;
            btn.innerHTML = '<i class="fa-solid fa-check-double"></i> Accept Selected into Laboratory';
        }
    })
    .catch(err => {
        showToast('Network error processing requests.', 'error');
        console.error(err);
        btn.disabled = false;
        btn.innerHTML = '<i class="fa-solid fa-check-double"></i> Accept Selected into Laboratory';
    });
}

// --- UI Feedback ---
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 style="font-size: 14px; font-weight: 600; color: var(--text-main);">${message}</span>`;
    container.appendChild(toast);
    
    setTimeout(() => toast.classList.add('show'), 10);
    setTimeout(() => { 
        toast.classList.remove('show'); 
        setTimeout(() => toast.remove(), 300); 
    }, 3500);
}