const fs = require('fs');
let code = fs.readFileSync('contractors_module.js', 'utf8');

const taxRowStr = `window.addClientAbstractTaxRow = function(name = '', value = 0) {
    const list = document.getElementById('client-abstract-taxes-list');
    if(!list) return;
    const div = document.createElement('div');
    div.style.display = 'flex';
    div.style.gap = '5px';
    div.style.marginBottom = '8px';
    div.style.alignItems = 'center';
    div.innerHTML = \`
        <input type="text" class="ca-tax-name" placeholder="اسم الضريبة" value="\${name}" style="flex:2; padding:6px; font-size:0.95em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;">
        <input type="number" class="ca-tax-value" placeholder="القيمة" value="\${value}" style="flex:1; padding:6px; font-size:0.95em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;" oninput="window.calcClientAbstractTotals()">
        <select class="ca-tax-type" style="flex:1; padding:6px; font-size:0.95em; border-radius:4px; border:1px solid #555; background:#222; color:#fff;" onchange="window.calcClientAbstractTotals()">
            <option value="percent">%</option>
            <option value="amount">قيمة</option>
        </select>
        <button type="button" class="btn-danger" style="padding:6px 12px; border-radius:4px; border:none; font-weight:bold; cursor:pointer;" onclick="this.parentElement.remove(); window.calcClientAbstractTotals()">X</button>
    \`;
    list.appendChild(div);
    window.calcClientAbstractTotals();
};`;

code = code.replace(/window\.addClientAbstractTaxRow = function[\s\S]*?list\.appendChild\(div\);\n    window\.calcClientAbstractTotals\(\);\n\};/, taxRowStr);

// remove extra <td>
code = code.replace(/<td class="ca-item-pct">0%<\/td>/g, '');

// restore correct prev_qty logic inside openClientAbstractModal
code = code.replace(/value="\${b\.curr_qty \+ b\.prev_qty \|\| 0}"/g, 'value="${parseFloat(b.prev_qty) || 0}"');
code = code.replace(/value="0" step="0\.01"/g, 'value="${parseFloat(b.curr_qty) || 0}" step="0.01"');

// And one more logic check: what if the user opens a NEW abstract?
// onClientAbstractProjectChange generates the empty rows. I need to make sure the NEW abstract properly accumulates previous abstract quantities for the selected project.
// In onClientAbstractProjectChange:
// <td><input type="number" class="ca-item-prev-qty" value="0" readonly ...>
// We need to fetch the sum of all prev_qty and curr_qty from PREVIOUS approved abstracts for the same project.

fs.writeFileSync('contractors_module.js', code, 'utf8');

// Update version
let indexHtml = fs.readFileSync('index.html', 'utf8');
indexHtml = indexHtml.replace(/v=20260610j/g, 'v=20260610k');
fs.writeFileSync('index.html', indexHtml, 'utf8');
