window.currentSettings = null;

async function loadSettings() {
    try {
        const settings = await window.DB.getAll('settings');
        if (settings && settings.length > 0) {
            window.currentSettings = settings[0];
            document.getElementById('settings-company-name').value = window.currentSettings.company_name || '';
            document.getElementById('settings-tax-number').value = window.currentSettings.tax_number || '';
            document.getElementById('settings-vat-rate').value = window.currentSettings.vat_rate || 0;
            if (document.getElementById('settings-allow-negative-stock')) {
                document.getElementById('settings-allow-negative-stock').checked = window.currentSettings.allow_negative_stock || false;
            }
            
            if (window.currentSettings.logo) {
                document.getElementById('settings-logo-preview').src = window.currentSettings.logo;
                document.getElementById('settings-logo-preview').style.display = 'block';
            }
        } else {
            window.currentSettings = null;
        }
    } catch (e) {
        console.error("Error loading settings:", e);
    }
}

function handleLogoUpload(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('settings-logo-preview');
            preview.src = e.target.result;
            preview.style.display = 'block';
            
            // Store base64 temporarily until save
            preview.dataset.base64 = e.target.result;
        };
        reader.readAsDataURL(file);
    }
}

async function saveSettings() {
    const btn = document.getElementById('btn-save-settings');
    const originalText = btn.innerHTML;
    btn.innerHTML = 'جاري الحفظ...';
    btn.disabled = true;

    try {
        const companyName = document.getElementById('settings-company-name').value;
        const taxNumber = document.getElementById('settings-tax-number').value;
        const vatRate = parseFloat(document.getElementById('settings-vat-rate').value) || 0;
        const allowNegativeStock = document.getElementById('settings-allow-negative-stock') ? document.getElementById('settings-allow-negative-stock').checked : false;
        
        let logoBase64 = null;
        const preview = document.getElementById('settings-logo-preview');
        if (preview.dataset.base64) {
            logoBase64 = preview.dataset.base64;
        } else if (window.currentSettings && window.currentSettings.logo) {
            logoBase64 = window.currentSettings.logo;
        }

        const newSettings = {
            id: window.currentSettings ? window.currentSettings.id : Date.now(),
            company_name: companyName,
            tax_number: taxNumber,
            vat_rate: vatRate,
            logo: logoBase64,
            allow_negative_stock: allowNegativeStock
        };

        if (window.currentSettings) {
            await window.DB.update('settings', newSettings);
        } else {
            await window.DB.add('settings', newSettings);
        }

        window.currentSettings = newSettings;
        alert('تم حفظ الإعدادات العامة بنجاح!');
    } catch (e) {
        console.error("Error saving settings:", e);
        alert('حدث خطأ أثناء الحفظ.');
    } finally {
        btn.innerHTML = originalText;
        btn.disabled = false;
    }
}

window.renderSettings = function() {
    if (currentUser.role !== 'مدير عام') {
        alert('عفواً، لا تملك صلاحية الوصول لهذه الشاشة.');
        return;
    }
    loadSettings();
};


const originalPrint = window.print;
window.print = function() {
    // Hide original headers if they exist
    document.querySelectorAll('.print-header h1').forEach(h1 => h1.style.display = 'none');

    // Create or update global header
    if (window.currentSettings && (window.currentSettings.company_name || window.currentSettings.logo)) {
        let globalHeader = document.getElementById('global-settings-print-header');
        if (!globalHeader) {
            globalHeader = document.createElement('div');
            globalHeader.id = 'global-settings-print-header';
            globalHeader.style.cssText = 'border-bottom: 2px solid #ccc; padding-bottom: 10px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; width: 100%;';
            document.body.insertBefore(globalHeader, document.body.firstChild);
        }
        
        let html = '';
        if (window.currentSettings.company_name) {
            html += `<h1 style="margin:0;">${window.currentSettings.company_name}</h1>`;
        } else {
            html += `<div></div>`;
        }
        if (window.currentSettings.logo) {
            html += `<img src="${window.currentSettings.logo}" style="max-height: 80px;">`;
        }
        globalHeader.innerHTML = html;
        
        // Ensure style exists
        if (!document.getElementById('global-settings-style')) {
            const style = document.createElement('style');
            style.id = 'global-settings-style';
            style.innerHTML = '@media screen { #global-settings-print-header { display: none !important; } } @media print { #global-settings-print-header { display: flex !important; } }';
            document.head.appendChild(style);
            // also append to body in case body was replaced
            document.body.appendChild(style.cloneNode(true));
        }
    }

    originalPrint.apply(window);
};
