async function loadPosArchive() {
    const tbody = document.getElementById('pos-archive-tbody');
    if (!tbody) return;
    tbody.innerHTML = '<tr><td colspan="9" style="text-align:center;">جاري التحميل...</td></tr>';
    
    try {
        let records = await window.DB.getAll('pos_archive');
        
        if (!Array.isArray(records)) {
             if (records && records.error) throw new Error(records.error);
             else throw new Error("استجابة غير متوقعة من الخادم: " + JSON.stringify(records));
        }

        // Sort descending by id
        records.sort((a, b) => b.id - a.id);
        
        // Fetch reference data to resolve names
        const clients = await window.DB.getAll('contacts');
        const warehouses = await window.DB.getAll('warehouses');

        tbody.innerHTML = '';
        if (!records || records.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" style="text-align:center;">لا يوجد فواتير مؤرشفة</td></tr>';
            return;
        }

        records.forEach(r => {
            const clientName = r.contact_id ? (clients.find(c => String(c.id) === String(r.contact_id))?.name || 'غير محدد') : 'عميل نقدي';
            const whName = r.from_warehouse_id ? (warehouses.find(w => String(w.id) === String(r.from_warehouse_id))?.name || 'غير محدد') : '-';
            
            let itemsHtml = '<ul style="margin:0; padding-right:20px; font-size:12px;">';
            if(r.items && r.items.length) {
                r.items.forEach(i => {
                    itemsHtml += `<li>${i.name} (الكمية: ${i.qty} | السعر: ${parseFloat(i.price).toFixed(2)} | الإجمالي: ${parseFloat(i.total).toFixed(2)})</li>`;
                });
            }
            itemsHtml += '</ul>';

            const netBefore = parseFloat(r.net_before_tax || 0).toFixed(2);
            const tax = parseFloat(r.tax_amount || 0).toFixed(2);
            const total = parseFloat(r.total || 0).toFixed(2);
            const dateStr = r.created_at ? new Date(r.created_at).toLocaleString('ar-EG') : '';

            tbody.innerHTML += `
                <tr>
                    <td>${r.reference || r.id}</td>
                    <td>${dateStr}</td>
                    <td>${r.user || '-'}</td>
                    <td>${clientName}</td>
                    <td>${whName}</td>
                    <td>${netBefore}</td>
                    <td>${tax}</td>
                    <td style="font-weight:bold; color:var(--primary);">${total}</td>
                    <td>${itemsHtml}</td>
                </tr>
            `;
        });
    } catch (e) {
        console.error("Failed to load POS archive", e);
        tbody.innerHTML = `<tr><td colspan="9" style="text-align:center; color:red;">خطأ في تحميل الأرشيف: ${e.message}</td></tr>`;
    }
}

// Automatically load when switching to the view
document.addEventListener('DOMContentLoaded', () => {
    const navPosArchive = document.getElementById('nav-pos-archive');
    if (navPosArchive) {
        navPosArchive.addEventListener('click', () => {
            loadPosArchive();
        });
    }
});
