@extends('layouts.admin')

@section('title', 'Inventory Report')

@section('page-title', 'Inventory Report')

@section('breadcrumbs')
    <a href="#" class="hover:text-primary">Reports</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">Inventory Report</span>
@endsection

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Tabs -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-6">
        <div class="border-b border-gray-200">
            <nav class="flex -mb-px">
                <button onclick="showTab('inventory')" id="tab-inventory" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-primary text-primary transition-colors">Inventory</button>
                <button onclick="showTab('lowstock')" id="tab-lowstock" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-primary transition-colors">Low Stock</button>
                <button onclick="showTab('outofstock')" id="tab-outofstock" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-primary transition-colors">Out of Stock</button>
            </nav>
        </div>
    </div>

    <!-- Inventory Tab Content -->
    <div id="content-inventory" class="tab-content">
        <!-- Stats -->
        <div class="grid grid-cols-1 sm:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <p class="text-sm text-gray-500">Total Products</p>
                <p class="text-2xl font-bold text-gray-900 mt-1" data-stat="total-products">{{ $totalProducts ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <p class="text-sm text-gray-500">Total Value</p>
                <p class="text-2xl font-bold text-green-600 mt-1" data-stat="total-value">{{ number_format($totalValue ?? 0, 2) }}</p>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <p class="text-sm text-gray-500">Low Stock Items</p>
                <p class="text-2xl font-bold text-yellow-600 mt-1" data-stat="low-stock">{{ $lowStockCount ?? 0 }}</p>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <p class="text-sm text-gray-500">Out of Stock</p>
                <p class="text-2xl font-bold text-red-600 mt-1" data-stat="out-of-stock">{{ $outOfStockCount ?? 0 }}</p>
            </div>
        </div>

        <!-- Filter and Export -->
        <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
            <div class="flex flex-wrap gap-3">
                <input type="text" id="inventory-search" placeholder="Search products..." class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                <select id="inventory-status" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                    <option value="all">All Status</option>
                    <option value="in_stock">In Stock</option>
                    <option value="low_stock">Low Stock</option>
                    <option value="out_of_stock">Out of Stock</option>
                </select>
                <button onclick="applyInventoryFilters()" class="px-4 h-10 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium">Filter</button>
                <button onclick="clearInventoryFilters()" class="px-4 h-10 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors text-sm font-medium">Clear</button>
            </div>
            <div class="flex gap-2">
                <button onclick="exportInventoryCsv()" class="flex items-center gap-2 px-4 h-10 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm font-medium">
                    <span class="material-symbols-outlined text-lg">description</span>
                    Export CSV
                </button>
                <button onclick="exportInventoryPdf()" class="flex items-center gap-2 px-4 h-10 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm font-medium">
                    <span class="material-symbols-outlined text-lg">picture_as_pdf</span>
                    Export PDF
                </button>
            </div>
        </div>

        <!-- Table -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Product</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Category</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Stock</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Unit Price</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Total Value</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Status</th>
                        </tr>
                    </thead>
                    <tbody id="inventory-tbody" class="divide-y divide-gray-100">
                        <tr>
                            <td colspan="7" class="py-12 px-6 text-center text-gray-500">
                                <div class="flex flex-col items-center">
                                    <svg class="animate-spin h-8 w-8 text-primary mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                    </svg>
                                    <p>Loading inventory data...</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Low Stock Tab Content (same API as Inventory, status=low_stock) -->
    <div id="content-lowstock" class="tab-content hidden">
        <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
            <div class="flex flex-wrap gap-3">
                <input type="text" id="lowstock-search" placeholder="Search products…" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary min-w-[12rem]">
                <button type="button" onclick="applyLowStockFilters()" class="px-4 h-10 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium">Filter</button>
                <button type="button" onclick="clearLowStockFilters()" class="px-4 h-10 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors text-sm font-medium">Clear</button>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Product</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Current Stock</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Alert Level</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Unit Price</th>
                        </tr>
                    </thead>
                    <tbody id="lowstock-tbody" class="divide-y divide-gray-100">
                        <tr>
                            <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">warning</span>
                                <p>Open this tab to load low-stock items.</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Out of Stock Tab Content (API status=out_of_stock) -->
    <div id="content-outofstock" class="tab-content hidden">
        <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
            <div class="flex flex-wrap gap-3">
                <input type="text" id="outofstock-search" placeholder="Search products…" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary min-w-[12rem]">
                <button type="button" onclick="applyOutOfStockFilters()" class="px-4 h-10 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium">Filter</button>
                <button type="button" onclick="clearOutOfStockFilters()" class="px-4 h-10 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors text-sm font-medium">Clear</button>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Product</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Category</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Last Stock Date</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Unit Price</th>
                        </tr>
                    </thead>
                    <tbody id="outofstock-tbody" class="divide-y divide-gray-100">
                        <tr>
                            <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">remove_shopping_cart</span>
                                <p>Open this tab to load out-of-stock items.</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    let inventoryFilters = {
        search: '',
        status: 'all'
    };

    let lowStockFilters = { search: '' };
    let outOfStockFilters = { search: '' };

    let inventorySearchTimeout;
    let lowStockSearchTimeout;
    let outOfStockSearchTimeout;

    function showTab(tabName) {
        document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
        document.querySelectorAll('.tab-btn').forEach(el => {
            el.classList.remove('border-primary', 'text-primary');
            el.classList.add('border-transparent', 'text-gray-500');
        });
        document.getElementById('content-' + tabName).classList.remove('hidden');
        const activeTab = document.getElementById('tab-' + tabName);
        activeTab.classList.remove('border-transparent', 'text-gray-500');
        activeTab.classList.add('border-primary', 'text-primary');
        
        if (tabName === 'inventory') {
            loadInventoryData();
        }
        if (tabName === 'lowstock') {
            loadLowStockData();
        }
        if (tabName === 'outofstock') {
            loadOutOfStockData();
        }
    }

    function applyInventoryFilters() {
        inventoryFilters.search = document.getElementById('inventory-search').value.trim();
        inventoryFilters.status = document.getElementById('inventory-status').value;
        loadInventoryData();
    }

    function clearInventoryFilters() {
        document.getElementById('inventory-search').value = '';
        document.getElementById('inventory-status').value = 'all';
        applyInventoryFilters();
    }

    function loadInventoryData() {
        const tbody = document.getElementById('inventory-tbody');
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="py-12 px-6 text-center text-gray-500">
                    <div class="flex flex-col items-center">
                        <svg class="animate-spin h-8 w-8 text-primary mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <p>Loading inventory data...</p>
                    </div>
                </td>
            </tr>
        `;

        const params = new URLSearchParams({
            search: inventoryFilters.search,
            status: inventoryFilters.status
        });

        fetch('{{ route("admin.reports.inventory.api") }}?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInventoryData(data.data);
                updateInventoryStats(data.stats);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            tbody.innerHTML = '<tr><td colspan="7" class="py-12 px-6 text-center text-red-500">Error loading inventory data</td></tr>';
        });
    }

    function renderInventoryData(products) {
        const tbody = document.getElementById('inventory-tbody');
        if (products.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" class="py-12 px-6 text-center text-gray-500"><span class="material-symbols-outlined text-4xl mb-2 block">inventory_2</span><p>No inventory data available</p></td></tr>';
            return;
        }

        let html = '';
        products.forEach((product, index) => {
            const statusClass = getStatusClass(product.status);
            html += `
                <tr class="hover:bg-gray-50/50 transition-colors">
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${index + 1}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">
                        <div class="font-medium">${product.name}</div>
                        ${product.code !== 'N/A' ? `<div class="text-xs text-gray-500">${product.code}</div>` : ''}
                    </td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${product.category}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${product.stock}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white text-right tabular-nums">${product.unit_price}</td>
                    <td class="py-4 px-6 text-sm font-medium text-gray-900 bg-white text-right tabular-nums">${product.total_value}</td>
                    <td class="py-4 px-6 bg-white">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusClass} border">
                            ${product.status_label}
                        </span>
                    </td>
                </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function getStatusClass(status) {
        const classes = {
            'in_stock': 'bg-green-50 text-green-700 border-green-100',
            'low_stock': 'bg-yellow-50 text-yellow-700 border-yellow-100',
            'out_of_stock': 'bg-red-50 text-red-700 border-red-100'
        };
        return classes[status] || classes['in_stock'];
    }

    function updateInventoryStats(stats) {
        document.querySelector('[data-stat="total-products"]').textContent = stats.totalProducts || 0;
        document.querySelector('[data-stat="total-value"]').textContent = parseFloat(stats.totalValue || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        document.querySelector('[data-stat="low-stock"]').textContent = stats.lowStockCount || 0;
        document.querySelector('[data-stat="out-of-stock"]').textContent = stats.outOfStockCount || 0;
    }

    function applyLowStockFilters() {
        lowStockFilters.search = document.getElementById('lowstock-search').value.trim();
        loadLowStockData();
    }

    function clearLowStockFilters() {
        document.getElementById('lowstock-search').value = '';
        lowStockFilters.search = '';
        loadLowStockData();
    }

    function loadLowStockData() {
        const tbody = document.getElementById('lowstock-tbody');
        if (!tbody) return;
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                    <div class="flex flex-col items-center">
                        <svg class="animate-spin h-8 w-8 text-primary mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <p>Loading low stock…</p>
                    </div>
                </td>
            </tr>
        `;

        const params = new URLSearchParams({
            search: lowStockFilters.search,
            status: 'low_stock'
        });

        fetch('{{ route("admin.reports.inventory.api") }}?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderLowStockData(data.data);
                if (data.stats) {
                    updateInventoryStats(data.stats);
                }
            } else {
                showLowStockError('Could not load low stock data.');
            }
        })
        .catch(error => {
            console.error('Low stock error:', error);
            showLowStockError('Could not load low stock data.');
        });
    }

    function renderLowStockData(products) {
        const tbody = document.getElementById('lowstock-tbody');
        if (!tbody) return;

        if (!products || products.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                        <span class="material-symbols-outlined text-4xl mb-2 block">warning</span>
                        <p>No low stock items</p>
                        <p class="text-sm text-gray-400 mt-2">Products appear here when stock is above zero but at or below the alert level.</p>
                    </td>
                </tr>
            `;
            return;
        }

        let html = '';
        products.forEach((product, index) => {
            html += `
                <tr class="hover:bg-gray-50/50 transition-colors">
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${index + 1}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">
                        <div class="font-medium">${product.name}</div>
                        ${product.code && product.code !== 'N/A' ? `<div class="text-xs text-gray-500">${product.code}</div>` : ''}
                    </td>
                    <td class="py-4 px-6 text-sm font-semibold text-amber-800 bg-white tabular-nums">${product.stock}</td>
                    <td class="py-4 px-6 text-sm text-gray-700 bg-white tabular-nums">${product.alert_quantity}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white text-right tabular-nums">${product.unit_price}</td>
                </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function showLowStockError(message) {
        const tbody = document.getElementById('lowstock-tbody');
        if (!tbody) return;
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="py-12 px-6 text-center text-red-500">
                    <span class="material-symbols-outlined text-4xl mb-2 block">error</span>
                    <p>${message}</p>
                </td>
            </tr>
        `;
    }

    function applyOutOfStockFilters() {
        outOfStockFilters.search = document.getElementById('outofstock-search').value.trim();
        loadOutOfStockData();
    }

    function clearOutOfStockFilters() {
        document.getElementById('outofstock-search').value = '';
        outOfStockFilters.search = '';
        loadOutOfStockData();
    }

    function loadOutOfStockData() {
        const tbody = document.getElementById('outofstock-tbody');
        if (!tbody) return;
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                    <div class="flex flex-col items-center">
                        <svg class="animate-spin h-8 w-8 text-primary mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <p>Loading out of stock…</p>
                    </div>
                </td>
            </tr>
        `;

        const params = new URLSearchParams({
            search: outOfStockFilters.search,
            status: 'out_of_stock'
        });

        fetch('{{ route("admin.reports.inventory.api") }}?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderOutOfStockData(data.data);
                if (data.stats) {
                    updateInventoryStats(data.stats);
                }
            } else {
                showOutOfStockError('Could not load out-of-stock data.');
            }
        })
        .catch(error => {
            console.error('Out of stock error:', error);
            showOutOfStockError('Could not load out-of-stock data.');
        });
    }

    function renderOutOfStockData(products) {
        const tbody = document.getElementById('outofstock-tbody');
        if (!tbody) return;

        if (!products || products.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="py-12 px-6 text-center text-gray-500">
                        <span class="material-symbols-outlined text-4xl mb-2 block">remove_shopping_cart</span>
                        <p>No out of stock items</p>
                        <p class="text-sm text-gray-400 mt-2">Products with zero stock appear here.</p>
                    </td>
                </tr>
            `;
            return;
        }

        let html = '';
        products.forEach((product, index) => {
            const lastDate = product.last_stock_date || '—';
            html += `
                <tr class="hover:bg-gray-50/50 transition-colors">
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${index + 1}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">
                        <div class="font-medium">${product.name}</div>
                        ${product.code && product.code !== 'N/A' ? `<div class="text-xs text-gray-500">${product.code}</div>` : ''}
                    </td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${product.category}</td>
                    <td class="py-4 px-6 text-sm text-gray-600 bg-white whitespace-nowrap">${lastDate}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white text-right tabular-nums">${product.unit_price}</td>
                </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function showOutOfStockError(message) {
        const tbody = document.getElementById('outofstock-tbody');
        if (!tbody) return;
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="py-12 px-6 text-center text-red-500">
                    <span class="material-symbols-outlined text-4xl mb-2 block">error</span>
                    <p>${message}</p>
                </td>
            </tr>
        `;
    }

    function exportInventoryCsv() {
        const params = new URLSearchParams({
            search: inventoryFilters.search,
            status: inventoryFilters.status
        });
        window.location.href = '{{ route("admin.reports.inventory.export.csv") }}?' + params.toString();
    }

    function exportInventoryPdf() {
        const params = new URLSearchParams({
            search: inventoryFilters.search,
            status: inventoryFilters.status
        });
        window.location.href = '{{ route("admin.reports.inventory.export.pdf") }}?' + params.toString();
    }

    // Event listeners
    document.getElementById('inventory-search').addEventListener('input', function() {
        clearTimeout(inventorySearchTimeout);
        inventorySearchTimeout = setTimeout(() => applyInventoryFilters(), 500);
    });

    document.getElementById('inventory-status').addEventListener('change', applyInventoryFilters);

    // Auto-refresh every 30 seconds
    setInterval(() => {
        if (!document.getElementById('content-inventory').classList.contains('hidden')) {
            loadInventoryData();
        }
        if (!document.getElementById('content-lowstock').classList.contains('hidden')) {
            loadLowStockData();
        }
        if (!document.getElementById('content-outofstock').classList.contains('hidden')) {
            loadOutOfStockData();
        }
    }, 30000);

    // Load data on page load
    document.addEventListener('DOMContentLoaded', function() {
        loadInventoryData();
        const lowSearch = document.getElementById('lowstock-search');
        if (lowSearch) {
            lowSearch.addEventListener('input', function() {
                clearTimeout(lowStockSearchTimeout);
                lowStockSearchTimeout = setTimeout(applyLowStockFilters, 500);
            });
        }
        const oosSearch = document.getElementById('outofstock-search');
        if (oosSearch) {
            oosSearch.addEventListener('input', function() {
                clearTimeout(outOfStockSearchTimeout);
                outOfStockSearchTimeout = setTimeout(applyOutOfStockFilters, 500);
            });
        }
    });
</script>
@endpush
@endsection




