/**
 * RiMax Systems Engineering Product Core UI Data Interactivity Engine
 * (Fixed for SPA Lifecycle, Absolute Routing, & Secure Button Triggers)
 */

window.showAppResponse = function(title, msg, type = 'success') {
    if ($('#appResponseModal').length === 0) return;
    if(type === 'success') {
        $('#appResIcon').attr('class', 'fa-solid fa-circle-check text-success fa-4x mb-3');
        $('#appResBtn').attr('class', 'btn btn-success fw-bold px-4 mt-2');
    } else {
        $('#appResIcon').attr('class', 'fa-solid fa-triangle-exclamation text-danger fa-4x mb-3');
        $('#appResBtn').attr('class', 'btn btn-dark fw-bold px-4 mt-2');
    }
    $('#appResTitle').text(title);
    $('#appResMsg').text(msg);
    $('#appResponseModal').modal('show');
};

window.appConfirm = function(title, msg, callback) {
    if ($('#appConfirmModal').length === 0) return;
    $('#appConfTitle').text(title);
    $('#appConfMsg').text(msg);
    $('#appConfirmModal').modal('show');
    $('#btnAppConfirm').off('click').on('click', function() {
        $('#appConfirmModal').modal('hide');
        if (typeof callback === 'function') callback();
    });
};

window.initListProducts = function() {
    setTimeout(() => {
        if (document.getElementById('catalog_grid_container')) window.fetchMasterCatalogGrid();
    }, 50);
};

if (document.getElementById('catalog_grid_container')) window.initListProducts();

window.fetchMasterCatalogGrid = async function() {
    const tableBody = document.getElementById('catalog_grid_container');
    if (!tableBody) return;

    try {
        tableBody.innerHTML = `<tr><td colspan="9" class="text-center py-5"><div class="spinner-border text-primary" role="status"></div><p class="text-muted mt-2 small fw-bold">Compiling dynamic commercial pricing records...</p></td></tr>`;

        const endpoint = '../../dripend/systemSetup/product/fetchListProduct.php';
        const response = await fetch(endpoint);
        const text = await response.text(); 
        
        let payload;
        try { payload = JSON.parse(text); } catch (e) { throw new Error(`Server Error: <br><code>${text.substring(0, 150)}...</code>`); }
        if (payload.status !== 'success') throw new Error(payload.message);

        document.getElementById('kpi_total_items').textContent = Number(payload.kpis.total).toLocaleString();
        document.getElementById('kpi_active_items').textContent = Number(payload.kpis.active).toLocaleString();
        document.getElementById('kpi_nhis_profiles').textContent = Number(payload.kpis.nhis).toLocaleString();
        document.getElementById('kpi_brand_variants').textContent = Number(payload.kpis.brands).toLocaleString();

        if (payload.data.length === 0) {
            tableBody.innerHTML = `<tr><td colspan="9" class="text-center py-5 text-muted"><i class="fa-solid fa-box-open d-block fs-1 mb-3 text-secondary"></i>No operational records exist.</td></tr>`;
            return;
        }

        tableBody.innerHTML = '';
        let rowCounter = 1;

        payload.data.forEach(item => {
            let productTitle = `<strong style="font-size:15px;">${item.generic_name}</strong>`;
            if (item.strength_value) productTitle += ` <span class="text-primary">${item.strength_value}${item.strength_unit || ''}</span>`;
            if (item.formulation_name) productTitle += ` <span class="text-muted">(${item.formulation_name})</span>`;

            let brandPricingBlock = `<span class="text-muted small fst-italic"><i class="fa-solid fa-circle-info me-1"></i>Pure Generic Base</span>`;
            if (item.brands && item.brands.length > 0) {
                brandPricingBlock = item.brands.map(b => `
                    <div class="mb-1 border-bottom pb-1 last-mb-0">
                        <span class="fw-bold text-dark d-block">${b.brand_name}</span>
                        <small class="text-muted text-nowrap">Cost: </small><span class="text-secondary font-monospace fw-bold">GH₵ ${b.purchase_price.toFixed(2)}</span> | 
                        <small class="text-muted text-nowrap">Sell: </small><span class="text-success font-monospace fw-bold">GH₵ ${b.selling_price.toFixed(2)}</span>
                    </div>
                `).join('');
            }

            const statusBadge = item.is_active === 1 
                ? `<span class="badge bg-success-subtle text-success border border-success px-2 py-1 rounded-pill"><i class="fa-solid fa-check me-1"></i>Active</span>`
                : `<span class="badge bg-danger-subtle text-danger border border-danger px-2 py-1 rounded-pill"><i class="fa-solid fa-xmark me-1"></i>Suspended</span>`;

            const primaryRowHTML = `
                <tr class="expand-row" onclick="window.toggleNestedDrawer(${item.product_id})">
                    <td class="text-center text-primary fw-bold">
                        <i id="toggle_arrow_${item.product_id}" class="fa-solid fa-chevron-right transition-all"></i>
                    </td>
                    <td class="text-center font-monospace fw-bold text-secondary bg-light-subtle">${rowCounter++}</td>
                    <td class="fw-bold text-secondary">#PRD-${String(item.product_id).padStart(5, '0')}</td>
                    <td>
                        <div class="text-dark">${productTitle}</div>
                        <small class="text-muted fw-bold d-block mt-1"><i class="fa-solid fa-folder-tree me-1"></i>${item.category_name || 'Uncategorized'}</small>
                    </td>
                    <td>${brandPricingBlock}</td>
                    <td>
                        <div class="font-monospace text-dark fw-bold">GH₵ ${item.gdrg_tariff.toFixed(2)}</div>
                        <small class="text-muted d-block" style="font-size:0.72rem;">Code: ${item.nhis_drug_code || 'N/A'}</small>
                    </td>
                    <td>
                        ${item.is_copay_required === 1 
                            ? `<span class="text-danger font-monospace fw-bold">GH₵ ${item.copay_amount.toFixed(2)}</span>` 
                            : `<span class="badge bg-light text-muted border small">No Copay</span>`}
                    </td>
                    <td class="text-center">${statusBadge}</td>
                    <td class="text-center" onclick="event.stopPropagation();">
                        <div class="d-flex align-items-center justify-content-center gap-2">
                            <!-- SPA Route to Update Product (FIXED: NOW USES BUTTON) -->
                            <button onclick="window.loadContent('Update Product', 'product/updateProduct.php?id=${item.product_id}', 'Pharmacy', 'pharmacy', null, true)" class="btn btn-sm btn-light border text-warning shadow-sm rounded-circle px-2" title="Edit Catalog Properties">
                                <i class="fa-solid fa-pen-to-square"></i>
                            </button>
                            <button onclick="window.executeStatusToggle(${item.product_id}, ${item.is_active})" class="btn btn-sm btn-light border ${item.is_active === 1 ? 'text-success' : 'text-muted'} shadow-sm rounded-circle px-2" title="Toggle Channel Access">
                                <i class="fa-solid ${item.is_active === 1 ? 'fa-toggle-on' : 'fa-toggle-off'}"></i>
                            </button>
                            <button onclick="window.executePurgeRequest(${item.product_id})" class="btn btn-sm btn-light border text-danger shadow-sm rounded-circle px-2" title="Purge Record">
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                
                <tr id="drawer_${item.product_id}" class="d-none detail-drawer bg-light-subtle">
                    <td colspan="9" class="p-4 border-top-0">
                        <div class="row g-4">
                            <div class="col-md-7 border-end">
                                <h6 class="fw-bold text-primary mb-3"><i class="fa-solid fa-tags me-2"></i>Granular Brand Inventory Architecture</h6>
                                ${window.renderBrandVariantSubTable(item.brands, item.base_uom)}
                            </div>
                            <div class="col-md-5">
                                <h6 class="fw-bold text-warning mb-3"><i class="fa-solid fa-shield-halved me-2"></i>Multi-Insurance Carrier Mappings</h6>
                                ${window.renderCorporateInsuranceMatrix(item.corporate_tariffs)}
                            </div>
                        </div>
                    </td>
                </tr>
            `;
            tableBody.insertAdjacentHTML('beforeend', primaryRowHTML);
        });

    } catch (err) {
        tableBody.innerHTML = `<tr><td colspan="9" class="text-center py-4 text-danger fw-bold"><div class="bg-danger-subtle border border-danger rounded p-3 d-inline-block text-start"><i class="fa-solid fa-triangle-exclamation fs-4 mb-2 text-danger"></i><br><strong>Data Retrieval Interrupted:</strong><br>${err.message}</div></td></tr>`;
    }
};

window.renderBrandVariantSubTable = function(brands, uom) {
    if (!brands || brands.length === 0) return `<p class="text-muted small py-2"><i class="fa-solid fa-circle-nodes me-2"></i>No commercial item variant layers provisioned.</p>`;
    return `
        <table class="table table-sm table-bordered bg-white shadow-sm m-0 rounded-3 overflow-hidden">
            <thead class="table-light small text-secondary">
                <tr><th class="py-2 px-3">Brand Variant</th><th class="py-2 px-3">Manufacturer</th><th class="py-2 px-3 text-center">Pack Size</th><th class="py-2 px-3 text-center">UOM</th><th class="py-2 px-3">Barcode</th></tr>
            </thead>
            <tbody class="small align-middle">
                ${brands.map(b => `<tr><td class="fw-bold text-dark px-3">${b.brand_name}</td><td class="px-3">${b.manufacturer_name}</td><td class="text-center fw-bold text-primary px-3">${b.pack_size}</td><td class="text-center px-3"><span class="badge bg-light text-secondary border">${uom}</span></td><td class="font-monospace text-muted px-3">${b.barcode || '--'}</td></tr>`).join('')}
            </tbody>
        </table>`;
};

window.renderCorporateInsuranceMatrix = function(tariffs) {
    if (!tariffs || tariffs.length === 0) return `<p class="text-muted small py-2"><i class="fa-solid fa-info-circle me-2"></i>No secondary corporate insurance provider rules configured.</p>`;
    return `
        <table class="table table-sm table-bordered bg-white shadow-sm m-0 rounded-3 overflow-hidden">
            <thead class="table-light small text-secondary">
                <tr><th class="py-2 px-3">Insurance Provider</th><th class="py-2 px-3">Agreed Tariff</th><th class="py-2 px-3 text-center">Co-Pay Rule</th><th class="py-2 px-3">Patient Liability</th></tr>
            </thead>
            <tbody class="small align-middle">
                ${tariffs.map(t => `<tr><td class="fw-bold text-dark px-3">${t.provider}</td><td class="font-monospace fw-bold text-success px-3">GH₵ ${t.tariff.toFixed(2)}</td><td class="text-center px-3">${t.copay_req === 1 ? '<span class="badge bg-danger-subtle text-danger border border-danger">Required</span>' : '<span class="badge bg-light text-muted border">None</span>'}</td><td class="font-monospace text-danger fw-bold px-3">${t.copay_req === 1 ? 'GH₵ ' + t.copay_amt.toFixed(2) : 'GH₵ 0.00'}</td></tr>`).join('')}
            </tbody>
        </table>`;
};

window.toggleNestedDrawer = function(productId) {
    const target = document.getElementById(`drawer_${productId}`);
    const arrow = document.getElementById(`toggle_arrow_${productId}`);
    if (!target) return;
    if (target.classList.contains('d-none')) {
        target.classList.remove('d-none');
        if (arrow) arrow.style.transform = 'rotate(90deg)';
    } else {
        target.classList.add('d-none');
        if (arrow) arrow.style.transform = 'rotate(0deg)';
    }
};

window.executeStatusToggle = async function(productId, currentStatus) {
    const nextState = currentStatus === 1 ? 0 : 1;
    appConfirm("Toggle Active Status", "Commit catalog distribution routing state adjustment?", async function() {
        try {
            const res = await fetch('../../dripend/systemSetup/product/processUpdateProduct.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=toggle_status&id=${productId}&is_active=${nextState}`
            });
            const data = await res.json();
            if (data.status === 'success') {
                showAppResponse("Updated", "Product status modified successfully.", "success");
                window.fetchMasterCatalogGrid();
            } else {
                showAppResponse("Error", data.message, "error");
            }
        } catch(e) { showAppResponse("Network Error", "Failed to communicate with server.", "error"); }
    });
};

window.executePurgeRequest = async function(productId) {
    appConfirm("Purge Product Record", "CRITICAL WARNING: This will permanently purge the master catalog asset definition and down-stream tracking layers. Proceed?", async function() {
        try {
            const res = await fetch('../../dripend/systemSetup/product/processUpdateProduct.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=delete&id=${productId}`
            });
            const data = await res.json();
            if (data.status === 'success') {
                showAppResponse("Purged", "Product record has been successfully deleted.", "success");
                window.fetchMasterCatalogGrid();
            } else {
                showAppResponse("Failed", data.message, "error");
            }
        } catch(e) { showAppResponse("Network Error", "Failed to communicate with server.", "error"); }
    });
};