
window.printClientAbstract = async function(id) {
    const currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];
    const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
    if(!ab) return;
    const currentProjects = await window.DB.getAll('projects') || [];
    const pName = (currentProjects.find(p => String(p.id) === String(ab.project_id)) || {}).name || '';

    let itemsHtml = '';
    if(ab.items && ab.items.length > 0) {
        itemsHtml = `
            <table style="width:100%; border-collapse: collapse; margin-top: 15px;" border="1">
                <thead>
                    <tr style="background:#eee;">
                        <th>البند</th>
                        <th>الوحدة</th>
                        <th>الفئة</th>
                        <th>إجمالي الكمية</th>
                        <th>السابق</th>
                        <th>الحالي</th>
                        <th>الإجمالي المنفذ</th>
                        <th>القيمة</th>
                    </tr>
                </thead>
                <tbody>
                    ${ab.items.map(b => {
                        let prev = parseFloat(b.prev_qty) || 0;
                        let curr = parseFloat(b.curr_qty) || 0;
                        let totalVal = parseFloat(b.total_val) || 0;
                        return `
                        <tr>
                            <td>${b.name || ''}</td>
                            <td>${b.unit || ''}</td>
                            <td>${b.price || 0}</td>
                            <td>${b.total_qty || 0}</td>
                            <td>${prev}</td>
                            <td>${curr}</td>
                            <td>${prev + curr}</td>
                            <td>${totalVal.toLocaleString('en-US')}</td>
                        </tr>
                        `;
                    }).join('')}
                </tbody>
            </table>
        `;
    }

    const printWin = window.open('', '', 'width=900,height=600');
    printWin.document.write(`
        <html dir="rtl">
        <head>
            <title>طباعة مستخلص عميل</title>
            <style>
                body { font-family: Tahoma, Arial, sans-serif; padding: 20px; }
                table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                th, td { border: 1px solid #000; padding: 8px; text-align: center; }
                th { background-color: #f2f2f2; }
                .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px; }
                .info { display: flex; justify-content: space-between; margin-bottom: 20px; }
                .totals { margin-top: 30px; font-weight: bold; }
                .totals div { margin-bottom: 10px; }
            </style>
        </head>
        <body>
            <div class="header">
                <h2>مستخلص إيراد عميل</h2>
                <h3>${ab.abstract_number || ('#' + ab.id)}</h3>
            </div>
            
            <div class="info">
                <div>
                    <p><strong>المشروع:</strong> ${pName}</p>
                    <p><strong>العميل:</strong> ${ab.client_name || ''}</p>
                </div>
                <div>
                    <p><strong>التاريخ:</strong> ${new Date(ab.date).toLocaleDateString('ar-EG')}</p>
                    <p><strong>عن الفترة:</strong> ${ab.period || ''}</p>
                </div>
            </div>

            ${itemsHtml}

            <div class="totals">
                <div style="font-size: 1.2em; margin-bottom: 15px; border-bottom: 1px solid #ccc; padding-bottom: 10px;">الإجمالي: ${(parseFloat(ab.total_value) || 0).toLocaleString('en-US')} ج.م</div>
                ${ab.taxes && ab.taxes.length ? `
                    <div style="margin-bottom: 15px;">
                        <strong>الضرائب والاستقطاعات:</strong>
                        <ul style="list-style:none; padding-right:0;">
                            ${ab.taxes.map(t => `<li>${t.name}: ${(parseFloat(t.amount) || 0).toLocaleString('en-US')} ج.م</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
                <div style="font-size: 1.4em; color: #28a745; margin-top: 20px; border-top: 2px solid #000; padding-top: 10px;">صافي المستخلص: ${(parseFloat(ab.net_value) || 0).toLocaleString('en-US')} ج.م</div>
            </div>
            
            <div style="margin-top: 50px; display: flex; justify-content: space-around;">
                <div>توقيع المهندس المختص<br><br>...........................</div>
                <div>توقيع مدير المشروع<br><br>...........................</div>
                <div>توقيع الحسابات<br><br>...........................</div>
            </div>
            
            <script>
                window.onload = function() { window.print(); window.close(); }
            </script>
        </body>
        </html>
    `);
    printWin.document.close();
};

window.payClientAbstract = async function(id) {
    const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
    if(!ab) return;
    
    const allInvoices = await window.DB.getAll('invoices') || [];
    const linkedVouchers = allInvoices.filter(j => j.type === 'receipt' && j.status === 'posted' && j.linked_invoice_id === 'cab-' + ab.id);
    let paid = 0;
    linkedVouchers.forEach(v => paid += parseFloat(v.amount) || 0);
    
    let remaining = Math.max(0, (parseFloat(ab.net_value) || 0) - paid);
    
    const currentProjects = await window.DB.getAll('projects') || [];
    const proj = currentProjects.find(p => String(p.id) === String(ab.project_id));
    
    if(typeof window.openVoucherModal === 'function') {
        window.openVoucherModal('receipt');
        
        setTimeout(() => {
            const linkedInput = document.getElementById('voucher-linked-invoice');
            if(linkedInput) linkedInput.value = 'cab-' + ab.id;
            
            const amountInput = document.getElementById('voucher-amount');
            if(amountInput) amountInput.value = remaining.toFixed(2);
            
            const statusInput = document.getElementById('voucher-status');
            if(statusInput) statusInput.value = 'posted';
            
            const partyInput = document.getElementById('voucher-contact');
            if(partyInput && proj && proj.client) {
                partyInput.value = proj.client;
            }
            
            const notesInput = document.getElementById('voucher-notes');
            if(notesInput) {
                notesInput.value = "دفعة من مستخلص إيراد رقم " + (ab.abstract_number || ab.id) + " لمشروع " + (proj ? proj.name : "");
            }
            
            const pInput = document.getElementById('voucher-project');
            if(pInput && ab.project_id) pInput.value = ab.project_id;
            
        }, 100);
    } else {
        alert('حدث خطأ: دالة فتح سند القبض غير متوفرة');
    }
};

window.renderClientAbstracts = async function() {
  currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];
  const currentProjects = await window.DB.getAll('projects') || [];
  const allInvoices = await window.DB.getAll('invoices') || [];
  
  const activeView = document.querySelector('.view.active, [id^="view-"].active');
  if(!activeView) return;
  const table = activeView.querySelector('table');
  if (!table) return;

  const tbody = table.querySelector('tbody') || table.appendChild(document.createElement('tbody'));
  tbody.innerHTML = '';
  
  const searchEl = document.getElementById('client-abstract-search');
  const search = searchEl ? searchEl.value.toLowerCase() : '';
  const filterEl = document.getElementById('client-abstract-status-filter');
  const statusFilter = filterEl ? filterEl.value : 'all';
  
  let filtered = currentClientAbstracts.filter(ab => {
    const pName = (currentProjects.find(p => String(p.id) === String(ab.project_id)) || {}).name || '';
    const matchSearch = (ab.client_name||'').toLowerCase().includes(search) || 
                        pName.toLowerCase().includes(search) || 
                        (ab.abstract_number && String(ab.abstract_number).toLowerCase().includes(search));
    const matchStatus = statusFilter === 'all' || statusFilter === '' || ab.status === statusFilter;
    return matchSearch && matchStatus;
  });
  
  filtered.sort((a,b) => new Date(b.date) - new Date(a.date));
  
  (filtered || []).forEach(ab => {
    const tr = document.createElement('tr');
    const pName = (currentProjects.find(p => String(p.id) === String(ab.project_id)) || {}).name || '';
    
    let paid = 0;
    const linkedVouchers = allInvoices.filter(j => j.type === 'receipt' && j.status === 'posted' && j.linked_invoice_id === 'cab-' + ab.id);
    (linkedVouchers || []).forEach(v => {
        paid += parseFloat(v.amount) || 0;
    });
    
    let actions = `
      <button class="action-btn btn-view" onclick="printClientAbstract(${ab.id})">طباعة</button>
      ${ab.status === 'draft' ? `<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="approveClientAbstract(${ab.id})">اعتماد</button>` : ''}
      ${ab.status === 'approved' ? `<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="payClientAbstract(${ab.id})">سند قبض</button>` : ''}
      ${ab.status === 'draft' ? `<button class="action-btn btn-edit" onclick="openClientAbstractModal(${ab.id})">تعديل</button>` : ''}
      <button class="action-btn btn-danger" onclick="deleteClientAbstract(${ab.id})">حذف</button>
    `;
    
    let remaining = Math.max(0, (parseFloat(ab.net_value) || 0) - paid);
    
    tr.innerHTML = `
      <td>${ab.abstract_number || ('#' + ab.id)}</td>
      <td>${new Date(ab.date).toLocaleDateString('ar-EG')}</td>
      <td>${pName}</td>
      <td>${ab.client_name || ''}</td>
      <td style="font-weight:bold; color:var(--success);">${(parseFloat(ab.net_value) || 0).toLocaleString('en-US')} ج.م</td>
      <td style="color:var(--primary); font-weight:bold;">${paid.toLocaleString('en-US')} ج.م</td>
      <td style="color:var(--danger); font-weight:bold;">${remaining.toLocaleString('en-US')} ج.م</td>
      <td><span class="status-badge ${ab.status==='approved'?'status-posted':'status-draft'}">${ab.status==='approved'?'معتمد':'مسودة'}</span></td>
      <td>${actions}</td>
    `;
    tbody.appendChild(tr);
  });
};
