const fs = require('fs');

// Fix 1: Fix app_final.js btn-approve-storekeeper to handle returns
let app = fs.readFileSync('app_final.js', 'utf8');

const oldApprove = `  if (inv.type === 'sales') await generateSalesJournal(inv);
  else if (inv.type === 'purchases') await generatePurchasesJournal(inv);
  
  if (window.currentStorekeeperReviewNotifDate) {`;

const newApprove = `  if (inv.type === 'sales') await generateSalesJournal(inv);
  else if (inv.type === 'purchases') await generatePurchasesJournal(inv);
  else if (inv.type === 'sales_return') { if(typeof generateSalesReturnJournal === 'function') await generateSalesReturnJournal(inv); }
  else if (inv.type === 'purchases_return') { if(typeof generatePurchasesReturnJournal === 'function') await generatePurchasesReturnJournal(inv); }
  
  if (window.currentStorekeeperReviewNotifDate) {`;

if (app.includes(oldApprove)) {
  app = app.replace(oldApprove, newApprove);
  console.log('Fixed app_final.js: approve storekeeper for returns.');
} else {
  console.log('Pattern not found in app_final.js - trying partial match...');
  // find the location
  const idx = app.indexOf("if (inv.type === 'sales') await generateSalesJournal(inv)");
  console.log('Found at index:', idx);
  if (idx > -1) {
    console.log('Context:', app.substring(idx, idx + 300));
  }
}

// Fix 2: Fix renderNotifications to handle returns notifications properly
const oldRenderNotif = `    if (msg.includes('مشتريات') || msg.includes('مبيعات')) {
        actionBtn = \`<button onclick="openStorekeeperReviewModal(\${n.invoice_id}, '\${n.date}')" class="btn-primary" style="background:var(--accent)">مراجعة واعتماد</button>\`;
    } else if (currentUser.role === 'مدير عام' && msg.includes('عجز')) {`;

const newRenderNotif = `    if (msg.includes('مشتريات') || msg.includes('مبيعات') || msg.includes('مرتجع')) {
        actionBtn = \`<button onclick="openStorekeeperReviewModal(\${n.invoice_id}, '\${n.date}')" class="btn-primary" style="background:var(--accent)">مراجعة واعتماد</button>\`;
    } else if (currentUser.role === 'مدير عام' && msg.includes('عجز')) {`;

if (app.includes(oldRenderNotif)) {
  app = app.replace(oldRenderNotif, newRenderNotif);
  console.log('Fixed app_final.js: renderNotifications for returns.');
} else {
  console.log('renderNotifications pattern not found');
  const idx = app.indexOf("msg.includes('مشتريات') || msg.includes('مبيعات')");
  console.log('Found at index:', idx);
  if (idx > -1) {
    console.log('Context:', app.substring(idx - 20, idx + 200));
  }
}

// Fix 3: Fix openStorekeeperReviewModal in app_final.js to handle returns
const oldSKTitle = `  document.getElementById('storekeeper-review-title').innerText = inv.type === 'purchases' ? 'مراجعة واستلام مشتريات' : 'مراجعة وصرف مبيعات';
  let info = \`<strong>رقم المستند:</strong> #\${inv.id} &nbsp;|&nbsp; <strong>النوع:</strong> \${inv.type === 'purchases' ? 'مشتريات' : 'مبيعات'}\`;`;

const newSKTitle = `  document.getElementById('storekeeper-review-title').innerText = 
    inv.type === 'purchases' ? 'مراجعة واستلام مشتريات' : 
    inv.type === 'sales' ? 'مراجعة وصرف مبيعات' : 
    inv.type === 'sales_return' ? 'مراجعة واستلام مرتجع مبيعات' : 
    'مراجعة وصرف مرتجع مشتريات';
  let typeLabel = inv.type === 'purchases' ? 'مشتريات' : inv.type === 'sales' ? 'مبيعات' : inv.type === 'sales_return' ? 'مرتجع مبيعات' : 'مرتجع مشتريات';
  let info = \`<strong>رقم المستند:</strong> #\${inv.id} &nbsp;|&nbsp; <strong>النوع:</strong> \${typeLabel}\`;`;

if (app.includes(oldSKTitle)) {
  app = app.replace(oldSKTitle, newSKTitle);
  console.log('Fixed app_final.js: openStorekeeperReviewModal title for returns.');
} else {
  console.log('openStorekeeperReviewModal title pattern not found');
  const idx = app.indexOf("'storekeeper-review-title'");
  console.log('Found storekeeper-review-title at index:', idx);
}

// Fix 4: Fix btn-approve-storekeeper in app_final.js - remove duplicate alert
const oldAlert = `  closeModal('storekeeper-review-modal');
  alert('?? ?????? ??????? ??????? ??????');
  if (typeof renderNotifications === 'function') renderNotifications();
  await loadData();
  alert('تم الاعتماد والتحديث بنجاح.');
});`;

const newAlert = `  closeModal('storekeeper-review-modal');
  if (typeof renderNotifications === 'function') renderNotifications();
  await loadData();
  alert('تم الاعتماد وتحديث المخزون والقيد المحاسبي بنجاح.');
});`;

if (app.includes(oldAlert)) {
  app = app.replace(oldAlert, newAlert);
  console.log('Fixed app_final.js: removed garbled alert.');
}

fs.writeFileSync('app_final.js', app);
console.log('Done updating app_final.js');

// Fix 5: Also fix store_module.js - same garbled alert
let store = fs.readFileSync('store_module.js', 'utf8');
const oldStoreAlert = `  closeModal('storekeeper-review-modal');
  alert('?? ?????? ??????? ??????? ??????');
  if (typeof renderNotifications === 'function') renderNotifications();
  await loadData();
  alert('تم الاعتماد والتحديث بنجاح.');
});`;

const newStoreAlert = `  closeModal('storekeeper-review-modal');
  if (typeof renderNotifications === 'function') renderNotifications();
  await loadData();
  alert('تم الاعتماد وتحديث المخزون والقيد المحاسبي بنجاح.');
});`;

if (store.includes(oldStoreAlert)) {
  store = store.replace(oldStoreAlert, newStoreAlert);
  console.log('Fixed store_module.js: removed garbled alert.');
}
fs.writeFileSync('store_module.js', store);
console.log('Done updating store_module.js');

// Fix 6: Fix btn-confirm-receipt to also handle notification marking
// Check the current code handles markNotifAsRead for any invoice type
console.log('\n=== Current btn-confirm-receipt related notif code: ===');
const confIdx = store.indexOf('btn-confirm-receipt');
if(confIdx > -1) {
  console.log(store.substring(confIdx, confIdx + 800));
}
