const fs = require('fs');

// 1. Update index.html
let html = fs.readFileSync('index.html', 'utf8');

const oldTaxesHtml = `          <div style="display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 10px; margin-bottom: 10px; align-items: center;">
            <span>ضرائب:</span>
            <div style="display: flex; align-items: center; gap: 5px;">
              <input type="number" id="client-abstract-tax-percent" value="0" oninput="window.calcClientAbstractTotals()" style="width: 60px; padding: 5px; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px; text-align: center;">
              <span>%</span>
            </div>
            <span id="client-abstract-tax-value" style="font-weight: bold; text-align: center; color: #ff6b6b;">0</span>
          </div>`;

const newTaxesHtml = `          <div style="margin-bottom: 15px; padding: 10px; background: rgba(0,0,0,0.2); border: 1px solid #555; border-radius: 4px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <span style="font-weight: bold;">الضرائب:</span>
                <button type="button" class="btn-primary" style="padding: 2px 8px; font-size: 0.9em;" onclick="window.addClientAbstractTaxRow()">+ إضافة ضريبة</button>
            </div>
            <div id="client-abstract-taxes-list"></div>
            <div style="display: flex; justify-content: space-between; margin-top: 10px; border-top: 1px dashed #555; padding-top: 5px;">
                <span>إجمالي الضرائب:</span>
                <span id="client-abstract-tax-total-value" style="font-weight: bold; color: #ff6b6b;">0</span>
            </div>
          </div>`;

if(html.includes('id="client-abstract-tax-percent"')) {
    html = html.replace(oldTaxesHtml, newTaxesHtml);
    fs.writeFileSync('index.html', html, 'utf8');
    console.log('index.html updated successfully.');
} else {
    console.log('Could not find taxes block in index.html');
}

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

const jsAddTaxFunc = `
window.addClientAbstractTaxRow = function(name = '', pct = 0, isRefundable = 'false', val = 0) {
    const list = document.getElementById('client-abstract-taxes-list');
    const div = document.createElement('div');
    div.className = 'tax-row flex-row';
    div.style.gap = '5px';
    div.style.marginBottom = '5px';
    div.style.alignItems = 'center';
    
    div.innerHTML = \`
        <input type="text" class="tax-name" placeholder="بيان الضريبة" value="\${name}" style="flex: 2; padding: 5px; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px;">
        <div style="display: flex; align-items: center; gap: 2px; flex: 1;">
            <input type="number" class="tax-pct" value="\${pct}" oninput="window.calcClientAbstractTotals()" style="width: 100%; padding: 5px; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px; text-align: center;">
            <span>%</span>
        </div>
        <select class="tax-refundable" style="flex: 1.5; padding: 5px; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px;">
            <option value="false" \${isRefundable === 'false' ? 'selected' : ''}>غير مستردة</option>
            <option value="true" \${isRefundable === 'true' ? 'selected' : ''}>مستردة</option>
        </select>
        <span class="tax-value" style="flex: 1; text-align: center; color: #ff6b6b; font-weight: bold;">\${val.toLocaleString('ar-EG')}</span>
        <button class="btn-danger" style="padding: 2px 8px; border-radius: 4px;" onclick="this.parentElement.remove(); window.calcClientAbstractTotals()">x</button>
    \`;
    list.appendChild(div);
};
`;

// Inject addTaxFunc before renderClientAbstracts if not already there
if (!js.includes('window.addClientAbstractTaxRow')) {
    js = js.replace('window.renderClientAbstracts = function() {', jsAddTaxFunc + '\\nwindow.renderClientAbstracts = function() {');
}

// Update logic in openClientAbstractModal
js = js.replace("document.getElementById('client-abstract-tax-percent').value = ab.tax_percent || 0;", `
      document.getElementById('client-abstract-taxes-list').innerHTML = '';
      if(ab.taxes && ab.taxes.length > 0) {
          ab.taxes.forEach(t => window.addClientAbstractTaxRow(t.name, t.pct, String(t.is_refundable), t.value));
      } else {
          // fallback for older abstracts
          if(ab.tax_percent > 0) window.addClientAbstractTaxRow('ضريبة قيمة مضافة', ab.tax_percent, 'false', ab.tax_value);
      }
`);

js = js.replace("document.getElementById('client-abstract-tax-percent').value = 0;", `
    document.getElementById('client-abstract-taxes-list').innerHTML = '';
`);

// Update logic in calcClientAbstractTotals
js = js.replace(`    let taxPct = parseFloat(document.getElementById('client-abstract-tax-percent').value) || 0;
    let taxVal = currTotal * (taxPct / 100);
    document.getElementById('client-abstract-tax-value').innerText = taxVal.toLocaleString('ar-EG');`, `
    let totalTaxVal = 0;
    document.querySelectorAll('#client-abstract-taxes-list .tax-row').forEach(row => {
        let pct = parseFloat(row.querySelector('.tax-pct').value) || 0;
        let tVal = currTotal * (pct / 100);
        totalTaxVal += tVal;
        row.querySelector('.tax-value').innerText = tVal.toLocaleString('ar-EG');
    });
    document.getElementById('client-abstract-tax-total-value').innerText = totalTaxVal.toLocaleString('ar-EG');
    let taxVal = totalTaxVal;
`);

// Update saving logic in btnSaveClientAbstract
js = js.replace(`                tax_percent: parseFloat(document.getElementById('client-abstract-tax-percent').value) || 0,
                tax_value: totals.taxVal,`, `
                taxes: Array.from(document.querySelectorAll('#client-abstract-taxes-list .tax-row')).map(row => ({
                    name: row.querySelector('.tax-name').value,
                    pct: parseFloat(row.querySelector('.tax-pct').value) || 0,
                    is_refundable: row.querySelector('.tax-refundable').value === 'true',
                    value: totals.currTotal * ((parseFloat(row.querySelector('.tax-pct').value) || 0) / 100)
                })),
`);

fs.writeFileSync('app_final.js', js, 'utf8');
console.log('app_final.js updated successfully.');
