/**
 * RiMax Systems Engineering Product Core UI Data Interactivity Engine
 * UPDATE / EDIT CONTROLLER
 */

window.initUpdateProduct = async function(productId) {
    if(!productId || productId <= 0) {
        document.getElementById('responseMessage').classList.remove('d-none');
        document.getElementById('responseMessage').classList.add('alert-danger');
        document.getElementById('responseMessage').innerHTML = '<strong>Error:</strong> Invalid Product Reference.';
        return;
    }

    try {
        const res = await fetch('../../dripend/systemSetup/product/processUpdateProduct.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=fetch_single&id=${productId}`
        });
        const data = await res.json();
        
        if (data.status !== 'success') throw new Error(data.message);

        // Populate Clinical Base
        const p = data.product;
        $('#upd_product_type_id').val(p.product_type_id);
        $('#upd_category_id').val(p.category_id);
        $('#upd_generic_name').val(p.generic_name);
        
        $('#upd_therapeutic_class_id').val(p.therapeutic_class_id);
        $('#upd_formulation_id').val(p.formulation_id);
        $('#upd_strength_value').val(p.strength_value);
        $('#upd_strength_unit_id').val(p.strength_unit_id);
        $('#upd_base_uom_id').val(p.base_uom_id);
        $('#upd_master_cash_price').val(p.cash_price);

        toggleCategoryFieldsUpd();
        syncPricingUnitUpd();

        // Populate NHIS Rules
        if (p.nhis_drug_code !== null || p.gdrg_tariff > 0) {
            $('#upd_nhis_cov_main').prop('checked', true);
            toggleNhisBlockUpd();
            $('#upd_nhis_drug_code').val(p.nhis_drug_code);
            $('#upd_prescribing_level').val(p.prescribing_level);
            $('#upd_gdrg_tariff').val(p.gdrg_tariff);
            
            if (p.is_copay_required == 1) {
                $('#upd_nhis_copay_chk').prop('checked', true);
                toggleNhisCopayUpd();
                $('#upd_nhis_copay_amt').val(p.copay_amount);
            }
        } else {
            toggleNhisBlockUpd();
        }

        // Populate Brands
        if (data.brands && data.brands.length > 0) {
            data.brands.forEach(b => {
                addBrandRowUpd(b.brand_id, b.manufacturer_id, b.barcode, b.pack_size, b.purchase_price, b.selling_price);
            });
        } else {
            addBrandRowUpd();
        }

        // Populate Corporate Matrix
        if (data.tariffs && data.tariffs.length > 0) {
            $('#upd_corp_cov_main').prop('checked', true);
            toggleCorpBlockUpd();

            data.tariffs.forEach(t => {
                const id = t.insurance_type_id;
                $(`#upd_map_${id}`).prop('checked', true);
                toggleCorpRowUpd(id);
                $(`#upd_tar_${id}`).val(t.tariff_amount);
                
                if (t.is_copay_required == 1) {
                    $(`#upd_req_${id}`).prop('checked', true);
                    toggleCorpCopayUpd(id);
                    $(`#upd_amt_${id}`).val(t.copay_amount_adult);
                }
            });
        } else {
            toggleCorpBlockUpd();
        }

    } catch(e) {
        document.getElementById('responseMessage').classList.remove('d-none');
        document.getElementById('responseMessage').classList.add('alert-danger');
        document.getElementById('responseMessage').innerHTML = `<strong>Data Error:</strong> ${e.message}`;
    }
};

function toggleCategoryFieldsUpd() {
    const catSel = document.getElementById('upd_category_id');
    const drugBlock = document.getElementById('upd_drug_fields_block');
    const formSel = document.getElementById('upd_formulation_id');
    
    if (!catSel) return;
    const isDrug = catSel.options[catSel.selectedIndex].getAttribute('data-is-drug') === 'true';

    if (isDrug) {
        drugBlock.style.display = 'flex';
        if (formSel) formSel.required = true;
    } else { 
        drugBlock.style.display = 'none';
        if (formSel) formSel.required = false;
    }
}

function syncPricingUnitUpd() {
    const sel = document.getElementById('upd_base_uom_id');
    const hiddenInput = document.getElementById('upd_unit_of_pricing_hidden');
    if(!sel || sel.selectedIndex === -1 || !hiddenInput) return;
    hiddenInput.value = sel.options[sel.selectedIndex].getAttribute('data-name') || '';
}

function addBrandRowUpd(b_id='', m_id='', barcode='', pack=1, cost='0.00', sell='') {
    const tbody = document.getElementById('upd_brandTableBody');
    if (!tbody) return;

    let bOptions = document.getElementById('tmpl-brands').innerHTML;
    let mOptions = document.getElementById('tmpl-manufacturers').innerHTML;
    
    if (b_id) bOptions = bOptions.replace(`value="${b_id}"`, `value="${b_id}" selected`);
    if (m_id) mOptions = mOptions.replace(`value="${m_id}"`, `value="${m_id}" selected`);

    sell = sell || document.getElementById('upd_master_cash_price')?.value || '0.00';

    const tr = document.createElement('tr');
    tr.innerHTML = `
        <td><select name="brand_id_arr[]" class="form-select form-select-sm border-success fw-bold" required>${bOptions}</select></td>
        <td><select name="manufacturer_id_arr[]" class="form-select form-select-sm" required>${mOptions}</select></td>
        <td><input type="text" name="barcode_arr[]" class="form-control form-control-sm" value="${barcode || ''}" placeholder="Scan Code"></td>
        <td><input type="number" name="pack_size_arr[]" min="1" class="form-control form-control-sm" value="${pack}" required></td>
        <td><input type="number" name="cost_price_arr[]" step="0.01" class="form-control form-control-sm" value="${cost}"></td>
        <td><input type="number" name="selling_price_arr[]" step="0.01" class="form-control form-control-sm text-success fw-bold" value="${sell}" required></td>
        <td class="text-center"><button type="button" class="btn btn-sm btn-light border text-danger shadow-sm rounded-circle px-2" onclick="this.closest('tr').remove()"><i class="fa-solid fa-trash"></i></button></td>
    `;
    tbody.appendChild(tr);
}

function toggleNhisBlockUpd() {
    const mainCheckbox = document.getElementById('upd_nhis_cov_main');
    const isCovered = mainCheckbox.checked;
    
    $('.upd-nhis-input').prop('disabled', !isCovered);
    if(!isCovered) {
        $('.upd-nhis-input').not(':checkbox').val('');
        $('#upd_nhis_copay_chk').prop('checked', false);
    }
    toggleNhisCopayUpd();
}

function toggleNhisCopayUpd() {
    const chk = document.getElementById('upd_nhis_copay_chk');
    const amt = document.getElementById('upd_nhis_copay_amt');
    if(chk && amt) {
        amt.disabled = !chk.checked; 
        if(!chk.checked) amt.value = '';
    }
}

function toggleCorpBlockUpd() {
    const isCovered = document.getElementById('upd_corp_cov_main').checked;
    
    $('.upd-corp-master-chk').prop('disabled', !isCovered);
    if(!isCovered) {
        $('.upd-corp-master-chk').prop('checked', false).trigger('change');
    }
}

function toggleCorpRowUpd(id) {
    const isMapped = $(`#upd_map_${id}`).prop('checked');
    $(`#upd_tar_${id}, #upd_req_${id}`).prop('disabled', !isMapped);
    if (!isMapped) {
        $(`#upd_tar_${id}`).val('');
        $(`#upd_req_${id}`).prop('checked', false).trigger('change');
    }
}

function toggleCorpCopayUpd(id) {
    const isReq = $(`#upd_req_${id}`).prop('checked');
    $(`#upd_amt_${id}`).prop('disabled', !isReq);
    if (!isReq) $(`#upd_amt_${id}`).val('');
}

// FORM SUBMIT HANDLER
$(document).off('submit', '#enterpriseProductUpdateForm').on('submit', '#enterpriseProductUpdateForm', async function (e) {
    e.preventDefault();
    const productForm = e.target;
    const submitBtn = document.getElementById('btnUpdateForm');
    const feedbackBox = document.getElementById('responseMessage');
    
    if (!productForm.checkValidity()) {
        productForm.classList.add('was-validated');
        return;
    }

    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Deploying Updates...';
    feedbackBox.className = 'alert d-none shadow-sm mb-4 border-0'; 
    
    try {
        const formData = new FormData(productForm);
        formData.append('action', 'update');

        const response = await fetch('../../dripend/systemSetup/product/processUpdateProduct.php', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) throw new Error(`HTTP Error: ${response.status}`);
        const result = await response.json();

        if (result.status === 'success') {
            feedbackBox.classList.add('alert-success', 'bg-success', 'text-white');
            feedbackBox.classList.remove('d-none');
            feedbackBox.innerHTML = `<i class="fa-solid fa-check-circle me-2 fs-5"></i> ${result.message} Returning to Catalog...`;
            
            setTimeout(() => { window.location.href = "?cat=products&page=product/listProducts.php"; }, 1000);
        } else {
            throw new Error(result.message);
        }
    } catch (error) {
        feedbackBox.classList.add('alert-danger', 'bg-danger', 'text-white');
        feedbackBox.classList.remove('d-none');
        feedbackBox.innerHTML = `<i class="fa-solid fa-triangle-exclamation me-2 fs-5"></i> <strong>Error:</strong> ${error.message}`;
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fa-solid fa-cloud-arrow-up me-2"></i> Save Updates & Distribute';
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
});