
window.openClientAbstractModal = function(id = null) {
  window.currentViewingAbstractId = id;
  document.getElementById('client-abstract-modal-title').innerText = id ? 'تعديل مستخلص إيراد عميل #' + id : 'مستخلص إيراد عميل جديد';
  document.getElementById('edit-client-abstract-id').value = id || '';
  
  const pSel = document.getElementById('client-abstract-project');
  if(pSel) pSel.innerHTML = '<option value="">اختر المشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  
  const tbody = document.getElementById('client-abstract-items-tbody');
  if(tbody) tbody.innerHTML = '';
  const taxesList = document.getElementById('client-abstract-taxes-list');
  if(taxesList) taxesList.innerHTML = '';
  
  if (id) {
      const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
      if (ab) {
          if(pSel) pSel.value = ab.project_id;
          
          if(document.getElementById('client-abstract-date')) document.getElementById('client-abstract-date').value = ab.date || '';
          if(document.getElementById('client-abstract-client-name')) document.getElementById('client-abstract-client-name').value = ab.client_name || '';
          if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = ab.abstract_number || '';
          if(document.getElementById('client-abstract-period')) document.getElementById('client-abstract-period').value = ab.period || '';
          
          if(document.getElementById('client-abstract-advance-payment')) document.getElementById('client-abstract-advance-payment').value = ab.advance_payment || 0;
          if(document.getElementById('client-abstract-retention-percent')) document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;
          if(document.getElementById('client-abstract-other-deductions')) document.getElementById('client-abstract-other-deductions').value = ab.other_deductions || 0;
          
          const attachView = document.getElementById('client-abstract-attachment-view');
          if(attachView) {
              if(ab.attachment) {
                  attachView.href = ab.attachment;
                  attachView.style.display = 'inline-block';
              } else {
                  attachView.style.display = 'none';
              }
          }
          
          if(ab.items && tbody) {
              ab.items.forEach(b => {
                 let tr = document.createElement('tr');
                 tr.innerHTML = `
                     <td><input type="text" class="ca-item-name" value="${b.name || ''}" readonly style="border:none;background:transparent;color:#fff;"></td>
                     <td><input type="text" class="ca-item-unit" value="${b.unit || ''}" readonly style="border:none;background:transparent;color:#fff;width:50px;"></td>
                     <td><input type="number" class="ca-item-price" value="${b.price || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                     <td><input type="number" class="ca-item-total-qty" value="${b.total_qty || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                     <td><input type="number" class="ca-item-prev-qty" value="${b.curr_qty + b.prev_qty || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                     <td><input type="number" class="ca-item-curr-qty" value="0" step="0.01" style="width:70px;" oninput="window.calcClientAbstractTotals()"></td>
                     <td class="ca-item-total-exec">0</td>
                     <td class="ca-item-prev-val">0</td>
                     <td class="ca-item-curr-val" style="color:var(--primary); font-weight:bold;">0</td>
                     <td class="ca-item-total-val" style="font-weight:bold;">0</td>
                     <td class="ca-item-pct">0%</td>
                 `;
                 tbody.appendChild(tr);
              });
          }
          
          if(ab.taxes && taxesList) {
              ab.taxes.forEach(t => {
                  if(typeof window.addClientAbstractTaxRow === 'function') {
                      window.addClientAbstractTaxRow(t.name, t.value);
                      const divs = taxesList.querySelectorAll('div');
                      if(divs.length > 0) {
                          const lastDiv = divs[divs.length - 1];
                          const typeSel = lastDiv.querySelector('.ca-tax-type');
                          if(typeSel) typeSel.value = t.type || 'amount';
                      }
                  }
              });
          }
      }
  } else {
      const form = document.getElementById('client-abstract-form'); if(form) form.reset();
      if(document.getElementById('client-abstract-date')) document.getElementById('client-abstract-date').value = new Date().toISOString().split('T')[0];
      const nextId = (currentClientAbstracts.length > 0 ? Math.max(...currentClientAbstracts.map(a=>a.id)) : 0) + 1;
      if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = 'CAB-' + nextId;
      if(document.getElementById('client-abstract-advance-payment')) document.getElementById('client-abstract-advance-payment').value = 0;
      if(document.getElementById('client-abstract-retention-percent')) document.getElementById('client-abstract-retention-percent').value = 0;
      if(document.getElementById('client-abstract-other-deductions')) document.getElementById('client-abstract-other-deductions').value = 0;
      const attachView = document.getElementById('client-abstract-attachment-view');
      if(attachView) attachView.style.display = 'none';
  }
  
  if(typeof window.calcClientAbstractTotals === 'function') window.calcClientAbstractTotals();
  showModal('client-abstract-modal');
};

window.printClientAbstract = function(id) {
    alert('سيتم إضافة نموذج الطباعة لاحقاً');
};

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);
    
    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-party-name');
            if(partyInput) partyInput.value = ab.client_name || '';
        }, 100);
    } else {
        alert('حدث خطأ: دالة فتح سند القبض غير متوفرة');
    }
};

window.deleteClientAbstract = async function(id) {
    if(confirm('هل أنت متأكد من حذف هذا المستخلص؟')) {
        await window.DB.remove('client_abstracts', id);
        if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
    }
};

window.approveClientAbstract = async function(id) {
    if(confirm('هل أنت متأكد من اعتماد هذا المستخلص؟')) {
        const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
        if(ab) {
            ab.status = 'approved';
            await window.DB.update('client_abstracts', ab);
            if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
            alert('تم الاعتماد بنجاح.');
        }
    }
};
