/**
 * Settings Actions - Handle system settings
 */
class SettingsManager {
    constructor() {
        this.basePath = window.location.pathname.includes('/rcp/') ? '/rcp/' : '/';
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.loadSettings();
    }

    setupEventListeners() {
        // Company form
        document.getElementById('companyForm')?.addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveCompanySettings();
        });

        // Logo form
        document.getElementById('logoForm')?.addEventListener('submit', (e) => {
            e.preventDefault();
            this.uploadLogo();
        });

        // Preferences form
        document.getElementById('preferencesForm')?.addEventListener('submit', (e) => {
            e.preventDefault();
            this.savePreferences();
        });

        // Logo preview
        document.getElementById('logoUpload')?.addEventListener('change', (e) => {
            this.previewLogo(e.target.files[0]);
        });

        // Remove logo button
        document.getElementById('removeLogoBtn')?.addEventListener('click', () => {
            this.removeLogo();
        });
    }

    loadSettings() {
        console.log('Loading settings...');
        // Load from localStorage as fallback
        const saved = localStorage.getItem('appSettings');
        if (saved) {
            const settings = JSON.parse(saved);
            this.populateForms(settings);
            this.showAlert('Settings loaded from local storage', 'success');
        }
    }

    populateForms(settings) {
        // Company info
        document.getElementById('companyName').value = settings.company_name || '';
        document.getElementById('companyAddress').value = settings.company_address || '';
        document.getElementById('companyPhone').value = settings.company_phone || '';
        document.getElementById('companyEmail').value = settings.company_email || '';
        document.getElementById('baseCurrency').value = settings.base_currency || 'ZAR';
        document.getElementById('decimalPlaces').value = settings.decimal_places || '2';

        // Preferences (load from separate storage)
        const prefs = localStorage.getItem('appPreferences');
        if (prefs) {
            const preferences = JSON.parse(prefs);
            document.getElementById('timezone').value = preferences.timezone || 'Africa/Johannesburg';
            document.getElementById('dateFormat').value = preferences.date_format || 'Y-m-d';
        }

        // Logo
        if (settings.logo_path) {
            document.getElementById('logoPreview').src = settings.logo_path;
        }
    }

    async saveCompanySettings() {
        const submitBtn = document.querySelector('#companyForm button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        try {
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
            submitBtn.disabled = true;

            // Get form data
            const settings = {
                company_name: document.getElementById('companyName').value,
                company_address: document.getElementById('companyAddress').value,
                company_phone: document.getElementById('companyPhone').value,
                company_email: document.getElementById('companyEmail').value,
                base_currency: document.getElementById('baseCurrency').value,
                decimal_places: document.getElementById('decimalPlaces').value
            };

            // Save to localStorage
            localStorage.setItem('appSettings', JSON.stringify(settings));
            
            this.updateFooterCompany(settings.company_name);
            this.showAlert('Company settings saved successfully!', 'success');

        } catch (error) {
            console.error('Error saving company settings:', error);
            this.showAlert('Error saving company settings', 'danger');
        } finally {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    async savePreferences() {
        const submitBtn = document.querySelector('#preferencesForm button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        try {
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
            submitBtn.disabled = true;

            const preferences = {
                timezone: document.getElementById('timezone').value,
                date_format: document.getElementById('dateFormat').value
            };

            localStorage.setItem('appPreferences', JSON.stringify(preferences));
            this.showAlert('Preferences saved successfully!', 'success');

        } catch (error) {
            console.error('Error saving preferences:', error);
            this.showAlert('Error saving preferences', 'danger');
        } finally {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    async uploadLogo() {
        const fileInput = document.getElementById('logoUpload');
        const submitBtn = document.querySelector('#logoForm button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        if (!fileInput.files[0]) {
            this.showAlert('Please select a file', 'danger');
            return;
        }

        const file = fileInput.files[0];
        
        // Validate file type
        const allowedTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
        if (!allowedTypes.includes(file.type)) {
            this.showAlert('Please select a valid image file (PNG, JPG, GIF, WebP)', 'danger');
            return;
        }

        // Validate file size
        if (file.size > 2 * 1024 * 1024) {
            this.showAlert('File size must be less than 2MB', 'danger');
            return;
        }

        try {
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Uploading...';
            submitBtn.disabled = true;

            const reader = new FileReader();
            reader.onload = (e) => {
                // Save to localStorage
                const settings = JSON.parse(localStorage.getItem('appSettings') || '{}');
                settings.logo_path = e.target.result;
                localStorage.setItem('appSettings', JSON.stringify(settings));

                // Update preview
                document.getElementById('logoPreview').src = e.target.result;
                
                this.showAlert('Logo uploaded successfully!', 'success');
                fileInput.value = '';
            };
            reader.readAsDataURL(file);

        } catch (error) {
            console.error('Error uploading logo:', error);
            this.showAlert('Error uploading logo', 'danger');
        } finally {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    async removeLogo() {
        if (!confirm('Are you sure you want to remove the company logo?')) {
            return;
        }

        try {
            // Remove from localStorage
            const settings = JSON.parse(localStorage.getItem('appSettings') || '{}');
            settings.logo_path = '';
            localStorage.setItem('appSettings', JSON.stringify(settings));

            // Reset preview
            document.getElementById('logoPreview').src = this.basePath + 'assets/images/logo-placeholder.png';
            
            this.showAlert('Logo removed successfully!', 'success');
        } catch (error) {
            console.error('Error removing logo:', error);
            this.showAlert('Error removing logo', 'danger');
        }
    }

    previewLogo(file) {
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                document.getElementById('logoPreview').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    }

    updateFooterCompany(companyName) {
        const footerCompany = document.querySelector('.footer-company');
        if (footerCompany) {
            footerCompany.textContent = companyName;
        }
    }

    exportSettings() {
        this.showAlert('Export feature coming soon!', 'info');
    }

    resetToDefaults() {
        if (confirm('Are you sure you want to reset all settings to defaults? This cannot be undone.')) {
            localStorage.removeItem('appSettings');
            localStorage.removeItem('appPreferences');
            location.reload();
        }
    }

    showAlert(message, type) {
        // Remove existing alerts
        const existingAlerts = document.querySelectorAll('.alert');
        existingAlerts.forEach(alert => alert.remove());

        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show mt-3`;
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        const container = document.querySelector('.container-fluid');
        if (container) {
            container.insertBefore(alert, container.firstChild);
        }

        setTimeout(() => {
            if (alert.parentNode) {
                alert.remove();
            }
        }, 5000);
    }
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    window.settingsManager = new SettingsManager();
});