const fs = require('fs');

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

const thRegex = /<th>الصافي \(إيراد\)<\/th>\s*<th>الحالة<\/th>\s*<th>إجراءات<\/th>/;
const thReplacement = `<th>الصافي (إيراد)</th>
                <th>المحصل</th>
                <th>المتبقي</th>
                <th>الحالة</th>
                <th>إجراءات</th>`;
html = html.replace(thRegex, thReplacement);
fs.writeFileSync('index.html', html, 'utf8');

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

const jsFix = `
let replaceBlockMatch = js.match(/let paidText = paid > 0[\\s\\S]*?<\\/span><\\/td>\\s*<td>\\$\\{actions\\}<\\/td>/);
if (replaceBlockMatch) {
    let replaceBlock = replaceBlockMatch[0];
    let newBlock = \`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(replaceBlock, newBlock);
} else {
    console.log("Could not find the block in app_final.js");
}
`;

eval(jsFix);

fs.writeFileSync('app_final.js', js, 'utf8');
console.log('Updated client abstract table columns!');
