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

const startStr = "let paidText = paid > 0 ? `<div style=\"font-size:0.85em; color:var(--primary); margin-top:5px;\">المحصل: ${paid.toLocaleString('ar-EG')}</div>` : '';";
const endStr = "<td>${actions}</td>\n    `;";

const startIdx = js.indexOf(startStr);
if (startIdx !== -1) {
    const endIdx = js.indexOf(endStr, startIdx);
    if (endIdx !== -1) {
        const replacement = `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('ar-EG')} ج.م</td>
      <td style="color:var(--primary); font-weight:bold;">\${paid.toLocaleString('ar-EG')} ج.م</td>
      <td style="color:var(--danger); font-weight:bold;">\${remaining.toLocaleString('ar-EG')} ج.م</td>
      <td><span class="status-badge \${ab.status==='approved'?'status-posted':'status-draft'}">\${ab.status==='approved'?'معتمد':'مسودة'}</span></td>
      <td>\${actions}</td>
    \`;`;
        
        js = js.substring(0, startIdx) + replacement + js.substring(endIdx + endStr.length);
        fs.writeFileSync('app_final.js', js, 'utf8');
        console.log("Fixed table successfully!");
    } else {
        console.log("Could not find endStr");
    }
} else {
    console.log("Could not find startStr");
}
