@extends('layouts.admin')

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

@section('page-title', 'Sales 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">Sales 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('sales')" id="tab-sales" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-primary text-primary transition-colors">Sales</button>
                <button onclick="showTab('returns')" id="tab-returns" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-primary transition-colors">Sales Return</button>
            </nav>
        </div>
    </div>

    <!-- Sales Tab Content -->
    <div id="content-sales" class="tab-content">
        <!-- Stats Cards -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500">Total Sales</p>
                        <p class="text-2xl font-bold text-gray-900 mt-1" data-stat="total-sales">{{ number_format($totalSales ?? 0, 2) }}</p>
                    </div>
                    <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                        <span class="material-symbols-outlined text-green-600">trending_up</span>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500">Total Invoices</p>
                        <p class="text-2xl font-bold text-gray-900 mt-1" data-stat="total-invoices">{{ $totalInvoices ?? 0 }}</p>
                    </div>
                    <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center">
                        <span class="material-symbols-outlined text-blue-600">receipt_long</span>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500">Paid</p>
                        <p class="text-2xl font-bold text-green-600 mt-1" data-stat="paid-invoices">{{ $paidInvoices ?? 0 }}</p>
                    </div>
                    <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                        <span class="material-symbols-outlined text-green-600">check_circle</span>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500">Unpaid</p>
                        <p class="text-2xl font-bold text-red-600 mt-1" data-stat="unpaid-invoices">{{ $unpaidInvoices ?? 0 }}</p>
                    </div>
                    <div class="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center">
                        <span class="material-symbols-outlined text-red-600">pending</span>
                    </div>
                </div>
            </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="date" id="date-from" value="{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}" 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">
                <input type="date" id="date-to" value="{{ $dateTo ?? now()->format('Y-m-d') }}" 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">
                <select id="status-filter" 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="draft">Draft</option>
                    <option value="sent">Sent</option>
                    <option value="viewed">Viewed</option>
                    <option value="partial">Partial</option>
                    <option value="paid">Paid</option>
                    <option value="overdue">Overdue</option>
                    <option value="cancelled">Cancelled</option>
                </select>
                <input type="text" id="search-input" placeholder="Search invoices..." 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">
                <button onclick="applyFilters()" 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="clearFilters()" 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="exportCsv()" 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="exportPdf()" 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">Invoice</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Customer</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Date</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Amount</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Status</th>
                        </tr>
                    </thead>
                    <tbody id="sales-tbody" class="divide-y divide-gray-100">
                        <tr>
                            <td colspan="6" 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 sales data...</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Sales Returns Tab Content (credit notes — loaded via API like Sales) -->
    <div id="content-returns" 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="date" id="returns-date-from" value="{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}" 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">
                <input type="date" id="returns-date-to" value="{{ $dateTo ?? now()->format('Y-m-d') }}" 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">
                <select id="returns-status-filter" 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="pending">Pending</option>
                    <option value="approved">Approved</option>
                    <option value="rejected">Rejected</option>
                </select>
                <input type="text" id="returns-search-input" placeholder="Search return #, invoice, customer…" 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="applyReturnsFilters()" 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="clearReturnsFilters()" 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">Return #</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Invoice</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Customer</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Date</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Amount</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Status</th>
                        </tr>
                    </thead>
                    <tbody id="returns-tbody" class="divide-y divide-gray-100">
                        <tr>
                            <td colspan="7" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">undo</span>
                                <p>Open this tab to load sales returns (credit notes).</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    let searchTimeout;
    let returnsSearchTimeout;
    let currentFilters = {
        date_from: '{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}',
        date_to: '{{ $dateTo ?? now()->format('Y-m-d') }}',
        status: 'all',
        search: ''
    };
    let returnsFilters = {
        date_from: '{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}',
        date_to: '{{ $dateTo ?? now()->format('Y-m-d') }}',
        status: 'all',
        search: ''
    };

    function showTab(tabName) {
        // Hide all tab contents
        document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
        // Remove active from all tabs
        document.querySelectorAll('.tab-btn').forEach(el => {
            el.classList.remove('border-primary', 'text-primary');
            el.classList.add('border-transparent', 'text-gray-500');
        });
        // Show selected content
        document.getElementById('content-' + tabName).classList.remove('hidden');
        // Activate selected tab
        const activeTab = document.getElementById('tab-' + tabName);
        activeTab.classList.remove('border-transparent', 'text-gray-500');
        activeTab.classList.add('border-primary', 'text-primary');
        
        // Reload data when switching tabs
        if (tabName === 'sales') {
            loadSalesData();
        }
        if (tabName === 'returns') {
            loadReturnsData();
        }
    }

    function applyFilters() {
        currentFilters.date_from = document.getElementById('date-from').value;
        currentFilters.date_to = document.getElementById('date-to').value;
        currentFilters.status = document.getElementById('status-filter').value;
        currentFilters.search = document.getElementById('search-input').value.trim();
        loadSalesData();
    }

    function clearFilters() {
        const startOfMonth = new Date();
        startOfMonth.setDate(1);
        document.getElementById('date-from').value = startOfMonth.toISOString().split('T')[0];
        document.getElementById('date-to').value = new Date().toISOString().split('T')[0];
        document.getElementById('status-filter').value = 'all';
        document.getElementById('search-input').value = '';
        applyFilters();
    }

    function loadSalesData() {
        const tbody = document.getElementById('sales-tbody');
        tbody.innerHTML = `
            <tr>
                <td colspan="6" 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 sales data...</p>
                    </div>
                </td>
            </tr>
        `;

        const params = new URLSearchParams({
            date_from: currentFilters.date_from,
            date_to: currentFilters.date_to,
            status: currentFilters.status,
            search: currentFilters.search
        });

        fetch('{{ route("admin.reports.transactions.sales.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) {
                renderSalesData(data.data);
                updateStats(data.stats);
            } else {
                showError('Error loading sales data');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('Error loading sales data');
        });
    }

    function renderSalesData(invoices) {
        const tbody = document.getElementById('sales-tbody');

        if (invoices.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" class="py-12 px-6 text-center text-gray-500">
                        <span class="material-symbols-outlined text-4xl mb-2 block">analytics</span>
                        <p>No sales data available</p>
                    </td>
                </tr>
            `;
            return;
        }

        let html = '';
        invoices.forEach((invoice, index) => {
            const statusClass = getStatusClass(invoice.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 font-mono text-primary bg-white">${invoice.invoice_number}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">
                        <div class="font-medium">${invoice.customer_name}</div>
                        ${invoice.customer_email ? `<div class="text-xs text-gray-500">${invoice.customer_email}</div>` : ''}
                    </td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white whitespace-nowrap">${invoice.issue_date}</td>
                    <td class="py-4 px-6 text-sm font-medium text-gray-900 bg-white text-right tabular-nums">${invoice.amount}</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">
                            ${invoice.status_label}
                        </span>
                    </td>
                </tr>
            `;
        });

        tbody.innerHTML = html;
    }

    function getStatusClass(status) {
        const classes = {
            'draft': 'bg-gray-50 text-gray-700 border-gray-100',
            'sent': 'bg-blue-50 text-blue-700 border-blue-100',
            'viewed': 'bg-purple-50 text-purple-700 border-purple-100',
            'partial': 'bg-yellow-50 text-yellow-700 border-yellow-100',
            'paid': 'bg-green-50 text-green-700 border-green-100',
            'overdue': 'bg-red-50 text-red-700 border-red-100',
            'cancelled': 'bg-gray-50 text-gray-700 border-gray-100'
        };
        return classes[status] || classes['draft'];
    }

    function updateStats(stats) {
        // Update stats cards
        const totalSalesEl = document.querySelector('[data-stat="total-sales"]');
        const totalInvoicesEl = document.querySelector('[data-stat="total-invoices"]');
        const paidInvoicesEl = document.querySelector('[data-stat="paid-invoices"]');
        const unpaidInvoicesEl = document.querySelector('[data-stat="unpaid-invoices"]');

        if (totalSalesEl) totalSalesEl.textContent = parseFloat(stats.totalSales || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        if (totalInvoicesEl) totalInvoicesEl.textContent = stats.totalInvoices || 0;
        if (paidInvoicesEl) paidInvoicesEl.textContent = stats.paidInvoices || 0;
        if (unpaidInvoicesEl) unpaidInvoicesEl.textContent = stats.unpaidInvoices || 0;
    }

    function showError(message) {
        const tbody = document.getElementById('sales-tbody');
        tbody.innerHTML = `
            <tr>
                <td colspan="6" 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 applyReturnsFilters() {
        returnsFilters.date_from = document.getElementById('returns-date-from').value;
        returnsFilters.date_to = document.getElementById('returns-date-to').value;
        returnsFilters.status = document.getElementById('returns-status-filter').value;
        returnsFilters.search = document.getElementById('returns-search-input').value.trim();
        loadReturnsData();
    }

    function clearReturnsFilters() {
        const startOfMonth = new Date();
        startOfMonth.setDate(1);
        document.getElementById('returns-date-from').value = startOfMonth.toISOString().split('T')[0];
        document.getElementById('returns-date-to').value = new Date().toISOString().split('T')[0];
        document.getElementById('returns-status-filter').value = 'all';
        document.getElementById('returns-search-input').value = '';
        applyReturnsFilters();
    }

    function loadReturnsData() {
        const tbody = document.getElementById('returns-tbody');
        if (!tbody) return;
        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 sales returns…</p>
                    </div>
                </td>
            </tr>
        `;

        const params = new URLSearchParams({
            date_from: returnsFilters.date_from,
            date_to: returnsFilters.date_to,
            status: returnsFilters.status,
            search: returnsFilters.search
        });

        fetch('{{ route("admin.reports.transactions.sales.returns.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) {
                renderReturnsData(data.data);
            } else {
                showReturnsError('Could not load sales returns.');
            }
        })
        .catch(error => {
            console.error('Returns fetch error:', error);
            showReturnsError('Could not load sales returns.');
        });
    }

    function renderReturnsData(rows) {
        const tbody = document.getElementById('returns-tbody');
        if (!tbody) return;

        if (!rows || rows.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">undo</span>
                        <p>No sales returns in this period.</p>
                        <p class="text-sm text-gray-400 mt-2">Credit notes appear here once created under Credit Notes.</p>
                    </td>
                </tr>
            `;
            return;
        }

        let html = '';
        rows.forEach((row, index) => {
            const statusClass = getReturnsStatusClass(row.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 font-mono bg-white">
                        <a href="${row.show_url}" class="text-primary hover:underline hover:text-blue-600">${row.credit_note_number}</a>
                    </td>
                    <td class="py-4 px-6 text-sm font-mono text-gray-800 bg-white">${row.invoice_number}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">
                        <div class="font-medium">${row.customer_name}</div>
                        ${row.customer_email ? `<div class="text-xs text-gray-500">${row.customer_email}</div>` : ''}
                    </td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white whitespace-nowrap">${row.credit_note_date}</td>
                    <td class="py-4 px-6 text-sm font-medium text-gray-900 bg-white text-right tabular-nums">${row.amount}</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">
                            ${row.status_label}
                        </span>
                    </td>
                </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function getReturnsStatusClass(status) {
        const classes = {
            pending: 'bg-amber-50 text-amber-800 border-amber-100',
            approved: 'bg-green-50 text-green-800 border-green-100',
            rejected: 'bg-red-50 text-red-800 border-red-100'
        };
        return classes[status] || 'bg-gray-50 text-gray-700 border-gray-100';
    }

    function showReturnsError(message) {
        const tbody = document.getElementById('returns-tbody');
        if (!tbody) return;
        tbody.innerHTML = `
            <tr>
                <td colspan="7" 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 exportCsv() {
        const params = new URLSearchParams({
            date_from: currentFilters.date_from,
            date_to: currentFilters.date_to,
            status: currentFilters.status,
            search: currentFilters.search
        });

        window.location.href = '{{ route("admin.reports.transactions.sales.export.csv") }}?' + params.toString();
    }

    function exportPdf() {
        const params = new URLSearchParams({
            date_from: currentFilters.date_from,
            date_to: currentFilters.date_to,
            status: currentFilters.status,
            search: currentFilters.search
        });

        window.location.href = '{{ route("admin.reports.transactions.sales.export.pdf") }}?' + params.toString();
    }

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

    document.getElementById('date-from').addEventListener('change', applyFilters);
    document.getElementById('date-to').addEventListener('change', applyFilters);
    document.getElementById('status-filter').addEventListener('change', applyFilters);

    // Auto-refresh every 30 seconds (sales always; returns only when tab visible)
    setInterval(function () {
        loadSalesData();
        const returnsPanel = document.getElementById('content-returns');
        if (returnsPanel && !returnsPanel.classList.contains('hidden')) {
            loadReturnsData();
        }
    }, 30000);

    // Load data on page load
    document.addEventListener('DOMContentLoaded', function() {
        loadSalesData();
        document.getElementById('returns-search-input').addEventListener('input', function() {
            clearTimeout(returnsSearchTimeout);
            returnsSearchTimeout = setTimeout(applyReturnsFilters, 500);
        });
        document.getElementById('returns-date-from').addEventListener('change', applyReturnsFilters);
        document.getElementById('returns-date-to').addEventListener('change', applyReturnsFilters);
        document.getElementById('returns-status-filter').addEventListener('change', applyReturnsFilters);
    });
</script>
@endpush
@endsection




