/**
 * RiMax Opening Inventory Allocation Engine
 */

window.rowCounter = 0;
window.productsList = []; 

// 1. Fetch Location Dropdown
window.fetchLocations = async function() {
    const type = document.querySelector('input[name="location_type"]:checked').value;
    const select = document.getElementById('dynamic_location_select');
    
    select.innerHTML = '<option value="" disabled selected>Loading nodes...</option>';
    try {
        const res = await fetch(`../../dripend/systemSetup/inventory/fetchAllocationLookups.php?action=locations&type=${type}`);
        const json = await res.json();
        
        select.innerHTML = '<option value="" disabled selected>-- Select Target Destination --</option>';
        json.data.forEach(node => {
            select.insertAdjacentHTML('beforeend', `<option value="${node.id}">${node.name}</option>`);
        });
    } catch(e) { console.error("Lookup fault", e); }
};

// 2. Fetch Master Products once
window.preloadProducts = async function() {
    try {
        const res = await fetch('../../dripend/systemSetup/inventory/fetchAllocationLookups.php?action=products');
        const json = await res.json();
        window.productsList = json.data;
        window.addAllocationRow(); 
    } catch(e) { console.error("Product cache fault", e); }
};

// 3. Add Dynamic Row
window.addAllocationRow = function() {
    const tbody = document.getElementById('allocationItemsBody');
    window.rowCounter++;
    const idx = window.rowCounter;

    let prodOptions = '<option value="" selected disabled>Select...</option>';
    window.productsList.forEach(p => { prodOptions += `<option value="${p.id}">${p.generic_name}</option>`; });

    const rowHTML = `
        <tr id="row_${idx}">
            <td><select name="product_id[]" class="form-select form-select-sm" onchange="window.fetchVariants(this.value, ${idx})" required>${prodOptions}</select></td>
            <td><select name="variant_id[]" id="var_${idx}" class="form-select form-select-sm border-info bg-light"><option value="">-- Auto-loading --</option></select></td>
            <td>
                <input type="text" name="batch_number[]" class="form-control form-control-sm mb-1" placeholder="Batch No.">
                <div class="d-flex gap-1">
                    <input type="date" name="mfg_date[]" class="form-control form-control-sm" title="Mfg Date">
                    <input type="date" name="exp_date[]" class="form-control form-control-sm border-warning" title="Exp Date" required>
                </div>
            </td>
            <td><input type="number" name="quantity[]" id="qty_${idx}" class="form-control form-control-sm text-center fw-bold" min="1" oninput="window.calcTotals()" required></td>
            <td><input type="number" step="0.01" name="unit_cost[]" id="cost_${idx}" class="form-control form-control-sm text-end" oninput="window.calcTotals()" required></td>
            <td><input type="number" step="0.01" name="selling_price[]" id="sell_${idx}" class="form-control form-control-sm text-end" oninput="window.calcTotals()" required></td>
            <td class="text-center"><button type="button" class="btn btn-sm btn-danger py-1 px-2" onclick="document.getElementById('row_${idx}').remove(); window.calcTotals();"><i class="fa-solid fa-times"></i></button></td>
        </tr>
    `;
    tbody.insertAdjacentHTML('beforeend', rowHTML);
};

// 4. Fetch Variants (Brands) when Product is selected
window.fetchVariants = async function(productId, rowIdx) {
    const varSelect = document.getElementById(`var_${rowIdx}`);
    varSelect.innerHTML = '<option value="">Loading...</option>';

    // Auto-populate selling price from service_catalog cache
    const selectedProd = window.productsList.find(p => p.id == productId);
    if (selectedProd) {
        document.getElementById(`sell_${rowIdx}`).value = selectedProd.selling_price || 0;
        window.calcTotals();
    }

    try {
        const res = await fetch(`../../dripend/systemSetup/inventory/fetchAllocationLookups.php?action=variants&product_id=${productId}`);
        const json = await res.json();
        
        if(json.data.length === 0) {
            // CRITICAL FIX: Allow default/0 if no specific brand exists yet
            varSelect.innerHTML = '<option value="0">Default / No Brand Specified</option>';
            varSelect.required = false; 
            varSelect.disabled = false;
        } else {
            varSelect.disabled = false;
            varSelect.required = true;
            varSelect.innerHTML = '<option value="">-- Select Brand --</option>';
            json.data.forEach(v => {
                varSelect.insertAdjacentHTML('beforeend', `<option value="${v.variant_id}" data-cost="${v.purchase_price}" data-sell="${v.selling_price}">${v.brand_name}</option>`);
            });
            
            varSelect.addEventListener('change', function() {
                const selected = this.options[this.selectedIndex];
                document.getElementById(`cost_${rowIdx}`).value = selected.dataset.cost || 0;
                document.getElementById(`sell_${rowIdx}`).value = selected.dataset.sell || 0;
                window.calcTotals();
            });
        }
    } catch(e) { console.error(e); }
};

// 5. Automatic Calculations
window.calcTotals = function() {
    let totalQty = 0, totalCost = 0, totalRev = 0, items = 0;
    
    document.querySelectorAll('input[name="quantity[]"]').forEach((input, i) => {
        let q = parseFloat(input.value) || 0;
        let c = parseFloat(document.querySelectorAll('input[name="unit_cost[]"]')[i].value) || 0;
        let s = parseFloat(document.querySelectorAll('input[name="selling_price[]"]')[i].value) || 0;
        
        if (q > 0) {
            items++;
            totalQty += q;
            totalCost += (q * c);
            totalRev += (q * s);
        }
    });

    document.getElementById('summary_items').textContent = items;
    document.getElementById('summary_qty').textContent = totalQty.toLocaleString();
    document.getElementById('summary_cost').textContent = totalCost.toLocaleString(undefined, {minimumFractionDigits: 2});
    document.getElementById('summary_revenue').textContent = totalRev.toLocaleString(undefined, {minimumFractionDigits: 2});
};

// 6. Form Submission
if (!window.allocFormInit) {
    document.addEventListener('submit', async function (e) {
        if (e.target && e.target.id === 'openingAllocationForm') {
            e.preventDefault();
            const form = e.target;
            const btn = document.getElementById('btnPostAllocation');
            const msg = document.getElementById('allocationResponseMessage');
            
            if (!form.checkValidity()) { form.classList.add('was-validated'); return; }

            btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Committing...';
            msg.className = 'alert d-none shadow-sm mb-4 border-0'; 
            
            try {
                const res = await fetch('../../dripend/systemSetup/inventory/processOpeningAllocation.php', { method: 'POST', body: new FormData(form) });
                const json = JSON.parse(await res.text());

                if (json.status === 'success') {
                    msg.classList.add('alert-success', 'bg-success', 'text-white');
                    msg.classList.remove('d-none');
                    msg.innerHTML = `<i class="fa-solid fa-check-circle me-2 fs-4 align-middle"></i> <span>${json.message}</span>`;
                    form.reset(); window.calcTotals();
                    document.getElementById('allocationItemsBody').innerHTML = ''; window.addAllocationRow();
                } else throw new Error(json.message);
            } catch (err) {
                msg.classList.add('alert-danger', 'bg-danger', 'text-white');
                msg.classList.remove('d-none');
                msg.innerHTML = `<i class="fa-solid fa-triangle-exclamation me-2 fs-5"></i> <strong>Ledger Fault:</strong> ${err.message}`;
            } finally {
                btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-check-double me-2"></i> Post Opening Allocation';
            }
        }
    });
    window.allocFormInit = true;
}

window.fetchLocations();
window.preloadProducts();