const fs = require('fs');

try {
    let indexHtml = fs.readFileSync('index.html', 'utf8');

    // 1. Add Pay button inside sales-modal
    if (!indexHtml.includes('btn-pay-inside-sales')) {
        indexHtml = indexHtml.replace(
            /<button class="btn-primary" id="btn-save-sales">حفظ الفاتورة<\/button>/g,
            `<button class="btn-primary" id="btn-save-sales">حفظ الفاتورة</button>\n        <button class="btn-success" id="btn-pay-inside-sales" style="display:none;" onclick="openPayInsideModal('sales')">تسديد دفعة 💵</button>`
        );
    }

    // 2. Add Pay button inside purchases-modal
    if (!indexHtml.includes('btn-pay-inside-purchases')) {
        indexHtml = indexHtml.replace(
            /<button class="btn-primary" id="btn-save-purchases">حفظ الفاتورة<\/button>/g,
            `<button class="btn-primary" id="btn-save-purchases">حفظ الفاتورة</button>\n        <button class="btn-success" id="btn-pay-inside-purchases" style="display:none;" onclick="openPayInsideModal('purchases')">تسديد دفعة 💵</button>`
        );
    }
    
    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + timestamp);
    
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    // Now update app_final.js to toggle this button
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');

    if (!appFinalJs.includes('window.openPayInsideModal = function')) {
        appFinalJs += `\n
window.openPayInsideModal = function(type) {
    const id = document.getElementById(\`edit-\${type}-id\`).value;
    const contactId = document.getElementById(\`\${type}-contact\`).value;
    if (!id) {
        alert('يجب حفظ الفاتورة أولاً!');
        return;
    }
    closeModal(type + '-modal');
    if(typeof openVoucherModal === 'function') {
        openVoucherModal(type === 'sales' ? 'receipt' : 'payment', id, contactId);
    }
};
`;
    }

    // Update openSalesModal
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('sales-status'\)\.value = inv\.status \|\| 'draft';/g,
        `document.getElementById('sales-status').value = inv.status || 'draft';\n    if (inv.status === 'posted') document.getElementById('btn-pay-inside-sales').style.display = 'inline-block'; else document.getElementById('btn-pay-inside-sales').style.display = 'none';`
    );
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('sales-status'\)\.value = 'draft';\n    currentSalesLines = \[\];/g,
        `document.getElementById('sales-status').value = 'draft';\n    document.getElementById('btn-pay-inside-sales').style.display = 'none';\n    currentSalesLines = [];`
    );

    // Update openPurchasesModal
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('purchases-status'\)\.value = inv\.status \|\| 'draft';/g,
        `document.getElementById('purchases-status').value = inv.status || 'draft';\n    if (inv.status === 'posted') document.getElementById('btn-pay-inside-purchases').style.display = 'inline-block'; else document.getElementById('btn-pay-inside-purchases').style.display = 'none';`
    );
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('purchases-status'\)\.value = 'draft';\n    currentPurchasesLines = \[\];/g,
        `document.getElementById('purchases-status').value = 'draft';\n    document.getElementById('btn-pay-inside-purchases').style.display = 'none';\n    currentPurchasesLines = [];`
    );

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

    console.log('Added pay buttons inside modals successfully.');
} catch (e) {
    console.error('Error patching:', e);
}
