جارِ التحميل...

window.renderLocalInvoices = function() { const container = document.getElementById('local-invoices-container'); if(!container) return; let history = JSON.parse(localStorage.getItem('adminInvoiceHistory') || '[]'); // Filtering const searchInput = document.getElementById('invoice-search-input'); const dateFilter = document.getElementById('invoice-date-filter'); const query = searchInput ? searchInput.value.toLowerCase().trim() : ''; const dateQ = dateFilter ? dateFilter.value : ''; // format YYYY-MM-DD if (query) { history = history.filter(inv => { const str = ((inv.studentName || '') + ' ' + (inv.email || '') + ' ' + (inv.orderId || '')).toLowerCase(); return str.includes(query); }); } if (dateQ) { history = history.filter(inv => { if(!inv.date) return false; return inv.date.startsWith(dateQ); // simple match on YYYY-MM-DD }); } if (history.length === 0) { container.innerHTML = '

لا توجد فواتير مطابقة للبحث أو لم يتم إنشاء أي فواتير محلياً.

'; return; } let tableHTML = ` `; history.forEach((inv, index) => { const dateObj = new Date(inv.date); const dateStr = dateObj.toLocaleString('ar-SA'); // Calculate Overdue let currentStatus = inv.status || 'paid'; const daysDiff = (new Date() - dateObj) / (1000 * 60 * 60 * 24); if (currentStatus === 'pending' && daysDiff > 7) { currentStatus = 'overdue'; } let statusBadge = ''; // Since array is filtered, passing `index` directly to update function could mutate wrong element. // We must pass the orderId or find the index in original array. // Best is to pass orderId. const originalIndex = JSON.parse(localStorage.getItem('adminInvoiceHistory') || '[]').findIndex(x => x.orderId === inv.orderId && x.date === inv.date); let statusSelect = `'; tableHTML += ` `; }); tableHTML += '
التاريخ اسم المتدرب الدورات الإجمالي الحالة الإجراءات
${dateStr} ${inv.studentName}
${inv.email}
${inv.courses} ${inv.total} ر.س ${statusBadge} ${statusSelect} عرض الفاتورة
'; container.innerHTML = tableHTML; }; window.updateLocalInvoiceStatus = async function(index, newStatus) { if(index === -1) return; const history = JSON.parse(localStorage.getItem('adminInvoiceHistory') || '[]'); if (history[index]) { history[index].status = newStatus; localStorage.setItem('adminInvoiceHistory', JSON.stringify(history)); try { const orderId = history[index].orderId; if(orderId) { const { doc, updateDoc } = window; await updateDoc(doc(window.db, "orders", orderId), { status: newStatus }); } } catch(e) { console.error("Could not update order in Firestore:", e); } renderLocalInvoices(); } }; window.exportInvoicesCSV = function() { const history = JSON.parse(localStorage.getItem('adminInvoiceHistory') || '[]'); if (history.length === 0) { alert('لا توجد فواتير لتصديرها'); return; } // CSV Header (UTF-8 BOM is required for Excel to read Arabic correctly) let csvContent = "\uFEFF"; csvContent += "رقم الطلب,التاريخ,اسم المتدرب,البريد الإلكتروني,الدورات,الإجمالي (ر.س),الحالة\n"; history.forEach(inv => { const dateObj = new Date(inv.date); const dateStr = dateObj.toLocaleDateString('ar-SA') + ' ' + dateObj.toLocaleTimeString('ar-SA'); let statusAr = 'مدفوعة'; if (inv.status === 'pending') statusAr = 'قيد الانتظار'; if (inv.status === 'overdue') statusAr = 'متأخرة'; // Escape fields with quotes if they contain commas const escapeCSV = (str) => '"' + String(str).replace(/"/g, '""') + '"'; const row = [ escapeCSV(inv.orderId || ''), escapeCSV(dateStr), escapeCSV(inv.studentName || ''), escapeCSV(inv.email || ''), escapeCSV(inv.courses || ''), inv.total || 0, escapeCSV(statusAr) ]; csvContent += row.join(',') + "\n"; }); // Create a Blob and trigger download const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.setAttribute("href", url); link.setAttribute("download", "invoices_report_" + new Date().toISOString().split('T')[0] + ".csv"); document.body.appendChild(link); link.click(); document.body.removeChild(link); }; window.clearLocalInvoices = function() { if(confirm('هل أنت متأكد من مسح أرشيف الفواتير المحلي؟ هذا الإجراء لا يحذف الفواتير من قاعدة البيانات، بل يمسح السجل المحلي فقط.')) { localStorage.removeItem('adminInvoiceHistory'); renderLocalInvoices(); } }; document.addEventListener('DOMContentLoaded', () => { if(window.renderLocalInvoices) { window.renderLocalInvoices(); const archiveTab = document.querySelector('[data-section="localinvoices"]'); if(archiveTab) { archiveTab.addEventListener('click', window.renderLocalInvoices); } } });