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

const regex = /let paidText = paid > 0[\s\S]*?<td>\$\\{actions\\}<\/td>\s*\\`;/;
const match = js.match(regex);

if (match) {
    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.replace(match[0], replacement);
    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Fixed table successfully with regex!');
} else {
    console.log('Regex did not match!');
}
