
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));
    
    const currentContacts = await window.DB.getAll('contacts') || [];
    const contact = currentContacts.find(c => c.name === (proj ? proj.client : ab.client_name));
    
    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 && contact) {
                partyInput.value = contact.id;
            }
            
            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>` : ''}
      <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);
  });
};
