window.renderAbstractComments = function(type, ab) {
  const section = document.getElementById(type + '-chat-section');
  if(section) section.style.display = ab.id ? 'block' : 'none';
  
  const listId = type + '-comments-list';
  const list = document.getElementById(listId);
  if(!list) return;
  list.innerHTML = '';
  if (!ab.comments || ab.comments.length === 0) {
    list.innerHTML = '<div style="color:var(--text-secondary); text-align:center; font-size:12px;">لا توجد تعليقات بعد.</div>';
    return;
  }
  (ab.comments || []).forEach(c => {
    let text = c.text;
    text = text.replace(/@([\w\u0600-\u06FF]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
    list.innerHTML += `<div style="margin-bottom:8px; padding-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.05);">
      <strong style="font-size:12px; color:var(--text-secondary);">${c.user} - ${new Date(c.date).toLocaleString('ar-EG')}</strong>
      <div style="margin-top:4px;">${text}</div>
    </div>`;
  });
  list.scrollTop = list.scrollHeight;
};

window.addAbstractComment = async function(type) {
  try {
    const input = document.getElementById(type + '-new-comment');
    const text = input.value.trim();
    if(!text || !window.currentViewingAbstractId) return;
    
    let isClient = type === 'client-abstract';
    let dbTable = isClient ? 'client_abstracts' : 'abstracts';
    let allData = isClient ? allClientAbstracts : allAbstracts;
    
    const abIndex = allData.findIndex(i => i.id === window.currentViewingAbstractId);
    if(abIndex === -1) return;
    
    const ab = allData[abIndex];
    if(!ab.comments) ab.comments = [];
    
    const commentObj = { user: currentUser.username, text: text, date: new Date().toISOString() };
    ab.comments.push(commentObj);
    
    const mentions = text.match(/@([\w\u0600-\u06FF]+)/g);
    if(mentions) {
      for(let m of mentions) {
        const username = m.substring(1);
        const mentionedUser = currentUsers.find(u => u.username === username);
        if(mentionedUser) {
          let notifs = await window.DB.getAll('notifications') || [];
          notifs.push({
            id: Date.now().toString() + Math.random().toString(36).substring(2),
            user: mentionedUser.username,
            text: `تم عمل منشن لك في مستخلص رقم ${ab.doc_no}`,
            link: `#`,
            date: new Date().toISOString(),
            read: false
          });
          await window.DB.put('notifications', notifs);
        }
      }
    }
    
    await window.DB.put(dbTable, ab);
    input.value = '';
    window.renderAbstractComments(type, ab);
    
    const allNotifications = await window.DB.getAll('notifications') || [];
    const myNotifs = allNotifications.filter(n => n.user === currentUser.username && !n.read);
    if(window.renderNotifications) renderNotifications(myNotifs);
  } catch(e) {
    alert("حدث خطأ أثناء إضافة التعليق: " + e.message);
  }
};

window.renderClientAbstracts = async function() {
  currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];
  const currentProjects = await window.DB.getAll('projects') || [];
  const allInvoices = await window.DB.getAll('transactions') || [];
  
  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 => p.id == ab.project_id) || {}).name || '';
    const matchSearch = (ab.client_name||'').toLowerCase().includes(search) || 
                        pName.toLowerCase().includes(search) || 
                        (ab.abstract_number && 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 => p.id == 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>` : ''}
      ${ab.status === 'draft' ? `<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);
  });
};

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');
  pSel.innerHTML = '<option value="">اختر المشروع...</option>' + currentProjects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
  
  if (id) {
      const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
      if (ab) {
          pSel.value = ab.project_id;
          document.getElementById('client-abstract-date').value = ab.date;
          document.getElementById('client-abstract-name').value = ab.client_name || '';
          document.getElementById('client-abstract-notes').value = ab.notes || '';
          document.getElementById('client-abstract-previous-value').value = ab.previous_value || 0;
          document.getElementById('client-abstract-current-value').value = ab.current_value || 0;
          document.getElementById('client-abstract-total-value').value = ab.total_value || 0;
          document.getElementById('client-abstract-deduction-percent').value = ab.deduction_percent || 0;
          document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;

          const tbody = document.getElementById('client-abstract-items-tbody');
          tbody.innerHTML = '';
          if (ab.items && ab.items.length > 0) {
              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.prev_qty || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                     <td><input type="number" class="ca-item-curr-qty" value="${parseFloat(b.curr_qty) || 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>
                 `;
                 tbody.appendChild(tr);
              });
              window.calcClientAbstractTotals();
          } else {
              // Fallback to project BOQ if abstract items were corrupted
              const proj = currentProjects.find(p => String(p.id) === String(ab.project_id));
              if (proj && proj.boq_items && Array.isArray(proj.boq_items)) {
                  proj.boq_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.qty || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                         <td><input type="number" class="ca-item-prev-qty" value="0" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                         <td><input type="number" class="ca-item-curr-qty" value="${parseFloat(b.curr_qty) || 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>
                     `;
                     tbody.appendChild(tr);
                  });
              }
              window.calcClientAbstractTotals();
          }

          if(window.renderAbstractComments) window.renderAbstractComments('client-abstract', ab);
      }
  } else {
      const form = document.getElementById('client-abstract-form'); if(form) form.reset();
      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;
      document.getElementById('client-abstract-number').value = 'CAB-' + nextId;
      if(window.renderAbstractComments) window.renderAbstractComments('client-abstract', {id:null});
  }
  
  showModal('client-abstract-modal');
};

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);
            await window.generateClientAbstractJournal(ab);
            if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
            alert('تم الاعتماد بنجاح.');
        }
    }
};

window.payClientAbstract = function(id) {
    const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
    if(ab) {
        document.getElementById('receipt-linked-invoice').value = 'cab-' + ab.id;
        document.getElementById('receipt-amount').value = ab.net_value;
        const proj = currentProjects.find(p => p.id === parseInt(ab.project_id));
        if (proj && proj.client_name) {
            document.getElementById('receipt-party-name').value = proj.client_name;
        } else {
            document.getElementById('receipt-party-name').value = ab.client_name || '';
        }
        showModal('receipt-modal');
    }
};



// ============================================
// CLIENT ABSTRACTS LOGIC (RESTORED)
// ============================================

window.onClientAbstractProjectChange = function() {
    const pId = document.getElementById('client-abstract-project').value;
    const proj = currentProjects.find(p => String(p.id) === String(pId));
    if(!proj) {
        document.getElementById('client-abstract-client-name').value = '';
        document.getElementById('client-abstract-items-tbody').innerHTML = '';
        window.calcClientAbstractTotals();
        return;
    }
    
    
    const projectAbstracts = (currentClientAbstracts || []).filter(a => String(a.project_id) === String(pId));
    let maxNum = 0;
    projectAbstracts.forEach(a => {
        let num = parseInt(String(a.abstract_number).replace(/[^\d]/g, '')) || 0;
        if(num > maxNum) maxNum = num;
    });
    const nextId = maxNum + 1;
    if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = 'جاري ' + nextId;

    document.getElementById('client-abstract-client-name').value = proj.client || '';
    
    const tbody = document.getElementById('client-abstract-items-tbody');
    tbody.innerHTML = '';
    
    if(proj.boq_items && Array.isArray(proj.boq_items)) {
        proj.boq_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.qty || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                 <td><input type="number" class="ca-item-prev-qty" value="0" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                 <td><input type="number" class="ca-item-curr-qty" value="${parseFloat(b.curr_qty) || 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>
                 
             `;
             tbody.appendChild(tr);
        });
    }
    
    window.calcClientAbstractTotals();
};

window.addClientAbstractTaxRow = function(name = '', value = 0) {
    const list = document.getElementById('client-abstract-taxes-list');
    if(!list) return;
    const div = document.createElement('div');
    div.style.display = 'flex';
    div.style.gap = '5px';
    div.style.marginBottom = '8px';
    div.style.alignItems = 'center';
    div.innerHTML = `
        <input type="text" class="ca-tax-name" placeholder="اسم الضريبة" value="${name}" style="flex:2; padding:6px; font-size:0.95em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;">
        <input type="number" class="ca-tax-value" placeholder="القيمة" value="${value}" style="flex:1; padding:6px; font-size:0.95em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;" oninput="window.calcClientAbstractTotals()">
        <select class="ca-tax-type" style="flex:1; padding:6px; font-size:0.95em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;" onchange="window.calcClientAbstractTotals()">
            <option value="percent">%</option>
            <option value="amount">قيمة</option>
        </select>
        <button type="button" class="btn-danger" style="padding:6px 12px; border-radius:4px; border:none; font-weight:bold; cursor:pointer;" onclick="this.parentElement.remove(); window.calcClientAbstractTotals()">X</button>
    `;
    list.appendChild(div);
    window.calcClientAbstractTotals();
};

window.calcClientAbstractTotals = function() {
    let prevTotal = 0;
    let currTotal = 0;
    let grossTotal = 0;
    const tbody = document.getElementById('client-abstract-items-tbody');
    if(!tbody) return { currTotal: 0, grossTotal: 0, totalDed: 0, net: 0, taxVal: 0, retVal: 0, advance: 0, otherDed: 0 };
    const rows = tbody.querySelectorAll('tr');
    
    rows.forEach(tr => {
        let price = parseFloat(tr.querySelector('.ca-item-price').value) || 0;
        let totalQty = parseFloat(tr.querySelector('.ca-item-total-qty').value) || 0;
        let pQty = parseFloat(tr.querySelector('.ca-item-prev-qty').value) || 0;
        let cQty = parseFloat(tr.querySelector('.ca-item-curr-qty').value) || 0;
        
        let totalExec = pQty + cQty;
        
        let pVal = pQty * price;
        let cVal = cQty * price;
        let tVal = totalExec * price;
        
        prevTotal += pVal;
        currTotal += cVal;
        grossTotal += tVal;
        
        tr.querySelector('.ca-item-total-exec').innerText = totalExec.toFixed(2);
        tr.querySelector('.ca-item-prev-val').innerText = pVal.toLocaleString('ar-EG');
        tr.querySelector('.ca-item-curr-val').innerText = cVal.toLocaleString('ar-EG');
        tr.querySelector('.ca-item-total-val').innerText = tVal.toLocaleString('ar-EG');
        let pct = totalQty > 0 ? ((totalExec / totalQty) * 100).toFixed(1) : 0;
        
    });
    
    if(document.getElementById('client-abstract-prev-works')) document.getElementById('client-abstract-prev-works').innerText = prevTotal.toLocaleString('ar-EG');
    if(document.getElementById('client-abstract-current-works')) document.getElementById('client-abstract-current-works').innerText = currTotal.toLocaleString('ar-EG');
    if(document.getElementById('client-abstract-total-works')) document.getElementById('client-abstract-total-works').innerText = grossTotal.toLocaleString('ar-EG');
    
    let advance = parseFloat(document.getElementById('client-abstract-advance-payment')?.value) || 0;
    
    // Dynamic taxes
    let taxVal = 0;
    let taxesArr = [];
    document.querySelectorAll('#client-abstract-taxes-list > div').forEach(div => {
        let name = div.querySelector('.ca-tax-name').value;
        let v = parseFloat(div.querySelector('.ca-tax-value').value) || 0;
        let type = div.querySelector('.ca-tax-type').value;
        taxesArr.push({ name, value: v, type });
        if(type === 'percent') {
            taxVal += currTotal * (v / 100);
        } else {
            taxVal += v;
        }
    });
    if(document.getElementById('client-abstract-tax-total-value')) {
        document.getElementById('client-abstract-tax-total-value').innerText = taxVal.toLocaleString('ar-EG');
    }
    
    let retPct = parseFloat(document.getElementById('client-abstract-retention-percent')?.value) || 0;
    let retVal = currTotal * (retPct / 100);
    if(document.getElementById('client-abstract-retention-value')) document.getElementById('client-abstract-retention-value').innerText = retVal.toLocaleString('ar-EG');
    
    let otherDed = parseFloat(document.getElementById('client-abstract-other-deductions')?.value) || 0;
    
    let totalDed = advance + taxVal + retVal + otherDed;
    let net = currTotal - totalDed;
    
    if(document.getElementById('client-abstract-total-deductions')) document.getElementById('client-abstract-total-deductions').innerText = totalDed.toLocaleString('ar-EG');
    if(document.getElementById('client-abstract-net-total')) document.getElementById('client-abstract-net-total').innerText = net.toLocaleString('ar-EG');
    
    return { currTotal, grossTotal, totalDed, net, taxVal, retVal, advance, otherDed, taxesArr };
};

// Directly attach the onclick event to the save button
const bSaveClientAb = document.getElementById('btn-save-client-abstract');
if (bSaveClientAb) {
    bSaveClientAb.onclick = async () => {
        try {
            const editIdStr = document.getElementById('edit-client-abstract-id')?.value;
            const abstract_number = document.getElementById('client-abstract-number')?.value;
            const date = document.getElementById('client-abstract-date')?.value;
            const period = document.getElementById('client-abstract-period')?.value || '';
            const project_id = document.getElementById('client-abstract-project')?.value;
            const client_name = document.getElementById('client-abstract-client-name')?.value;
            
            if(!project_id) { alert('يجب اختيار المشروع'); return; }
            
            const fileInput = document.getElementById('client-abstract-attachment');
            let attachment = document.getElementById('client-abstract-attachment-view')?.href || null;
            if(attachment === window.location.href || (attachment && attachment.endsWith('#'))) attachment = null;
            
            if (fileInput && fileInput.files && fileInput.files[0]) {
                const file = fileInput.files[0];
                attachment = await new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = (ev) => resolve(ev.target.result);
                    reader.onerror = (ev) => reject(ev);
                    reader.readAsDataURL(file);
                });
            }
            
            const tbody = document.getElementById('client-abstract-items-tbody');
            const rows = tbody.querySelectorAll('tr');
            let items = [];
            rows.forEach(tr => {
                items.push({
                    name: tr.querySelector('.ca-item-name').value,
                    unit: tr.querySelector('.ca-item-unit').value,
                    price: parseFloat(tr.querySelector('.ca-item-price').value) || 0,
                    total_qty: parseFloat(tr.querySelector('.ca-item-total-qty').value) || 0,
                    prev_qty: parseFloat(tr.querySelector('.ca-item-prev-qty').value) || 0,
                    curr_qty: parseFloat(tr.querySelector('.ca-item-curr-qty').value) || 0
                });
            });
            
            const totals = window.calcClientAbstractTotals();
            
            const obj = {
                abstract_number, date, period, project_id, client_name, attachment,
                items,
                advance_payment: totals.advance,
                taxes: totals.taxesArr,
                tax_value: totals.taxVal,
                retention_percent: parseFloat(document.getElementById('client-abstract-retention-percent')?.value) || 0,
                retention_value: totals.retVal,
                other_deductions: totals.otherDed,
                gross_value: totals.grossTotal,
                current_value: totals.currTotal,
                total_deductions: totals.totalDed,
                net_value: totals.net,
                status: 'draft'
            };
            
            if (editIdStr) {
                obj.id = parseInt(editIdStr);
                const existing = currentClientAbstracts.find(a => String(a.id) === String(obj.id));
                if(existing) obj.status = existing.status;
                if(obj.status === 'approved') { alert('لا يمكن تعديل مستخلص معتمد'); return; }
                if(!attachment && existing && existing.attachment) obj.attachment = existing.attachment;
                await window.DB.update('client_abstracts', obj);
            } else {
                await window.DB.add('client_abstracts', obj);
            }
            
            closeModal('client-abstract-modal');
            
            // Re-fetch client abstracts
            currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];
            if(typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
            
            alert('تم الحفظ بنجاح');
        } catch(err) {
            alert('خطأ في الحفظ: ' + err.message);
        }
    };
}

// ============================================
// CLIENT ABSTRACTS ACTIONS FIX
// ============================================

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="${parseFloat(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="${parseFloat(b.curr_qty) || 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>
                     
                 `;
                 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];
      if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = '';
      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('transactions') || [];
    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.currentLinkedInvoiceId = 'cab-' + ab.id;
        window.openVoucherModal('receipt', 'cab-' + ab.id);
        
        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);
            await window.generateClientAbstractJournal(ab);
            if (typeof window.renderClientAbstracts === 'function') window.renderClientAbstracts();
            alert('تم الاعتماد بنجاح.');
        }
    }
};

// ============================================
// CLIENT ABSTRACTS PRINT AND RECEIPT FIX
// ============================================

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('transactions') || [];
    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.currentLinkedInvoiceId = 'cab-' + ab.id;
        window.openVoucherModal('receipt', 'cab-' + ab.id);
        
        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('transactions') || [];
  
  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);
  });
};

// ============================================
// CLIENT ABSTRACTS EDIT BUTTON AND CONTACT FIX
// ============================================

window.payClientAbstract = async function(id) {
    const ab = currentClientAbstracts.find(a => String(a.id) === String(id));
    if(!ab) return;
    
    const allInvoices = await window.DB.getAll('transactions') || [];
    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.currentLinkedInvoiceId = 'cab-' + ab.id;
        window.openVoucherModal('receipt', 'cab-' + ab.id);
        
        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('transactions') || [];
  
  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);
  });
};

// ============================================
// CLIENT ABSTRACTS PROJECT CHANGE FIX
// ============================================

window.onClientAbstractProjectChange = function() {
    const pId = document.getElementById('client-abstract-project').value;
    const proj = currentProjects.find(p => String(p.id) === String(pId));
    if(!proj) {
        document.getElementById('client-abstract-client-name').value = '';
        document.getElementById('client-abstract-items-tbody').innerHTML = '';
        window.calcClientAbstractTotals();
        return;
    }
    
    
    const projectAbstracts = (currentClientAbstracts || []).filter(a => String(a.project_id) === String(pId));
    let maxNum = 0;
    projectAbstracts.forEach(a => {
        let num = parseInt(String(a.abstract_number).replace(/[^\d]/g, '')) || 0;
        if(num > maxNum) maxNum = num;
    });
    const nextId = maxNum + 1;
    if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = 'جاري ' + nextId;

    document.getElementById('client-abstract-client-name').value = proj.client || '';
    
    const tbody = document.getElementById('client-abstract-items-tbody');
    tbody.innerHTML = '';
    
    // Calculate previous quantities from approved abstracts for this project
    const approvedAbstracts = (currentClientAbstracts || []).filter(a => String(a.project_id) === String(pId) && a.status === 'approved');
    let prevQuantities = {};
    approvedAbstracts.forEach(ab => {
        if(ab.items && Array.isArray(ab.items)) {
            ab.items.forEach(item => {
                if(!prevQuantities[item.name]) prevQuantities[item.name] = 0;
                // Add the current quantity executed in that approved abstract
                prevQuantities[item.name] += parseFloat(item.curr_qty) || 0;
            });
        }
    });
    
    if(proj.boq_items && Array.isArray(proj.boq_items)) {
        proj.boq_items.forEach(b => {
             let prevQty = prevQuantities[b.name] || 0;
             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.qty || 0}" readonly style="border:none;background:transparent;color:#fff;width:70px;"></td>
                 <td><input type="number" class="ca-item-prev-qty" value="${prevQty}" 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>
             `;
             tbody.appendChild(tr);
        });
    }
    
    window.calcClientAbstractTotals();
};


window.generateClientAbstractJournal = async function(ab) {
    if(!ab || !window.resolveContactAccount || !window.resolveSystemAccount) return;
    
    const proj = (typeof currentProjects !== 'undefined') ? currentProjects.find(p => String(p.id) === String(ab.project_id)) : null;
    const clientName = proj ? proj.client : ab.client_name;
    const contact = (typeof currentContacts !== 'undefined') ? currentContacts.find(c => c.name === clientName) : null;
    
    const clientAcc = contact ? await window.resolveContactAccount(contact.id, 'sales') : await window.resolveSystemAccount('حسابات العملاء', ['أصول'], 'assets');
    const revAcc = await window.resolveSystemAccount('إيرادات مستخلصات', ['إيرادات'], 'revenues');
    
    let rows = [];
    const gross = parseFloat(ab.gross_value) || 0;
    const net = parseFloat(ab.net_value) || 0;
    const tax = parseFloat(ab.tax_value) || 0;
    const ret = parseFloat(ab.retention_value) || 0;
    const advance = parseFloat(ab.advance_payment) || 0;
    const otherDed = parseFloat(ab.other_deductions) || 0;
    
    // Debit Client
    if(net > 0) rows.push({ account_id: clientAcc.id, debit: net, credit: 0, project_id: ab.project_id });
    
    // Debit Taxes
    if(tax > 0) {
        const taxAcc = await window.resolveSystemAccount('ضرائب خصم من المنبع', ['أصول', 'ضرائب'], 'assets');
        rows.push({ account_id: taxAcc.id, debit: tax, credit: 0, project_id: ab.project_id });
    }
    
    // Debit Retention
    if(ret > 0) {
        const retAcc = await window.resolveSystemAccount('تأمينات ضمان أعمال', ['أصول', 'تأمينات'], 'assets');
        rows.push({ account_id: retAcc.id, debit: ret, credit: 0, project_id: ab.project_id });
    }
    
    // Debit Advance
    if(advance > 0) {
        const advAcc = await window.resolveSystemAccount('دفعات مقدمة من العملاء', ['خصوم'], 'liabilities');
        rows.push({ account_id: advAcc.id, debit: advance, credit: 0, project_id: ab.project_id });
    }
    
    
    // Debit Other Deductions
    if(otherDed > 0) {
        const otherAcc = await window.resolveSystemAccount('استقطاعات مستخلصات العملاء', ['مصروفات'], 'expenses');
        rows.push({ account_id: otherAcc.id, debit: otherDed, credit: 0, project_id: ab.project_id });
    }

    // Credit Revenue
    if(gross > 0) rows.push({ account_id: revAcc.id, debit: 0, credit: gross, project_id: ab.project_id });
    
    const journalObj = {
        date: ab.date || new Date().toISOString().split('T')[0],
        reference: 'CAB-' + (ab.abstract_number || ab.id),
        desc: 'استحقاق مستخلص إيراد رقم ' + (ab.abstract_number || ab.id) + ' لمشروع ' + (proj ? proj.name : ''),
        status: 'posted',
        created_by: 'النظام',
        total: gross,
        rows: rows
    };
    
    await window.DB.add('journal_entries', journalObj);
};
