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

// I will match everything from "let paidText =" down to "tbody.appendChild(tr);"
const regex = /let paidText = paid > 0[\s\S]*?tbody\.appendChild\(tr\);/g;

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>
    \\\`;
    tbody.appendChild(tr);`;

    js = js.replace(match[0], replacement);
    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log("Success! Updated app_final.js!");
} else {
    console.log("Failed to match regex in app_final.js!");
}
