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

// ============================================================
// Fix 1: renderNotifications - detect financial vs warehouse notifications
// ============================================================
const oldRenderNotif = `  (notifs || []).forEach(n => {
    let msg = n.message || '';
    let actionBtn = \`<button onclick="openReceiveModal(\${n.invoice_id})" class="btn-primary">فتح الإذن</button>\`;
    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('عجز')) { 
        actionBtn = \`<button onclick="openDecisionModal(\${n.invoice_id})" class="btn-primary" style="background:var(--danger)">مراجعة العجز</button>\`; 
    } else if (msg.includes('تعليق') || msg.includes('ذكرك')) {
        actionBtn = \`<button onclick="viewDetails(\${n.invoice_id}); markNotifAsRead('\${n.date}');" class="btn-primary" style="background:var(--secondary)">عرض التعليق والفاتورة</button>\`;
    }`;

const newRenderNotif = `  (notifs || []).forEach(n => {
    let msg = n.message || '';
    let actionBtn = '';

    if (msg.includes('مشتريات') || msg.includes('مبيعات') || msg.includes('مرتجع')) {
        // Warehouse storekeeper review (purchases, sales, returns)
        actionBtn = \`<button onclick="openStorekeeperReviewModal(\${n.invoice_id}, '\${n.date}')" class="btn-primary" style="background:var(--accent)">مراجعة واعتماد المخزن</button>\`;
    } else if (msg.includes('تحويل مخزني') || msg.includes('إذن تحويل')) {
        // Inventory transfer receipt
        actionBtn = \`<button onclick="openReceiveModal(\${n.invoice_id})" class="btn-primary">فتح إذن التحويل</button>\`;
    } else if (msg.includes('مبلغ') || msg.includes('عهدة') || msg.includes('نقدية') || msg.includes('صرف') || msg.includes('قبض')) {
        // Financial receipt (cash to custody) - just confirm with simple button
        actionBtn = \`<button onclick="confirmCashNotif(\${n.id}, \${n.invoice_id}, '\${n.date}')" class="btn-primary" style="background:var(--success)">✅ تأكيد الاستلام</button>\`;
    } else if (currentUser.role === 'مدير عام' && msg.includes('عجز')) { 
        actionBtn = \`<button onclick="openDecisionModal(\${n.invoice_id})" class="btn-primary" style="background:var(--danger)">مراجعة العجز</button>\`; 
    } else if (msg.includes('تعليق') || msg.includes('ذكرك')) {
        actionBtn = \`<button onclick="viewDetails(\${n.invoice_id}); markNotifAsRead('\${n.date}');" class="btn-primary" style="background:var(--secondary)">عرض التعليق</button>\`;
    } else {
        // Default: just dismiss
        actionBtn = \`<button onclick="n/a" class="btn-primary">عرض</button>\`;
    }`;

if (app.includes(oldRenderNotif)) {
  app = app.replace(oldRenderNotif, newRenderNotif);
  console.log('✅ Fixed renderNotifications logic');
} else {
  console.log('❌ renderNotifications pattern not found - searching...');
  const idx = app.indexOf("let actionBtn = `<button onclick=\"openReceiveModal");
  console.log('Found at:', idx);
  if (idx > -1) console.log(app.substring(idx - 50, idx + 400));
}

// ============================================================
// Fix 2: Add confirmCashNotif function (financial receipt confirmation)
// ============================================================
const confirmCashFn = `
window.confirmCashNotif = async function(notifId, invoiceId, notifDate) {
  try {
    // Mark the notification as read
    const notif = allNotifications.find(n => n.id == notifId || n.date === notifDate);
    if (notif) {
      notif.read = true;
      await window.DB.update('notifications', notif);
    }
    
    // Mark the related invoice/voucher as received if it exists
    if (invoiceId) {
      const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
      if (inv && inv.status !== 'posted') {
        inv.receiver_user = currentUser.username;
        inv.receiver_confirmed = true;
        await window.DB.update('transactions', inv);
      }
    }
    
    await loadData();
    alert('تم تأكيد الاستلام بنجاح.');
  } catch(e) {
    alert('خطأ: ' + e.message);
    console.error(e);
  }
};

window.dismissNotification = async function(notifId) {
  const notif = allNotifications.find(n => n.id == notifId);
  if (notif) {
    notif.read = true;
    await window.DB.update('notifications', notif);
    await loadData();
  }
};
`;

// Find a good place to insert it - after the renderNotifications function
const insertAfter = `  if (notifs.length === 0) {
    tbody.innerHTML = \`<tr><td colspan="4" style="text-align:center; padding: 20px; color: var(--text-secondary);">لا توجد مهام أو إشعارات جديدة بانتظارك</td></tr>\`;
  }
}`;

if (app.includes(insertAfter)) {
  app = app.replace(insertAfter, insertAfter + confirmCashFn);
  console.log('✅ Added confirmCashNotif and dismissNotification functions');
} else {
  console.log('❌ insertAfter pattern not found');
  const idx2 = app.indexOf('لا توجد مهام أو إشعارات');
  console.log('Found at:', idx2);
}

// ============================================================
// Fix 3: Fix openReceiveModal - handle missing warehouse name gracefully
// ============================================================
const oldReceive = `window.openReceiveModal = function(invoiceId) {
  const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
  document.getElementById('receive-invoice-id').value = invoiceId;
  document.getElementById('receive-info').innerText = \`إذن تحويل رقم #\${inv.id} من مخزن \${inv.from_warehouse_name}\`;`;

const newReceive = `window.openReceiveModal = function(invoiceId) {
  const inv = allInvoices.find(i => String(i.id) === String(invoiceId));
  if (!inv) { alert('لم يتم العثور على المستند.'); return; }
  const fromWh = inv.from_warehouse_name || (currentWarehouses.find(w => String(w.id) === String(inv.from_warehouse_id))?.name) || 'غير محدد';
  document.getElementById('receive-invoice-id').value = invoiceId;
  document.getElementById('receive-info').innerText = \`إذن تحويل رقم #\${inv.id} من مخزن \${fromWh}\`;`;

// Also fix store_module.js
let store = fs.readFileSync('store_module.js', 'utf8');
if (store.includes(oldReceive)) {
  store = store.replace(oldReceive, newReceive);
  console.log('✅ Fixed openReceiveModal in store_module.js');
} else {
  console.log('❌ openReceiveModal pattern not found in store_module.js');
  const idx3 = store.indexOf('openReceiveModal = function');
  console.log('Found at:', idx3);
  if (idx3 > -1) console.log(store.substring(idx3, idx3 + 400));
}

fs.writeFileSync('app_final.js', app);
fs.writeFileSync('store_module.js', store);
console.log('\n✅ All fixes applied!');
