const fs = require('fs');

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

    // 1. Give IDs to the "Paid Now" containers so we can hide them
    if (!indexHtml.includes('id="sales-payment-now-container"')) {
        indexHtml = indexHtml.replace(
            /<div style="display: flex; gap: 15px; margin-top: 15px; background: rgba\(0,255,0,0\.05\); padding: 15px; border-radius: 8px;">\s*<div class="flex-col">\s*<label>المبلغ المدفوع الآن \(اختياري\)<\/label>\s*<input type="number" id="sales-paid-amount"/g,
            '<div id="sales-payment-now-container" style="display: flex; gap: 15px; margin-top: 15px; background: rgba(0,255,0,0.05); padding: 15px; border-radius: 8px;">\n        <div class="flex-col">\n          <label>المبلغ المدفوع الآن (اختياري)</label>\n          <input type="number" id="sales-paid-amount"'
        );
    }
    
    if (!indexHtml.includes('id="purchases-payment-now-container"')) {
        indexHtml = indexHtml.replace(
            /<div style="display: flex; gap: 15px; margin-top: 15px; background: rgba\(0,255,0,0\.05\); padding: 15px; border-radius: 8px;">\s*<div class="flex-col">\s*<label>المبلغ المدفوع الآن \(اختياري\)<\/label>\s*<input type="number" id="purchases-paid-amount"/g,
            '<div id="purchases-payment-now-container" style="display: flex; gap: 15px; margin-top: 15px; background: rgba(0,255,0,0.05); padding: 15px; border-radius: 8px;">\n        <div class="flex-col">\n          <label>المبلغ المدفوع الآن (اختياري)</label>\n          <input type="number" id="purchases-paid-amount"'
        );
    }

    // 2. Add Delete button inside the invoice modal
    if (!indexHtml.includes('btn-delete-inside-sales')) {
        indexHtml = indexHtml.replace(
            /<button class="btn-success" id="btn-pay-inside-sales" style="display:none;" onclick="openPayInsideModal\('sales'\)">تسديد دفعة 💵<\/button>/g,
            `<button class="btn-success" id="btn-pay-inside-sales" style="display:none;" onclick="openPayInsideModal('sales')">تسديد دفعة 💵</button>\n        <button class="btn-danger" id="btn-delete-inside-sales" style="display:none;" onclick="deleteInvoiceInsideModal('sales')">حذف הפاتورة 🗑️</button>`
        );
    }
    
    if (!indexHtml.includes('btn-delete-inside-purchases')) {
        indexHtml = indexHtml.replace(
            /<button class="btn-success" id="btn-pay-inside-purchases" style="display:none;" onclick="openPayInsideModal\('purchases'\)">تسديد دفعة 💵<\/button>/g,
            `<button class="btn-success" id="btn-pay-inside-purchases" style="display:none;" onclick="openPayInsideModal('purchases')">تسديد دفعة 💵</button>\n        <button class="btn-danger" id="btn-delete-inside-purchases" style="display:none;" onclick="deleteInvoiceInsideModal('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');

    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');

    // 3. Fix v.total_amount -> v.amount
    appFinalJs = appFinalJs.replace(/v\.total_amount/g, 'v.amount');
    
    // 4. Hide "Paid Now" and show "Delete" in openSalesModal
    appFinalJs = appFinalJs.replace(
        /if \(inv\.status === 'posted'\) document\.getElementById\('btn-pay-inside-sales'\)\.style\.display = 'inline-block'; else document\.getElementById\('btn-pay-inside-sales'\)\.style\.display = 'none';/g,
        `if (inv.status === 'posted') document.getElementById('btn-pay-inside-sales').style.display = 'inline-block'; else document.getElementById('btn-pay-inside-sales').style.display = 'none';
    
    if (inv.status === 'draft') document.getElementById('btn-delete-inside-sales').style.display = 'inline-block'; else document.getElementById('btn-delete-inside-sales').style.display = 'none';
    
    document.getElementById('sales-payment-now-container').style.display = 'none'; // Hide when editing`
    );
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('btn-pay-inside-sales'\)\.style\.display = 'none';\n    currentSalesLines = \[\];/g,
        `document.getElementById('btn-pay-inside-sales').style.display = 'none';
    document.getElementById('btn-delete-inside-sales').style.display = 'none';
    document.getElementById('sales-payment-now-container').style.display = 'flex'; // Show when creating new
    currentSalesLines = [];`
    );

    // 5. Hide "Paid Now" and show "Delete" in openPurchasesModal
    appFinalJs = appFinalJs.replace(
        /if \(inv\.status === 'posted'\) document\.getElementById\('btn-pay-inside-purchases'\)\.style\.display = 'inline-block'; else document\.getElementById\('btn-pay-inside-purchases'\)\.style\.display = 'none';/g,
        `if (inv.status === 'posted') document.getElementById('btn-pay-inside-purchases').style.display = 'inline-block'; else document.getElementById('btn-pay-inside-purchases').style.display = 'none';
        
    if (inv.status === 'draft') document.getElementById('btn-delete-inside-purchases').style.display = 'inline-block'; else document.getElementById('btn-delete-inside-purchases').style.display = 'none';
    
    document.getElementById('purchases-payment-now-container').style.display = 'none'; // Hide when editing`
    );
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('btn-pay-inside-purchases'\)\.style\.display = 'none';\n    currentPurchasesLines = \[\];/g,
        `document.getElementById('btn-pay-inside-purchases').style.display = 'none';
    document.getElementById('btn-delete-inside-purchases').style.display = 'none';
    document.getElementById('purchases-payment-now-container').style.display = 'flex'; // Show when creating new
    currentPurchasesLines = [];`
    );

    // 6. Add deleteInvoiceInsideModal function
    if (!appFinalJs.includes('deleteInvoiceInsideModal')) {
        appFinalJs += `\n
window.deleteInvoiceInsideModal = async function(type) {
    const id = document.getElementById(\`edit-\${type}-id\`).value;
    if (!id) return;
    if (confirm('هل أنت متأكد من حذف هذه الفاتورة؟')) {
        await deleteInvoice(parseInt(id), type);
        closeModal(type + '-modal');
    }
};
`;
    }

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');
    console.log('Repairs applied successfully.');
} catch (e) {
    console.error('Error patching:', e);
}
