/**
 * Master Catalog Provisioning JS
 * Fully database-responsive UI handlers & SPA Safe.
 */

function toggleCategoryFields() {
    const catSel = document.getElementById('category_id');
    const drugBlock = document.getElementById('drug_fields_block');
    const formSel = document.getElementById('drug_formulation');
    const nameLabel = document.getElementById('name_label');
    const tClassSel = document.getElementById('therapeutic_class');

    if (!catSel || !drugBlock) return;

    const selectedOpt = catSel.options[catSel.selectedIndex];
    const isDrug = selectedOpt ? selectedOpt.getAttribute('data-is-drug') === 'true' : false;

    if (isDrug) {
        drugBlock.style.display = 'flex';
        if (formSel) formSel.required = true;
        if (nameLabel) nameLabel.innerHTML = 'Clinical Generic Name <span class="text-danger">*</span>';
    } else { 
        drugBlock.style.display = 'none';
        if (formSel) { formSel.required = false; formSel.value = ''; }
        if (tClassSel) tClassSel.value = ''; 
        document.getElementById('drug_strength').value = '';
        document.getElementById('strength_unit').value = '';
        if (nameLabel) nameLabel.innerHTML = 'Consumable Item Name <span class="text-danger">*</span>';
    }
}

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

function toggleBrandSection() {
    const status = document.getElementById('has_brands')?.value;
    const container = document.getElementById('brands_container');
    const tbody = document.getElementById('brandTableBody');
    
    if (!container || !tbody) return;
    
    if (status === '1') {
        container.style.display = 'block';
        if(tbody.children.length === 0) addBrandRow();
    } else {
        container.style.display = 'none';
        tbody.innerHTML = ''; 
    }
}

function addBrandRow() {
    const tbody = document.getElementById('brandTableBody');
    if (!tbody) return;

    // Fetch directly from the HTML templates injected by PHP to bypass SPA execution blocks
    const bOptions = document.getElementById('tmpl-brands') ? document.getElementById('tmpl-brands').innerHTML : '<option value="" disabled>Error Loading</option>';
    const mOptions = document.getElementById('tmpl-manufacturers') ? document.getElementById('tmpl-manufacturers').innerHTML : '<option value="" disabled>Error Loading</option>';
    
    const basePrice = document.getElementById('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" placeholder="Scan Code"></td>
        <td><input type="number" name="pack_size_arr[]" min="1" value="1" class="form-control form-control-sm" required></td>
        <td><input type="number" name="cost_price_arr[]" step="0.01" value="0.00" class="form-control form-control-sm"></td>
        <td><input type="number" name="selling_price_arr[]" step="0.01" value="${basePrice}" class="form-control form-control-sm" required></td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-light border text-danger shadow-sm" onclick="this.closest('tr').remove()">
                <i class="fa-solid fa-trash"></i>
            </button>
        </td>
    `;
    tbody.appendChild(tr);
}

// --- NHIS LOGIC ---
function toggleNhisBlock() {
    const mainCheckbox = document.getElementById('nhis_cov_main');
    if (!mainCheckbox) return;

    const isCovered = mainCheckbox.checked;
    ['nhis_drug_code', 'prescribing_level', 'gdrg_tariff', 'nhis_copay_chk'].forEach(id => {
        const el = document.getElementById(id);
        if (el) {
            el.disabled = !isCovered;
            if (!isCovered) {
                if(el.type === 'checkbox') el.checked = false;
                else el.value = '';
            }
        }
    });
    toggleNhisCopay();
}

function toggleNhisCopay() {
    const chk = document.getElementById('nhis_copay_chk');
    const amt = document.getElementById('nhis_copay_amt');
    if(chk && amt) {
        amt.disabled = !chk.checked; 
        if(!chk.checked) amt.value = '';
    }
}

// --- CORPORATE MATRIX LOGIC ---
function toggleCorpBlock() {
    const mainCheckbox = document.getElementById('corp_cov_main');
    if (!mainCheckbox) return;
    const isCovered = mainCheckbox.checked;
    
    document.querySelectorAll('.corp-master-chk').forEach(chk => {
        chk.disabled = !isCovered;
        if(!isCovered) {
            chk.checked = false;
            const rowId = chk.id.split('_')[1];
            if (rowId) toggleCorpRow(rowId); 
        }
    });
}

function toggleCorpRow(id) {
    const mapChk = document.getElementById('map_' + id);
    const tar = document.getElementById('tar_' + id);
    const req = document.getElementById('req_' + id);
    if(mapChk && tar && req) {
        const isMapped = mapChk.checked;
        tar.disabled = !isMapped;
        req.disabled = !isMapped;
        if (!isMapped) { tar.value = ''; req.checked = false; }
        toggleCorpCopay(id);
    }
}

function toggleCorpCopay(id) {
    const req = document.getElementById('req_' + id);
    const amt = document.getElementById('amt_' + id);
    if(req && amt) {
        amt.disabled = !req.checked;
        if (!req.checked) amt.value = '';
    }
}

// --- AJAX FORM SUBMISSION (SPA SAFE DELEGATION) ---
document.addEventListener('submit', async function (e) {
    if (e.target && e.target.id === 'enterpriseProductForm') {
        e.preventDefault();

        const productForm = e.target;
        const submitBtn = document.getElementById('btnSubmitForm');
        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> Compiling...';
        feedbackBox.className = 'alert d-none shadow-sm mb-4 border-0'; 
        
        try {
            const endpointURL = '../../dripend/systemSetup/product/processAddProduct.php';
            const response = await fetch(endpointURL, {
                method: 'POST',
                body: new FormData(productForm)
            });

            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} Redirecting...`;
                
                // REDIRECT TO PRODUCT LIST
                setTimeout(() => {
                    window.location.href = "?cat=products&page=product/listProducts.php";
                }, 1500);

            } 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> Deploy to Master Catalog';
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }
});