const fs = require('fs');

// 1. Fix index.html buttons
let html = fs.readFileSync('index.html', 'utf8');
html = html.replace(/onclick="openSalesReturnsModal\(\)"/g, 'onclick="openSalesReturnModal()"');
html = html.replace(/onclick="openPurchasesReturnsModal\(\)"/g, 'onclick="openPurchasesReturnModal()"');
fs.writeFileSync('index.html', html, 'utf8');

// 2. Add Purchases Returns logic to vouchers_returns.js
let js = fs.readFileSync('vouchers_returns.js', 'utf8');

if (!js.includes('renderPurchasesReturns')) {
    const additions = `
window.renderPurchasesReturns = function() {
  const tbody = document.querySelector('#purchases-returns-table tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  
  const returns = allInvoices.filter(t => t.type === 'purchases_return');
  
  returns.forEach(r => {
    const contact = currentContacts.find(c => c.id == r.contact_id);
    const treasury = currentAccounts.find(a => a.id == r.treasury_account_id);
    const contactName = contact ? contact.name : 'غير محدد';
    const treasuryName = treasury ? treasury.name : 'آجل / غير محدد';
    
    let statusBadge = r.status === 'draft' 
      ? '<span class="badge" style="background:#ff9800;color:#fff;">مسودة</span>' 
      : '<span class="badge" style="background:#4caf50;color:#fff;">مرحلة</span>';

    const tr = document.createElement('tr');
    tr.innerHTML = \`
      <td>\${r.id}</td>
      <td>\${new Date(r.date).toLocaleString('ar-EG')}</td>
      <td>\${contactName}</td>
      <td>\${treasuryName}</td>
      <td>\${r.total_amount ? parseFloat(r.total_amount).toFixed(2) : '0.00'}</td>
      <td>\${r.notes || ''} \${statusBadge}</td>
      <td>\${r.created_by || ''}</td>
      <td>
        <button class="btn-primary" onclick="editPurchasesReturn(\${r.id})" style="padding:5px;">عرض/تعديل</button>
        \${currentUser && currentUser.role === 'مدير عام' ? \`<button class="btn-danger" onclick="deleteInvoice(\${r.id}, 'purchases_return')" style="padding:5px;">حذف</button>\` : ''}
      </td>
    \`;
    tbody.appendChild(tr);
  });
};

window.openPurchasesReturnModal = function() {
  document.getElementById('purchases-returns-modal-title').innerText = 'إنشاء فاتورة مرتجع مشتريات';
  document.getElementById('edit-purchases-returns-id').value = '';
  document.getElementById('purchases-returns-date').value = new Date().toISOString().slice(0, 16);
  document.getElementById('purchases-returns-doc-no').value = '';
  document.getElementById('purchases-returns-total').value = '';
  document.getElementById('purchases-returns-notes').value = '';
  document.getElementById('purchases-returns-status').value = 'draft';
  document.getElementById('btn-save-purchases-returns').style.display = 'inline-block';
  
  const contactSelect = document.getElementById('purchases-returns-contact');
  contactSelect.innerHTML = '<option value="">-- اختر المورد --</option>';
  currentContacts.forEach(c => {
    if(c.type === 'مورد' || c.type === 'عميل/مورد') {
      contactSelect.innerHTML += \`<option value="\${c.id}">\${c.name}</option>\`;
    }
  });

  const treasurySelect = document.getElementById('purchases-returns-treasury');
  treasurySelect.innerHTML = '<option value="">-- آجل (بدون سداد) --</option>';
  currentAccounts.filter(a => a.name.includes('خزينة') || a.name.includes('صندوق') || a.name.includes('بنك')).forEach(a => {
    treasurySelect.innerHTML += \`<option value="\${a.id}">\${a.name}</option>\`;
  });

  const itemSelect = document.getElementById('purchases-returns-item');
  itemSelect.innerHTML = '<option value="">-- اختر الصنف --</option>';
  currentItems.forEach(i => {
    itemSelect.innerHTML += \`<option value="\${i.id}">\${i.name}</option>\`;
  });

  document.getElementById('purchases-returns-items-tbody').innerHTML = '';
  
  showModal('purchases-returns-modal');
};

window.editPurchasesReturn = function(id) {
  const r = allInvoices.find(x => x.id == id && x.type === 'purchases_return');
  if(!r) return;
  openPurchasesReturnModal();
  document.getElementById('purchases-returns-modal-title').innerText = 'تعديل فاتورة مرتجع المشتريات #' + id;
  document.getElementById('edit-purchases-returns-id').value = r.id;
  document.getElementById('purchases-returns-date').value = r.date;
  document.getElementById('purchases-returns-doc-no').value = r.doc_no || '';
  document.getElementById('purchases-returns-contact').value = r.contact_id || '';
  document.getElementById('purchases-returns-treasury').value = r.treasury_account_id || '';
  document.getElementById('purchases-returns-total').value = r.total_amount || '';
  document.getElementById('purchases-returns-notes').value = r.notes || '';
  document.getElementById('purchases-returns-status').value = r.status || 'draft';
  
  const tbody = document.getElementById('purchases-returns-items-tbody');
  tbody.innerHTML = '';
  if(r.items) {
    r.items.forEach(it => {
      const item = currentItems.find(x => x.id == it.item_id);
      const itemName = item ? item.name : 'غير معروف';
      tbody.innerHTML += \`
        <tr>
          <td>\${itemName}</td>
          <td>\${it.qty}</td>
          <td>\${it.price}</td>
          <td>\${(it.qty * it.price).toFixed(2)}</td>
          <td></td>
        </tr>
      \`;
    });
  }
  
  if (r.status === 'posted') {
      document.getElementById('btn-save-purchases-returns').style.display = 'none';
  }
};

const btnSavePurchasesReturns = document.getElementById('btn-save-purchases-returns');
if (btnSavePurchasesReturns) {
  btnSavePurchasesReturns.addEventListener('click', async () => {
    const id = document.getElementById('edit-purchases-returns-id').value;
    const r = {
      date: document.getElementById('purchases-returns-date').value,
      doc_no: document.getElementById('purchases-returns-doc-no').value,
      contact_id: parseInt(document.getElementById('purchases-returns-contact').value) || null,
      treasury_account_id: parseInt(document.getElementById('purchases-returns-treasury').value) || null,
      total_amount: parseFloat(document.getElementById('purchases-returns-total').value) || 0,
      notes: document.getElementById('purchases-returns-notes').value,
      status: document.getElementById('purchases-returns-status').value,
      type: 'purchases_return',
      items: [], // Simplified for now since we usually pick an invoice to return, but let's let them enter amount
      created_by: currentUser ? currentUser.username : 'نظام'
    };
    
    if(!r.contact_id) { alert('يرجى اختيار المورد'); return; }
    if(!r.total_amount) { alert('يرجى إدخال إجمالي المرتجع'); return; }
    
    if (id) {
      r.id = parseInt(id);
      await window.DB.update('transactions', r);
      if (r.status === 'posted') {
          await generatePurchasesReturnJournal(r);
      }
    } else {
      r.id = Date.now();
      await window.DB.add('transactions', r);
      if (r.status === 'posted') {
          await generatePurchasesReturnJournal(r);
      }
    }
    
    closeModal('purchases-returns-modal');
    await loadData();
    if(typeof renderPurchasesReturns === 'function') renderPurchasesReturns();
  });
}

async function generatePurchasesReturnJournal(invoice) {
  const purchasesReturnAcc = currentAccounts.find(a => a.name === 'مرتجعات المشتريات' || a.name === 'مرتجع المشتريات');
  const supplierAcc = currentAccounts.find(a => a.name === 'الموردين');
  
  if(!purchasesReturnAcc || !supplierAcc) {
      alert('لم يتم العثور على حساب "مرتجعات المشتريات" أو "الموردين". يرجى إضافتها لدليل الحسابات للترحيل.');
      return;
  }

  const journal = {
      date: invoice.date,
      description: 'إثبات مرتجع مشتريات رقم ' + invoice.id + (invoice.doc_no ? ' / مرجع: ' + invoice.doc_no : ''),
      lines: [],
      user: currentUser.username,
      type: 'purchases_return',
      ref_id: invoice.id
  };

  // Debit Supplier, Credit Purchases Returns
  journal.lines.push({ account_id: supplierAcc.id, debit: invoice.total_amount, credit: 0, notes: 'مرتجع للمورد' });
  journal.lines.push({ account_id: purchasesReturnAcc.id, debit: 0, credit: invoice.total_amount, notes: 'قيمة المرتجع' });

  // If paid immediately, Credit Treasury, Debit Supplier
  if (invoice.treasury_account_id) {
      journal.lines.push({ account_id: invoice.treasury_account_id, debit: invoice.total_amount, credit: 0, notes: 'سداد المرتجع من المورد' });
      journal.lines.push({ account_id: supplierAcc.id, debit: 0, credit: invoice.total_amount, notes: 'إقفال حساب المورد' });
  }

  await window.DB.add('journal_entries', journal);
}
`;
    js += additions;
    fs.writeFileSync('vouchers_returns.js', js, 'utf8');
}

console.log('Fixed returns buttons and logic.');
