const fs = require('fs');

let spJs = fs.readFileSync('d:/برنامج مخازن/sales_purchases_module.js', 'utf8');

// 1. Remove the 'let' declarations to avoid SyntaxError
spJs = spJs.replace(/^let currentSalesLines = \[\];[\r\n]+/m, '');
spJs = spJs.replace(/^let currentPurchasesLines = \[\];[\r\n]+/m, '');

// 2. Add the "سداد" button to renderSales and renderPurchases
// renderSales button logic:
spJs = spJs.replace(
    /actions \+= `<button class="action-btn btn-delete".*?<\/button>`;\s*\}/,
    `$&
      if(inv.status === 'posted') {
         actions += \` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${inv.id}; openVoucherModal('receipt', \${inv.id}, \${inv.contact_id}); }">سداد 💵</button>\`;
      }`
);

// renderPurchases button logic:
spJs = spJs.replace(
    /actions \+= `<button class="action-btn btn-delete" onclick="deleteInvoice\(\$\{inv\.id\}\)".*?<\/button>`;\s*\}/,
    `$&
      if(inv.status === 'posted') {
         actions += \` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${inv.id}; openVoucherModal('payment', \${inv.id}, \${inv.contact_id}); }">سداد 💵</button>\`;
      }`
);

fs.writeFileSync('d:/برنامج مخازن/sales_purchases_module.js', spJs, 'utf8');

// Bust cache just in case, though for file:// it doesn't matter
let html = fs.readFileSync('d:/برنامج مخازن/index.html', 'utf8');
const version = Date.now().toString();
html = html.replace(/v=\d+/g, 'v=' + version);
fs.writeFileSync('d:/برنامج مخازن/index.html', html, 'utf8');

console.log('Fixed sales_purchases_module.js SyntaxError and added Pay buttons.');
