const fs = require('fs');

if (fs.existsSync('index.html')) {
    let html = fs.readFileSync('index.html', 'utf8');
    
    // Add backup button to sidebar
    if (!html.includes('btn-full-backup')) {
        const logoutIndex = html.indexOf('<li id="btn-logout"');
        const backupBtn = `        <li id="btn-full-backup" style="color: #4caf50; font-weight: bold; margin-top: 10px; border-top: 1px solid rgba(255,255,255,0.1); padding-top: 15px;">&#128190; حفظ نسخة احتياطية</li>\n`;
        html = html.slice(0, logoutIndex) + backupBtn + html.slice(logoutIndex);
        fs.writeFileSync('index.html', html, 'utf8');
        console.log('Added backup button to index.html');
    }
}

const jsAppend = `

// Full Backup Logic
document.getElementById('btn-full-backup')?.addEventListener('click', async () => {
    try {
        if (!confirm('هل تريد تحميل نسخة احتياطية كاملة من قاعدة البيانات الآن؟')) return;
        
        const backupData = {
            timestamp: new Date().toISOString(),
            users: await window.DB.getAll('users'),
            items: await window.DB.getAll('items'),
            projects: await window.DB.getAll('projects'),
            warehouses: await window.DB.getAll('warehouses'),
            contacts: await window.DB.getAll('contacts'),
            units: await window.DB.getAll('units'),
            transactions: await window.DB.getAll('transactions'),
            notifications: await window.DB.getAll('notifications'),
            client_abstracts: await window.DB.getAll('client_abstracts'),
            invoice_items: await window.DB.getAll('invoice_items'),
            item_bom: await window.DB.getAll('item_bom'),
            accounts: await window.DB.getAll('accounts'),
            journal_entries: await window.DB.getAll('journal_entries'),
            journal_lines: await window.DB.getAll('journal_lines')
        };
        
        const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(backupData, null, 2));
        const downloadAnchorNode = document.createElement('a');
        downloadAnchorNode.setAttribute("href", dataStr);
        const dateStr = new Date().toISOString().split('T')[0];
        downloadAnchorNode.setAttribute("download", "EasyERP_FullBackup_" + dateStr + ".json");
        document.body.appendChild(downloadAnchorNode); // required for firefox
        downloadAnchorNode.click();
        downloadAnchorNode.remove();
        
    } catch (err) {
        console.error('Backup failed:', err);
        alert('حدث خطأ أثناء تحميل النسخة الاحتياطية: ' + err.message);
    }
});
`;

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    if (!js.includes('btn-full-backup')) {
        fs.appendFileSync('app_final.js', jsAppend, 'utf8');
        console.log('Added backup logic to app_final.js');
    }
}

// Cache buster
if (fs.existsSync('index.html')) {
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/v=\d+/g, 'v=' + Date.now());
    fs.writeFileSync('index.html', html, 'utf8');
}
