window.initStockMovement = function() {
    const apiPath = "/rimax/application/dripend/systemSetup/inventory/fetchStockMovement.php";
    window.MasterLookupData = { stores: [], departments: [] };

    setTodayAsDefault();
    initLookups();

    // Prevent form from placing variables in URL
    const formEl = document.getElementById('movementFilterForm');
    if (formEl) {
        formEl.onsubmit = function(e) {
            e.preventDefault();
            fetchGridData();
        };
    }

    // Dynamic Cascading Selection
    const locTypeSelect = document.getElementById('filter_loc_type');
    if (locTypeSelect) {
        locTypeSelect.addEventListener('change', function() {
            const locType = this.value; // Exact case (Store / Department)
            const locSelect = document.getElementById('filter_location');
            if (!locSelect) return;

            locSelect.innerHTML = '<option value="">-- All Locations --</option>';

            if (locType === 'Store') {
                window.MasterLookupData.stores.forEach(s => {
                    locSelect.insertAdjacentHTML('beforeend', `<option value="${s.id}">${s.name}</option>`);
                });
            } else if (locType === 'Department') {
                window.MasterLookupData.departments.forEach(d => {
                    locSelect.insertAdjacentHTML('beforeend', `<option value="${d.id}">${d.name}</option>`);
                });
            }
        });
    }

    function setTodayAsDefault() {
        const today = new Date().toISOString().split('T')[0];
        const start = document.getElementById('filter_start');
        const end = document.getElementById('filter_end');
        if (start && !start.value) start.value = today;
        if (end && !end.value) end.value = today;
    }

    window.resetFilters = function() {
        if(formEl) formEl.reset();
        setTodayAsDefault();
        const locSelect = document.getElementById('filter_location');
        if(locSelect) locSelect.innerHTML = '<option value="">-- Select Type First --</option>';
        fetchGridData();
    };

    async function initLookups() {
        try {
            const res = await fetch(`${apiPath}?action=get_lookups`);
            const json = await res.json();
            
            if (json.status === 'success') {
                // Populate ENUM transaction types
                const typeSelect = document.getElementById('filter_type');
                if (typeSelect) {
                    typeSelect.innerHTML = '<option value="">-- All Types --</option>';
                    json.types.forEach(t => {
                        typeSelect.insertAdjacentHTML('beforeend', `<option value="${t}">${t}</option>`);
                    });
                }
                // Store DB response
                window.MasterLookupData.stores = json.stores || [];
                window.MasterLookupData.departments = json.departments || [];
                
                fetchGridData();
            }
        } catch (error) { 
            console.error("Lookup Sync Engine Faulted:", error); 
        }
    }

    window.fetchGridData = async function() {
        const tbody = document.getElementById('movementsGridBody');
        if (!tbody) return;

        try {
            const params = new URLSearchParams({
                action: 'get_movements',
                start_date: document.getElementById('filter_start')?.value || '',
                end_date: document.getElementById('filter_end')?.value || '',
                location_type: document.getElementById('filter_loc_type')?.value || '',
                location_id: document.getElementById('filter_location')?.value || '',
                transaction_type: document.getElementById('filter_type')?.value || '',
                search: document.getElementById('filter_search')?.value || ''
            });

            tbody.innerHTML = '<tr><td colspan="9" class="text-center py-5"><div class="spinner-border text-primary spinner-border-sm"></div> Syncing Ledger Data...</td></tr>';

            const res = await fetch(`${apiPath}?${params.toString()}`);
            const textResponse = await res.text();
            
            let payload;
            try {
                payload = JSON.parse(textResponse);
            } catch(e) {
                console.error("Backend Error:", textResponse);
                throw new Error("Server returned corrupt JSON. See console.");
            }

            if (payload.status !== 'success') throw new Error(payload.message);

            const kpiTotal = document.getElementById('kpi_total_tx');
            const kpiIn = document.getElementById('kpi_qty_in');
            const kpiOut = document.getElementById('kpi_qty_out');
            const kpiVal = document.getElementById('kpi_asset_value');
            
            if (kpiTotal) kpiTotal.textContent = payload.kpis.total_tx.toLocaleString();
            if (kpiIn) kpiIn.textContent = payload.kpis.qty_in.toLocaleString();
            if (kpiOut) kpiOut.textContent = payload.kpis.qty_out.toLocaleString();
            if (kpiVal) kpiVal.textContent = parseFloat(payload.kpis.asset_value).toLocaleString(undefined, {minimumFractionDigits:2});

            if (!payload.data || payload.data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" class="text-center py-5 text-muted"><i class="fa-solid fa-ghost fs-2 mb-2 d-block"></i> No ledger movements found matching current filters.</td></tr>';
                return;
            }

            tbody.innerHTML = '';
            
            payload.data.forEach(item => {
                const dateObj = new Date(item.movement_date);
                const dateStr = `${dateObj.getDate().toString().padStart(2, '0')}-${dateObj.toLocaleString('default', {month:'short'})}-${dateObj.getFullYear()} <small class="text-muted d-block">${dateObj.getHours().toString().padStart(2, '0')}:${dateObj.getMinutes().toString().padStart(2, '0')}</small>`;

                let badgeClass = 'bg-secondary';
                let matrixStr = '';

                if (['Receive', 'Opening Allocation', 'Transfer In', 'Receive Goods'].includes(item.transaction_type)) {
                    badgeClass = 'bg-success';
                    matrixStr = `<span class="text-muted"><i class="fa-solid fa-arrow-right text-success"></i> ${item.dest_name || 'System'}</span>`;
                } else if (['Dispense', 'Write-Off', 'Transfer Out'].includes(item.transaction_type)) {
                    badgeClass = 'bg-danger';
                    matrixStr = `<span class="text-muted">${item.source_name || 'System'} <i class="fa-solid fa-arrow-right text-danger"></i></span>`;
                } else {
                    badgeClass = 'bg-info text-dark';
                    matrixStr = `<span class="text-muted">${item.source_name || '?'} <i class="fa-solid fa-arrow-right text-info"></i> ${item.dest_name || '?'}</span>`;
                }

                const brandStr = item.brand_name ? `<br><small class="badge bg-light text-secondary border mt-1">${item.brand_name}</small>` : '';
                const viewUrl = `inventory/stockMovementHistory.php&product_id=${item.product_id}&batch_id=${item.batch_id}`;

                const row = `
                    <tr class="bg-white">
                        <td class="px-3 border-end text-secondary">${dateStr}</td>
                        <td class="font-monospace text-dark fw-bold">${item.reference_id}</td>
                        <td><span class="badge ${badgeClass} text-uppercase px-2 py-1">${item.transaction_type}</span></td>
                        <td><span class="fw-bold text-primary-emphasis">${item.generic_name}</span>${brandStr}</td>
                        <td>
                            <span class="font-monospace fw-bold">${item.batch_number}</span>
                            <small class="d-block text-muted">Exp: ${item.expiry_date}</small>
                        </td>
                        <td class="text-center fw-medium bg-light-subtle">${matrixStr}</td>
                        <td class="text-center fw-bold fs-6">${item.quantity}</td>
                        <td class="text-muted fw-medium"><i class="fa-regular fa-circle-user me-1"></i> ${item.staff_name || 'System'}</td>
                        <td class="text-center">
                            <a href="${viewUrl}" data-title="Product Lifecycle" class="btn btn-sm btn-outline-primary px-3 shadow-sm rounded-pill fw-bold">
                                <i class="fa-solid fa-eye me-1"></i> View
                            </a>
                        </td>
                    </tr>
                `;
                tbody.insertAdjacentHTML('beforeend', row);
            });

        } catch (error) {
            tbody.innerHTML = `<tr><td colspan="9" class="text-center py-4 text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation mb-2 fs-3 d-block"></i> Fetch Interrupted: ${error.message}</td></tr>`;
        }
    };
};

// Emergency fallback trigger
if (!document.querySelector('.main-wrapper')) {
    document.addEventListener("DOMContentLoaded", () => {
        if (typeof window.initStockMovement === 'function') window.initStockMovement();
    });
}