/**
 * RiMax Store Management Engine
 * Completely Relational Database-Responsive Dynamic UI Rendering Lifecycle Handlers
 */

if (!window.storeFormInitialized) {
    document.addEventListener('submit', async function (e) {
        if (e.target && e.target.id === 'storeManagementForm') {
            e.preventDefault();

            const form = e.target;
            const submitBtn = document.getElementById('btnSubmitStore');
            const feedbackBox = document.getElementById('storeResponseMessage');
            
            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                return;
            }

            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Writing Schema Bounds...';
            feedbackBox.className = 'alert d-none shadow-sm mb-4 border-0'; 
            
            try {
                const endpointURL = '/rimax/application/dripend/systemSetup/inventory/processAddStore.php';
                const response = await fetch(endpointURL, {
                    method: 'POST',
                    body: new FormData(form)
                });

                const text = await response.text();
                const result = JSON.parse(text);

                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}`;
                    form.reset();
                    form.classList.remove('was-validated');
                    
                    setTimeout(() => {
                        window.location.href = "?cat=inventory&page=inventory/listStores.php";
                    }, 1300);
                } 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>Operation Terminated:</strong> ${error.message}`;
            } finally {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa-solid fa-hard-drive me-2"></i> Provision Store';
            }
        }
    });
    window.storeFormInitialized = true;
}

// Secure UI execution trigger hooked directly into the SPA view container loop
setTimeout(() => {
    if (document.getElementById('stores_grid_container')) {
        window.fetchStoresGrid();
    }
}, 100);

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

    try {
        tableBody.innerHTML = `<tr><td colspan="5" class="text-center py-5"><div class="spinner-border text-primary" role="status"></div></td></tr>`;

        const endpoint = '/rimax/application/dripend/systemSetup/inventory/fetchStores.php';
        const response = await fetch(endpoint);
        const payload = await response.json();
        
        if (payload.status !== 'success') throw new Error(payload.message);

        // Map live global aggregations straight into UI counters
        document.getElementById('kpi_total_stores').textContent = payload.kpis.total;
        document.getElementById('kpi_active_stores').textContent = payload.kpis.active;
        document.getElementById('kpi_suspended_stores').textContent = payload.kpis.suspended;

        if (payload.data.length === 0) {
            tableBody.innerHTML = `<tr><td colspan="5" class="text-center py-5 text-muted"><i class="fa-solid fa-shop-slash fs-2 mb-2 d-block"></i>No storage systems found matching data dictionary states.</td></tr>`;
            return;
        }

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

        payload.data.forEach(item => {
            // Process badges cleanly based on the data dictionary type code values
            let typeBadgeHTML = `<span class="badge bg-secondary text-uppercase border shadow-sm"><i class="fa-solid fa-box me-1"></i> ${item.type_name}</span>`;
            
            if (item.type_code.toLowerCase() === 'central') {
                typeBadgeHTML = `<span class="badge bg-primary text-uppercase border shadow-sm"><i class="fa-solid fa-warehouse me-1"></i> ${item.type_name}</span>`;
            } else if (item.type_code.toLowerCase() === 'satellite') {
                typeBadgeHTML = `<span class="badge bg-info text-dark text-uppercase border shadow-sm"><i class="fa-solid fa-shop-medical me-1"></i> ${item.type_name}</span>`;
            } else if (item.type_code.toLowerCase() === 'ward') {
                typeBadgeHTML = `<span class="badge bg-warning text-dark text-uppercase border shadow-sm"><i class="fa-solid fa-bed-pulse me-1"></i> ${item.type_name}</span>`;
            } else if (item.type_code.toLowerCase() === 'virtual') {
                typeBadgeHTML = `<span class="badge bg-dark text-uppercase border shadow-sm"><i class="fa-solid fa-shuffle me-1"></i> ${item.type_name}</span>`;
            }

            const lifeCycleBadge = item.is_active === 1 
                ? '<span class="badge bg-success-subtle text-success border border-success px-3 py-2 rounded-pill">Active</span>'
                : '<span class="badge bg-danger-subtle text-danger border border-danger px-3 py-2 rounded-pill">Suspended</span>';

            const computedRow = `
                <tr class="bg-white">
                    <td class="fw-bold px-4 text-muted">${loopCounter++}</td>
                    <td class="fw-bold text-dark">
                        ${item.store_name}
                        <small class="d-block text-muted fw-normal mt-1" style="font-size:0.68rem; letter-spacing:0.5px;">SYSTEM REFERENCE HASH: NODE-${String(item.id).padStart(4, '0')}</small>
                    </td>
                    <td>${typeBadgeHTML}</td>
                    <td class="text-center">${lifeCycleBadge}</td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-light border p-2 text-warning shadow-sm mx-1" title="Modify Node Reference"><i class="fa-solid fa-pen-to-square"></i></button>
                        <button class="btn btn-sm btn-light border p-2 text-danger shadow-sm mx-1" title="Decommission Storage Entity"><i class="fa-solid fa-trash"></i></button>
                    </td>
                </tr>
            `;
            tableBody.insertAdjacentHTML('beforeend', computedRow);
        });

    } catch (err) {
        tableBody.innerHTML = `<tr><td colspan="5" class="text-center py-4 text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation mb-2"></i><br>Data Stream Broken: ${err.message}</td></tr>`;
    }
};