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

// 1. In openAbstractModal, clear the default value
const badDefaultNumberCode = "document.getElementById('ab-abstract-number').value = 'SUB-' + (currentSubcontractAbstracts.length > 0 ? Math.max(...currentSubcontractAbstracts.map(a => a.id)) + 1 : 1).toString().padStart(4, '0');";
const goodDefaultNumberCode = "document.getElementById('ab-abstract-number').value = '';";

code = code.replace(badDefaultNumberCode, goodDefaultNumberCode);

// 2. In onAbstractContractChange, calculate 'جاري x'
const searchStr = "document.getElementById('ab-display-subcontractor').innerText = currentContacts.find(c => c.id == contract.subcontractor_id)?.name || '-';";

const numberingLogic = `
        const contractAbstracts = (currentSubcontractAbstracts || []).filter(a => String(a.contract_id) === String(cid));
        let maxNum = 0;
        contractAbstracts.forEach(a => {
            let num = parseInt(String(a.abstract_number).replace(/[^\\d]/g, '')) || 0;
            if(num > maxNum) maxNum = num;
        });
        const nextId = maxNum + 1;
        if(document.getElementById('ab-abstract-number')) document.getElementById('ab-abstract-number').value = 'جاري ' + nextId;
`;

if(code.indexOf("document.getElementById('ab-abstract-number').value = 'جاري '") === -1) {
    code = code.replace(searchStr, searchStr + '\n' + numberingLogic);
}

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

let indexHtml = fs.readFileSync('index.html', 'utf8');
indexHtml = indexHtml.replace(/v=20260610s/g, 'v=20260610t');
fs.writeFileSync('index.html', indexHtml, 'utf8');

console.log('Fixed subcontract abstract numbering');
