const fs = require('fs');

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

    // 1. Show delete button inside Sales Modal for ALL invoices
    appFinalJs = appFinalJs.replace(
        /if \(inv\.status === 'draft'\) document\.getElementById\('btn-delete-inside-sales'\)\.style\.display = 'inline-block'; else document\.getElementById\('btn-delete-inside-sales'\)\.style\.display = 'none';/g,
        `document.getElementById('btn-delete-inside-sales').style.display = 'inline-block';`
    );

    // 2. Show delete button inside Purchases Modal for ALL invoices
    appFinalJs = appFinalJs.replace(
        /if \(inv\.status === 'draft'\) document\.getElementById\('btn-delete-inside-purchases'\)\.style\.display = 'inline-block'; else document\.getElementById\('btn-delete-inside-purchases'\)\.style\.display = 'none';/g,
        `document.getElementById('btn-delete-inside-purchases').style.display = 'inline-block';`
    );

    // 3. Show delete button in Sales Table for ALL invoices (remove role restriction too, or keep it?)
    // Let's replace the whole block in renderSales
    appFinalJs = appFinalJs.replace(
        /if\(inv\.status === 'draft'\) {\s*if \(currentUser && currentUser\.role === 'المدير العام'\) {\s*actions \+= `<button class="action-btn btn-delete" onclick="deleteInvoice\(\$\{inv\.id\}\)"><i class="fas fa-trash"><\/i><\/button>`;\s*}\s*}/g,
        `actions += \`<button class="action-btn btn-delete" onclick="deleteInvoice(\${inv.id})"><i class="fas fa-trash"></i></button>\`;`
    );
    // There might be another format, let's just do a regex that replaces the draft check if it exists.
    // Actually, earlier I added a "سداد" button to the actions. The string looks like:
    // actions += `<button class="action-btn btn-view" onclick="openSalesModal(${inv.id})"><i class="fas fa-edit"></i></button>`;
    // if(inv.status === 'draft') { ... }

    // Let's do a more robust replace for the table buttons just in case
    appFinalJs = appFinalJs.replace(
        /if\s*\(inv\.status\s*===\s*'draft'\)\s*\{\s*if\s*\(currentUser\s*&&\s*currentUser\.role\s*===\s*'المدير العام'\)\s*\{\s*actions\s*\+=\s*`<button class="action-btn btn-delete" onclick="deleteInvoice\(\$\{inv\.id\}\)"><i class="fas fa-trash"><\/i><\/button>`;\s*\}\s*\}/g,
        `actions += \`<button class="action-btn btn-delete" onclick="deleteInvoice(\${inv.id})" title="حذف الفاتورة"><i class="fas fa-trash" style="color:red;"></i></button>\`;`
    );

    // For purchases
    appFinalJs = appFinalJs.replace(
        /if\s*\(inv\.status\s*===\s*'draft'\)\s*\{\s*if\s*\(currentUser\s*&&\s*currentUser\.role\s*===\s*'المدير العام'\)\s*\{\s*actions\s*\+=\s*`<button class="action-btn btn-delete" onclick="deleteInvoice\(\$\{inv\.id\}\)"><i class="fas fa-trash"><\/i><\/button>`;\s*\}\s*\}/g,
        `actions += \`<button class="action-btn btn-delete" onclick="deleteInvoice(\${inv.id})" title="حذف الفاتورة"><i class="fas fa-trash" style="color:red;"></i></button>\`;`
    );

    // Make sure deleteInvoice deletes associated vouchers!
    if (!appFinalJs.includes('// Delete linked vouchers')) {
        appFinalJs = appFinalJs.replace(
            /await window\.DB\.remove\('transactions', id\);/g,
            `// Delete linked vouchers
    try {
        const allTransactions = await window.DB.getAll('transactions');
        const linkedVouchers = allTransactions.filter(t => t.linked_invoice_id == id);
        for (let v of linkedVouchers) {
            // Also delete journal entries for these vouchers
            const vJournals = allJ.filter(j => j.reference && j.reference.includes(\`\${v.id}\`));
            for (let j of vJournals) {
                await window.DB.remove('journal_entries', j.id);
            }
            await window.DB.remove('transactions', v.id);
        }
    } catch(e) { console.error("Failed to delete linked vouchers", e); }
    
    await window.DB.remove('transactions', id);`
        );
    }

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

    // Bust cache
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + timestamp);
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    console.log('Delete button logic injected successfully.');
} catch (e) {
    console.error('Error patching:', e);
}
