const fs = require('fs');

// ===================================================
// Fix 1: Save 'user' field in returns (not just created_by)
// So "بواسطة" column shows correctly
// ===================================================
let js = fs.readFileSync('vouchers_returns.js', 'utf8');

// In sales return save
const oldSalesUser = `        created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'النظام'`;
const newSalesUser = `        created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'النظام',
        user: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'النظام'`;

if (js.includes(oldSalesUser)) {
  js = js.replace(oldSalesUser, newSalesUser);
  console.log('✅ Fixed sales return: added user field');
} else {
  console.log('❌ sales user pattern not found');
  const idx = js.indexOf("created_by: (typeof currentUser");
  if (idx > -1) console.log('Found at idx:', idx, ':', js.substring(idx, idx + 150));
}

// In purchases return save
const oldPurchUser = `        created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'نظام'`;
const newPurchUser = `        created_by: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'نظام',
        user: (typeof currentUser !== 'undefined' && currentUser) ? currentUser.username : 'نظام'`;

if (js.includes(oldPurchUser)) {
  js = js.replace(oldPurchUser, newPurchUser);
  console.log('✅ Fixed purchases return: added user field');
} else {
  console.log('❌ purchases user pattern not found');
  const idx2 = js.indexOf("created_by: (typeof currentUser");
  console.log('Pattern check - all created_by occurrences:');
  js.split('\n').forEach((l, i) => { if (l.includes('created_by')) console.log((i+1) + ': ' + l.trim()); });
}

fs.writeFileSync('vouchers_returns.js', js);
console.log('vouchers_returns.js saved.\n');

// ===================================================
// Fix 2: Make "pending_store" default status in HTML
// and REMOVE "posted" option from returns modals
// (posted only happens via storekeeper approval)
// ===================================================
let html = fs.readFileSync('index.html', 'utf8');

// Fix sales returns status dropdown
const oldSalesStatus = `<select id="sales-returns-status">
            <option value="draft">مسودة (لا تؤثر على الأرصدة)</option>
            <option value="pending_store">بانتظار اعتماد المخزن (موصى به)</option>
            <option value="posted">مُرحلة (تؤثر فوراً على الأرصدة والحسابات)</option>
          </select>`;

const newSalesStatus = `<select id="sales-returns-status">
            <option value="draft">مسودة (لا تؤثر على الأرصدة)</option>
            <option value="pending_store" selected>⏳ بانتظار اعتماد المخزن (الموصى به)</option>
          </select>
          <small style="color:var(--text-secondary); font-size:11px;">⚠️ يتم التحويل لـ"مُرحلة" تلقائياً بعد اعتماد أمين المخزن</small>`;

if (html.includes(oldSalesStatus)) {
  html = html.replace(oldSalesStatus, newSalesStatus);
  console.log('✅ Fixed sales returns status dropdown (removed posted option)');
} else {
  console.log('❌ sales status pattern not found');
}

// Fix purchases returns status dropdown
const oldPurchStatus = `<select id="purchases-returns-status">
            <option value="draft">مسودة (لا تؤثر على الأرصدة)</option>
            <option value="pending_store">بانتظار اعتماد المخزن (موصى به)</option>
            <option value="posted">مُرحلة (تؤثر فوراً على الأرصدة والحسابات)</option>
          </select>`;

const newPurchStatus = `<select id="purchases-returns-status">
            <option value="draft">مسودة (لا تؤثر على الأرصدة)</option>
            <option value="pending_store" selected>⏳ بانتظار اعتماد المخزن (الموصى به)</option>
          </select>
          <small style="color:var(--text-secondary); font-size:11px;">⚠️ يتم التحويل لـ"مُرحلة" تلقائياً بعد اعتماد أمين المخزن</small>`;

if (html.includes(oldPurchStatus)) {
  html = html.replace(oldPurchStatus, newPurchStatus);
  console.log('✅ Fixed purchases returns status dropdown (removed posted option)');
} else {
  console.log('❌ purchases status pattern not found');
}

// Update cache version
const now = Date.now();
html = html.replace(/vouchers_returns\.js\?v=\d+/, 'vouchers_returns.js?v=' + now);
html = html.replace(/app_final\.js\?v=\d+/, 'app_final.js?v=' + now);

fs.writeFileSync('index.html', html);
console.log('index.html saved.\n');

// ===================================================
// Fix 3: renderInvoices / renderSalesReturns / renderPurchasesReturns
// Use t.user || t.created_by for بواسطة column  
// ===================================================
let app = fs.readFileSync('app_final.js', 'utf8');

// In renderInvoices, the row uses t.user - need to also check created_by
const oldRow = `tbody.innerHTML += \`<tr><td>#\${t.id}</td><td>\${new Date(t.date).toLocaleString('ar-EG')}</td><td>\${typeLabel}</td><td style="font-size:13px;">\${whLabel}</td><td>\${statusLabel}</td><td>\${t.user}</td>`;

const newRow = `tbody.innerHTML += \`<tr><td>#\${t.id}</td><td>\${new Date(t.date).toLocaleString('ar-EG')}</td><td>\${typeLabel}</td><td style="font-size:13px;">\${whLabel}</td><td>\${statusLabel}</td><td>\${t.user || t.created_by || '-'}</td>`;

if (app.includes(oldRow)) {
  app = app.replace(oldRow, newRow);
  console.log('✅ Fixed renderInvoices: بواسطة uses user || created_by');
} else {
  console.log('❌ renderInvoices row pattern not found');
  const idx = app.indexOf('t.user}</td>');
  if (idx > -1) console.log('Found t.user at:', idx, ':', app.substring(idx - 50, idx + 60));
}

fs.writeFileSync('app_final.js', app);
console.log('app_final.js saved.\n');

console.log('=== All fixes done ===');
console.log('Please do Ctrl+Shift+R to reload');
