const fs = require('fs');

// 1. Fix vouchers_returns.js
let vouchers = fs.readFileSync('vouchers_returns.js', 'utf8');
vouchers = vouchers.replace(
  /const cashParent = currentAccounts\.find\(a => a\.name === 'الأصول' \|\| a\.name === 'الأصول المتداولة' \|\| a\.name === 'نقدية بالصندوق والبنوك'\);/g,
  `const cashParent = currentAccounts.find(a => a.name.includes('صول') || a.name.includes('نقدية') || a.name.includes('خزن') || a.name.includes('بنك'));`
);
fs.writeFileSync('vouchers_returns.js', vouchers, 'utf8');

// 2. Fix app_final.js
let app = fs.readFileSync('app_final.js', 'utf8');

// A. Add button to renderAccounts
if (!app.includes('openAccountStatement(${acc.id})')) {
  app = app.replace(
    /const actions = `<div class="action-buttons">\s*<button class="action-btn btn-edit"/g,
    `const actions = \`<div class="action-buttons">\n        <button class="action-btn btn-view" onclick="openAccountStatement(\${acc.id})" title="كشف حساب"><i class="fas fa-file-invoice-dollar"></i></button>\n        <button class="action-btn btn-edit"`
  );
}

// B. Add button to renderContacts
if (!app.includes(`openContactStatement('\${c.id}')`)) {
  app = app.replace(
    /<button class="action-btn btn-view" onclick="viewContact\('\${c.id}'\)">/g,
    `<button class="action-btn btn-view" onclick="viewContact('\${c.id}')"><i class="fas fa-eye"></i></button>\n          <button class="action-btn btn-view" onclick="openContactStatement('\${c.id}')" title="كشف حساب" style="background:#17a2b8;"><i class="fas fa-file-invoice-dollar"></i></button>`
  );
  // Actually, wait, viewContact already has the icon inside it. 
  // Let me match it properly without breaking viewContact.
}

// C. Define openAccountStatement and refreshAccountStatement
const accStatementJS = `
window.openAccountStatement = function(accountId) {
  window.currentStatementAccountId = accountId;
  const a = currentAccounts.find(x => x.id === accountId);
  if(!a) return;
  document.getElementById('statement-header-info').innerText = \`كشف حساب: \${a.name}\`;
  document.getElementById('statement-date-from').value = '';
  document.getElementById('statement-date-to').value = '';
  window.refreshAccountStatement();
  
  // Reuse the contact statement modal since it's just a generic table
  showModal('contact-statement-modal');
};

window.refreshAccountStatement = function() {
  const accountId = window.currentStatementAccountId;
  const a = currentAccounts.find(x => x.id === accountId);
  if(!a) return;

  const filterFrom = document.getElementById('statement-date-from').value;
  const filterTo = document.getElementById('statement-date-to').value;

  const tbody = document.getElementById('statement-tbody');
  tbody.innerHTML = '';

  let records = [];

  // Add Opening Balance
  if (a.op_debit || a.op_credit) {
    records.push({
      date: '1970-01-01', // very old date to stay at top
      type: 'رصيد افتتاحي',
      ref: '-',
      notes: '',
      debit: parseFloat(a.op_debit) || 0,
      credit: parseFloat(a.op_credit) || 0
    });
  }

  // Gather Journals
  currentJournals.filter(j => j.status === 'posted').forEach(j => {
    if(j.rows) {
      j.rows.forEach(r => {
        if(r.account_id == accountId) {
          records.push({
            date: j.date,
            type: 'قيد يومية',
            ref: '#' + j.id,
            notes: r.description || j.notes || '',
            debit: parseFloat(r.debit) || 0,
            credit: parseFloat(r.credit) || 0
          });
        }
      });
    }
  });

  // Filter by date
  if (filterFrom) {
    const fromDate = new Date(filterFrom); fromDate.setHours(0,0,0,0);
    records = records.filter(r => r.date === '1970-01-01' || new Date(r.date) >= fromDate);
  }
  if (filterTo) {
    const toDate = new Date(filterTo); toDate.setHours(23,59,59,999);
    records = records.filter(r => new Date(r.date) <= toDate);
  }

  // Sort chronologically
  records.sort((r1, r2) => new Date(r1.date) - new Date(r2.date));

  let runningBalance = 0;
  let totalDebit = 0;
  let totalCredit = 0;

  records.forEach(r => {
    totalDebit += r.debit;
    totalCredit += r.credit;
    runningBalance += (r.debit - r.credit);

    let balStr = Math.abs(runningBalance).toLocaleString('ar-EG');
    if (runningBalance > 0) balStr += ' مدين';
    else if (runningBalance < 0) balStr += ' دائن';

    let displayDate = r.date === '1970-01-01' ? '-' : new Date(r.date).toLocaleString('ar-EG');

    tbody.innerHTML += \`<tr>
      <td>\${displayDate}</td>
      <td>\${r.type}</td>
      <td>\${r.ref}</td>
      <td>\${r.notes}</td>
      <td style="color:var(--danger)">\${r.debit ? r.debit.toLocaleString('ar-EG') : '-'}</td>
      <td style="color:var(--success)">\${r.credit ? r.credit.toLocaleString('ar-EG') : '-'}</td>
      <td style="font-weight:bold">\${balStr}</td>
    </tr>\`;
  });

  document.getElementById('statement-total-debit').innerText = totalDebit.toLocaleString('ar-EG');
  document.getElementById('statement-total-credit').innerText = totalCredit.toLocaleString('ar-EG');
  
  let finalBalStr = Math.abs(runningBalance).toLocaleString('ar-EG');
  if (runningBalance > 0) finalBalStr += ' مدين';
  else if (runningBalance < 0) finalBalStr += ' دائن';
  else finalBalStr = '0';
  document.getElementById('statement-final-balance').innerText = finalBalStr;
};
`;

if (!app.includes('window.openAccountStatement = function')) {
  app += '\n' + accStatementJS;
}

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

// 3. Fix index.html cache bust and update the refresh button to call the correct function dynamically!
let html = fs.readFileSync('index.html', 'utf8');
html = html.replace(/window\.refreshContactStatement\(\)/g, "window.currentStatementAccountId ? window.refreshAccountStatement() : window.refreshContactStatement()");
html = html.replace(/v=\d+/g, 'v=' + Date.now());
fs.writeFileSync('index.html', html, 'utf8');

console.log('Done adding statement features!');
