const fs = require('fs');

// 1. UPDATE index.html
let html = fs.readFileSync('index.html', 'utf8');

const regex = /<span style="color: #aaa; margin-top: 10px;">جنيه مصري<\/span>\s*<\/div>\s*<\/div>\s*<div class="modal-actions"/;

const replacement = `<span style="color: #aaa; margin-top: 10px;">جنيه مصري</span>
        </div>
      </div>
      
      <div id="client-ab-linked-vouchers-container" style="display: none; margin-top: 20px; padding: 20px; background: rgba(0,0,0,0.2); border-radius: 8px; border: 1px solid #444; clear: both; width: 100%; box-sizing: border-box;">
        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #555; padding-bottom: 10px; margin-bottom: 15px;">
          <h3 style="margin:0; color: var(--primary);"><i class="fas fa-receipt"></i> الدفعات المحصلة لهذا المستخلص</h3>
          <button class="action-btn" id="btn-pay-client-abstract-inner" style="background:var(--success); color:#fff; padding:5px 15px; font-size:1rem; border:none;" onclick="payClientAbstractFromModal()">+ سند قبض</button>
        </div>
        <div style="display: flex; gap: 40px; font-weight: bold; font-size: 1.3rem; margin-bottom: 15px;">
          <div style="color: var(--success);">إجمالي المحصل: <span id="client-ab-total-paid">0</span></div>
          <div style="color: var(--danger);">المتبقي من المستخلص: <span id="client-ab-remaining">0</span></div>
        </div>
        <ul id="client-ab-linked-vouchers-list" style="list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 5px;"></ul>
      </div>

      <div class="modal-actions"`;

html = html.replace(regex, replacement);
fs.writeFileSync('index.html', html, 'utf8');

// 2. UPDATE app_final.js
let js = fs.readFileSync('app_final.js', 'utf8');

const jsRegex = /document\.getElementById\('client-abstract-attachment-view'\)\.style\.display = 'none';\s*document\.getElementById\('client-abstract-attachment-view'\)\.href = '#';/;

const jsReplacement = `document.getElementById('client-abstract-attachment-view').style.display = 'none';
    document.getElementById('client-abstract-attachment-view').href = '#';
    
    const paymentsContainer = document.getElementById('client-ab-linked-vouchers-container');
    const paymentsList = document.getElementById('client-ab-linked-vouchers-list');
    const paidSpan = document.getElementById('client-ab-total-paid');
    const remainingSpan = document.getElementById('client-ab-remaining');
    
    if (id) {
        const linkedVouchers = allInvoices.filter(v => v.type === 'receipt' && v.linked_invoice_id == 'cab-' + id && v.status === 'posted');
        let totalPaid = 0;
        let html = '';
        if (linkedVouchers.length > 0) {
            linkedVouchers.forEach(v => {
                totalPaid += parseFloat(v.amount) || 0;
                let d = new Date(v.created_at || Date.now()).toLocaleDateString('ar-EG');
                let accName = '-';
                let acc = currentAccounts.find(a => a.id === parseInt(v.treasury_account_id));
                if(acc) accName = acc.name;
                html += \`<li style="padding: 10px; background: rgba(255,255,255,0.05); border-radius: 4px; display: flex; justify-content: space-between;">
                    <span>سند قبض: \${v.id} | التاريخ: \${d} | الخزنة/البنك: \${accName}</span>
                    <span style="font-weight:bold; color:var(--success);">\${parseFloat(v.amount).toLocaleString('ar-EG')} ج.م</span>
                </li>\`;
            });
            paymentsList.innerHTML = html;
        } else {
            paymentsList.innerHTML = '<li style="color:#aaa;">لا توجد أي دفعات محصلة حتى الآن.</li>';
        }
        
        const abObjForVal = currentClientAbstracts.find(a => a.id === id);
        const netVal = abObjForVal ? parseFloat(abObjForVal.net_value) || 0 : 0;
        const remaining = netVal - totalPaid;
        
        paidSpan.innerText = totalPaid.toLocaleString('ar-EG', {minimumFractionDigits:2});
        remainingSpan.innerText = remaining.toLocaleString('ar-EG', {minimumFractionDigits:2});
        
        window.currentClientAbstractRemaining = remaining;
        paymentsContainer.style.display = 'block';
    } else {
        paymentsContainer.style.display = 'none';
        window.currentClientAbstractRemaining = 0;
    }`;

js = js.replace(jsRegex, jsReplacement);

// Hide the inner payment button if abstract is not approved
const jsRegex2 = /document\.getElementById\('btn-pay-client-abstract'\)\.style\.display = 'inline-block';/;
const jsReplacement2 = `document.getElementById('btn-pay-client-abstract').style.display = 'inline-block';
          if(document.getElementById('btn-pay-client-abstract-inner')) document.getElementById('btn-pay-client-abstract-inner').style.display = 'inline-block';`;
js = js.replace(jsRegex2, jsReplacement2);

const jsRegex3 = /document\.getElementById\('btn-pay-client-abstract'\)\.style\.display = 'none';/g;
const jsReplacement3 = `document.getElementById('btn-pay-client-abstract').style.display = 'none';
          if(document.getElementById('btn-pay-client-abstract-inner')) document.getElementById('btn-pay-client-abstract-inner').style.display = 'none';`;
js = js.replace(jsRegex3, jsReplacement3);

fs.writeFileSync('app_final.js', js, 'utf8');
console.log('Added client abstract payments list!');
