const fs = require('fs');
let code = fs.readFileSync('app_final.js', 'utf8');

const updatedLogic = `
window.renderClientAbstracts = function() {
  const tbody = document.getElementById('client-abstracts-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  const search = document.getElementById('client-abstract-search').value.toLowerCase();
  const statusFilter = document.getElementById('client-abstract-status-filter').value;
  
  let filtered = currentClientAbstracts.filter(a => {
    let match = true;
    if(statusFilter && a.status !== statusFilter) match = false;
    if(search) {
      let pName = currentProjects.find(p => p.id === parseInt(a.project_id))?.name || '';
      if(!pName.toLowerCase().includes(search) && !(a.client_name||'').toLowerCase().includes(search)) match = false;
    }
    return match;
  });
  
  filtered.sort((a,b) => new Date(b.date) - new Date(a.date));
  
  filtered.forEach(ab => {
    let pName = currentProjects.find(p => p.id === parseInt(ab.project_id))?.name || '';
    let tr = document.createElement('tr');
    
    // Check how much has been received for this abstract
    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 paidText = paid > 0 ? \`<div style="font-size:0.85em; color:var(--primary); margin-top:5px;">المقبوض: \${paid.toLocaleString('ar-EG')}</div>\` : '';
    
    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('ar-EG')} ج.م\${paidText}</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) {
  document.getElementById('client-abstract-modal-title').innerText = id ? 'تعديل مستخلص إيراد عميل #' + id : 'مستخلص إيراد عميل جديد';
  document.getElementById('edit-client-abstract-id').value = id || '';
  
  // Load projects
  const pSel = document.getElementById('client-abstract-project');
  pSel.innerHTML = '<option value="">اختر المشروع...</option>' + currentProjects.map(p => \`<option value="\${p.id}">\${p.name}</option>\`).join('');
  
  const tbody = document.getElementById('client-abstract-items-tbody');
  tbody.innerHTML = '';
  
  document.getElementById('client-abstract-attachment-view').style.display = 'none';
  document.getElementById('client-abstract-attachment-view').href = '#';
  
  if (id) {
    const ab = currentClientAbstracts.find(a => a.id === id);
    if(ab) {
      document.getElementById('client-abstract-number').value = ab.abstract_number || '';
      document.getElementById('client-abstract-date').value = ab.date || new Date().toISOString().split('T')[0];
      document.getElementById('client-abstract-period').value = ab.period || '';
      document.getElementById('client-abstract-project').value = ab.project_id || '';
      document.getElementById('client-abstract-client-name').value = ab.client_name || '';
      document.getElementById('client-abstract-advance-payment').value = ab.advance_payment || 0;
      document.getElementById('client-abstract-tax-percent').value = ab.tax_percent || 0;
      document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;
      document.getElementById('client-abstract-other-deductions').value = ab.other_deductions || 0;
      
      if(ab.attachment) {
          document.getElementById('client-abstract-attachment-view').style.display = 'block';
          document.getElementById('client-abstract-attachment-view').href = ab.attachment;
      }
      
      if(ab.items) {
        ab.items.forEach((it, idx) => {
           let tr = document.createElement('tr');
           tr.innerHTML = \`
             <td>\${it.name}<input type="hidden" class="ca-item-name" value="\${it.name}"></td>
             <td>\${it.unit}<input type="hidden" class="ca-item-unit" value="\${it.unit}"></td>
             <td>\${parseFloat(it.price).toLocaleString('ar-EG')}<input type="hidden" class="ca-item-price" value="\${it.price}"></td>
             <td>\${it.total_qty}<input type="hidden" class="ca-item-total-qty" value="\${it.total_qty}"></td>
             <td><input type="number" class="ca-item-prev-qty" value="\${it.prev_qty||0}" step="0.01" style="width:70px;" oninput="window.calcClientAbstractTotals()"></td>
             <td><input type="number" class="ca-item-curr-qty" value="\${it.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>
             <td class="ca-item-pct">0%</td>
           \`;
           tbody.appendChild(tr);
        });
      }
      window.calcClientAbstractTotals();
    }
  } else {
    document.getElementById('client-abstract-number').value = '';
    document.getElementById('client-abstract-date').value = new Date().toISOString().split('T')[0];
    document.getElementById('client-abstract-period').value = '';
    document.getElementById('client-abstract-project').value = '';
    document.getElementById('client-abstract-client-name').value = '';
    document.getElementById('client-abstract-attachment').value = '';
    
    document.getElementById('client-abstract-advance-payment').value = 0;
    document.getElementById('client-abstract-tax-percent').value = 0;
    document.getElementById('client-abstract-retention-percent').value = 0;
    document.getElementById('client-abstract-other-deductions').value = 0;
    window.calcClientAbstractTotals();
  }
  
  document.getElementById('client-abstract-modal').classList.add('active');
};

window.onClientAbstractProjectChange = function() {
  const pId = document.getElementById('client-abstract-project').value;
  const cNameInput = document.getElementById('client-abstract-client-name');
  const tbody = document.getElementById('client-abstract-items-tbody');
  tbody.innerHTML = '';
  cNameInput.value = '';
  
  if(!pId) { window.calcClientAbstractTotals(); return; }
  
  const p = currentProjects.find(x => x.id === parseInt(pId));
  if(!p) { window.calcClientAbstractTotals(); return; }
  
  cNameInput.value = p.client || '';
  
  // Previous abstracts for this project to get prev quantities
  let prevAbstracts = currentClientAbstracts.filter(a => a.project_id == pId && a.id !== parseInt(document.getElementById('edit-client-abstract-id').value) && a.status === 'approved');
  let prevQtys = {};
  prevAbstracts.forEach(ab => {
      ab.items.forEach(it => {
          if(!prevQtys[it.name]) prevQtys[it.name] = 0;
          prevQtys[it.name] += (parseFloat(it.curr_qty)||0);
      });
  });
  
  if(p.boq_items) {
      p.boq_items.forEach(it => {
         let pQty = prevQtys[it.name] || 0;
         let tr = document.createElement('tr');
         tr.innerHTML = \`
             <td>\${it.name}<input type="hidden" class="ca-item-name" value="\${it.name}"></td>
             <td>\${it.unit}<input type="hidden" class="ca-item-unit" value="\${it.unit}"></td>
             <td>\${parseFloat(it.price).toLocaleString('ar-EG')}<input type="hidden" class="ca-item-price" value="\${it.price}"></td>
             <td>\${it.qty}<input type="hidden" class="ca-item-total-qty" value="\${it.qty}"></td>
             <td><input type="number" class="ca-item-prev-qty" value="\${pQty}" step="0.01" style="width:70px;" oninput="window.calcClientAbstractTotals()"></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);
      });
  }
  
  window.calcClientAbstractTotals();
};

window.calcClientAbstractTotals = function() {
    let prevTotal = 0;
    let currTotal = 0;
    let grossTotal = 0;
    const tbody = document.getElementById('client-abstract-items-tbody');
    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;
        tr.querySelector('.ca-item-pct').innerText = pct + '%';
    });
    
    document.getElementById('client-abstract-prev-works').innerText = prevTotal.toLocaleString('ar-EG');
    document.getElementById('client-abstract-current-works').innerText = currTotal.toLocaleString('ar-EG');
    document.getElementById('client-abstract-total-works').innerText = grossTotal.toLocaleString('ar-EG');
    
    let advance = parseFloat(document.getElementById('client-abstract-advance-payment').value) || 0;
    
    let taxPct = parseFloat(document.getElementById('client-abstract-tax-percent').value) || 0;
    let taxVal = currTotal * (taxPct / 100);
    document.getElementById('client-abstract-tax-value').innerText = taxVal.toLocaleString('ar-EG');
    
    let retPct = parseFloat(document.getElementById('client-abstract-retention-percent').value) || 0;
    let retVal = currTotal * (retPct / 100);
    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;
    
    document.getElementById('client-abstract-total-deductions').innerText = totalDed.toLocaleString('ar-EG');
    document.getElementById('client-abstract-net-total').innerText = net.toLocaleString('ar-EG');
    
    return { currTotal, grossTotal, totalDed, net, taxVal, retVal, advance, otherDed };
};

const btnSaveClientAbstract = document.getElementById('btn-save-client-abstract');
if (btnSaveClientAbstract) {
    // Need to make sure we don't duplicate event listeners, so we replace it with an onclick
    btnSaveClientAbstract.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;
            if(attachment === window.location.href || attachment.endsWith('#')) attachment = null;
            
            if (fileInput.files && fileInput.files[0]) {
                const file = fileInput.files[0];
                attachment = await new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = (e) => resolve(e.target.result);
                    reader.onerror = (e) => reject(e);
                    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,
                tax_percent: parseFloat(document.getElementById('client-abstract-tax-percent').value) || 0,
                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 => a.id === 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');
            await loadData();
            alert('تم الحفظ بنجاح');
        } catch(e) {
            alert('خطأ: ' + e.message);
        }
    };
}
`;

// Replace everything from window.renderClientAbstracts to the end of btnSaveClientAbstract listener
const startStr = 'window.renderClientAbstracts = function() {';
const endStr = 'window.deleteClientAbstract = async function(id) {';

const startIndex = code.indexOf(startStr);
const endIndex = code.indexOf(endStr);

if (startIndex !== -1 && endIndex !== -1) {
    const pre = code.substring(0, startIndex);
    const post = code.substring(endIndex);
    code = pre + updatedLogic + post;
    fs.writeFileSync('app_final.js', code, 'utf8');
    console.log('app_final.js updated successfully!');
} else {
    console.log('Could not find boundaries for replacement.');
}
