const fs = require('fs');

try {
    // 1. ADD LINKS TO RETURNS MODALS
    let vrJs = fs.readFileSync('vouchers_returns.js', 'utf8');

    // Add a container for the link in sales returns modal
    vrJs = vrJs.replace(
        /document\.getElementById\('edit-sales-returns-id'\)\.value = r\.id;/g,
        `document.getElementById('edit-sales-returns-id').value = r.id;
    let linkContainer = document.getElementById('sales-returns-link-banner');
    if(!linkContainer) {
        linkContainer = document.createElement('div');
        linkContainer.id = 'sales-returns-link-banner';
        document.getElementById('sales-returns-modal-title').after(linkContainer);
    }
    if (r.linked_invoice_id) {
        linkContainer.innerHTML = \`<div style="margin:10px 0; background:#e3f2fd; padding:10px; border-radius:5px; border-right:4px solid #2196f3;"><a href="#" onclick="closeModal('sales-returns-modal'); openSalesModal(\${r.linked_invoice_id}); return false;" style="text-decoration:none; font-weight:bold; color:#0d47a1;">🔗 الانتقال للفاتورة الأصلية رقم #\${r.linked_invoice_id}</a></div>\`;
    } else {
        linkContainer.innerHTML = '';
    }`
    );

    // Same for purchases returns modal
    vrJs = vrJs.replace(
        /document\.getElementById\('edit-purchases-returns-id'\)\.value = r\.id;/g,
        `document.getElementById('edit-purchases-returns-id').value = r.id;
    let plinkContainer = document.getElementById('purchases-returns-link-banner');
    if(!plinkContainer) {
        plinkContainer = document.createElement('div');
        plinkContainer.id = 'purchases-returns-link-banner';
        document.getElementById('purchases-returns-modal-title').after(plinkContainer);
    }
    if (r.linked_invoice_id) {
        plinkContainer.innerHTML = \`<div style="margin:10px 0; background:#e3f2fd; padding:10px; border-radius:5px; border-right:4px solid #2196f3;"><a href="#" onclick="closeModal('purchases-returns-modal'); openPurchasesModal(\${r.linked_invoice_id}); return false;" style="text-decoration:none; font-weight:bold; color:#0d47a1;">🔗 الانتقال للفاتورة الأصلية رقم #\${r.linked_invoice_id}</a></div>\`;
    } else {
        plinkContainer.innerHTML = '';
    }`
    );
    
    // Clear the link banner when opening a new return
    vrJs = vrJs.replace(
        /document\.getElementById\('edit-sales-returns-id'\)\.value = '';/g,
        `document.getElementById('edit-sales-returns-id').value = '';\n  if(document.getElementById('sales-returns-link-banner')) document.getElementById('sales-returns-link-banner').innerHTML = '';`
    );
    vrJs = vrJs.replace(
        /document\.getElementById\('edit-purchases-returns-id'\)\.value = '';/g,
        `document.getElementById('edit-purchases-returns-id').value = '';\n  if(document.getElementById('purchases-returns-link-banner')) document.getElementById('purchases-returns-link-banner').innerHTML = '';`
    );

    fs.writeFileSync('vouchers_returns.js', vrJs, 'utf8');

    // 2. ADD LINKS TO ORIGINAL INVOICES MODALS
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');

    // For openSalesModal(id)
    appFinalJs = appFinalJs.replace(
        /const inv = allInvoices\.find\(i => i\.id === id\);/g,
        `const inv = allInvoices.find(i => i.id === id);
  let banner = document.getElementById('sales-invoice-returns-banner');
  if(!banner) {
     banner = document.createElement('div');
     banner.id = 'sales-invoice-returns-banner';
     const title = document.getElementById('sales-modal-title');
     if(title) title.after(banner);
  }
  if(inv) {
     const returns = allInvoices.filter(r => r.type === 'sales_return' && r.linked_invoice_id === inv.id);
     if(returns.length > 0) {
         let linksHTML = returns.map(r => \`<a href="#" onclick="closeModal('sales-modal'); window.switchView('sales-returns'); setTimeout(() => { window.editSalesReturn(\${r.id}); }, 200); return false;" style="margin-right:10px; text-decoration:none; font-weight:bold; color:#b71c1c;">🔗 عرض المرتجع #\${r.id}</a>\`).join('');
         banner.innerHTML = \`<div style="margin:10px 0; background:#ffebee; padding:10px; border-radius:5px; border-right:4px solid #f44336;"><strong>⚠️ يوجد مرتجعات لهذه الفاتورة:</strong><br>\${linksHTML}</div>\`;
     } else {
         banner.innerHTML = '';
     }
  } else {
     banner.innerHTML = '';
  }`
    );

    // For openPurchasesModal(id)
    // Wait, the regex might replace too many, let's target openPurchasesModal specifically
    // It's safer to use an exact string
    let purchasesRegex = /const pInv = allInvoices\.find\(i => i\.id === id\);/;
    if(appFinalJs.match(purchasesRegex)) {
        appFinalJs = appFinalJs.replace(
            purchasesRegex,
            `const pInv = allInvoices.find(i => i.id === id);
      let pbanner = document.getElementById('purchases-invoice-returns-banner');
      if(!pbanner) {
         pbanner = document.createElement('div');
         pbanner.id = 'purchases-invoice-returns-banner';
         const title = document.getElementById('purchases-modal-title');
         if(title) title.after(pbanner);
      }
      if(pInv) {
         const returns = allInvoices.filter(r => r.type === 'purchases_return' && r.linked_invoice_id === pInv.id);
         if(returns.length > 0) {
             let linksHTML = returns.map(r => \`<a href="#" onclick="closeModal('purchases-modal'); window.switchView('purchases-returns'); setTimeout(() => { window.editPurchasesReturn(\${r.id}); }, 200); return false;" style="margin-right:10px; text-decoration:none; font-weight:bold; color:#b71c1c;">🔗 عرض المرتجع #\${r.id}</a>\`).join('');
             pbanner.innerHTML = \`<div style="margin:10px 0; background:#ffebee; padding:10px; border-radius:5px; border-right:4px solid #f44336;"><strong>⚠️ يوجد مرتجعات لهذه الفاتورة:</strong><br>\${linksHTML}</div>\`;
         } else {
             pbanner.innerHTML = '';
         }
      } else {
         pbanner.innerHTML = '';
      }`
        );
    }

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');

    // Bust cache
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/vouchers_returns\.js\?v=\d+/g, 'vouchers_returns.js?v=' + timestamp);
    indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + timestamp);
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    console.log('UI links for returns added successfully.');
} catch (e) {
    console.error('Error patching UI links:', e);
}
