// OrangeHRM Dynamic Data Management System

class OrangeHRMDataManager {
    constructor() {
        this.initializeData();
        this.setupEventListeners();
        this.syncWithBackend();
    }

    // Initialize all data with default values
    initializeData() {
        // Initialize quotes data
        if (!localStorage.getItem('orangehrm_quotes')) {
            const sampleQuotes = [
                {
                    id: this.generateId(),
                    company: 'Tech Corp Solutions',
                    name: 'John Anderson',
                    job_title: 'HR Director',
                    email: 'john.anderson@techcorp.com',
                    phone: '555-0123-4567',
                    industry: 'technology',
                    employees: '101-500',
                    country: 'United States',
                    selected_plan: 'advanced',
                    modules: ['recruitment', 'performance', 'time_attendance'],
                    message: 'Looking for comprehensive HR solution for our growing team',
                    status: 'pending',
                    timestamp: new Date(Date.now() - 86400000).toISOString() // 1 day ago
                },
                {
                    id: this.generateId(),
                    company: 'StartUp Innovations',
                    name: 'Sarah Chen',
                    job_title: 'CEO',
                    email: 'sarah@startupinnovations.com',
                    phone: '555-0987-6543',
                    industry: 'technology',
                    employees: '11-50',
                    country: 'Canada',
                    selected_plan: 'starter',
                    modules: [],
                    message: 'Need basic HR management for our startup',
                    status: 'contacted',
                    timestamp: new Date(Date.now() - 172800000).toISOString() // 2 days ago
                },
                {
                    id: this.generateId(),
                    company: 'Global Manufacturing Co',
                    name: 'Michael Roberts',
                    job_title: 'Operations Manager',
                    email: 'm.roberts@globalmfg.com',
                    phone: '555-0234-5678',
                    industry: 'manufacturing',
                    employees: '1000+',
                    country: 'Germany',
                    selected_plan: 'advanced',
                    modules: ['recruitment', 'onboarding', 'performance', 'time_attendance', 'leave', 'payroll'],
                    message: 'Enterprise-level HR solution needed for multiple locations',
                    status: 'converted',
                    timestamp: new Date(Date.now() - 259200000).toISOString() // 3 days ago
                }
            ];
            localStorage.setItem('orangehrm_quotes', JSON.stringify(sampleQuotes));
        }

        // Initialize pricing data
        if (!localStorage.getItem('orangehrm_pricing')) {
            const pricingData = {
                starter: {
                    name: 'Starter (Open Source)',
                    price: 'FREE',
                    description: 'Completely FREE & Open-source HR Software ideal for small businesses and start-ups.',
                    target_audience: 'Tech-savvy organisations of 20-50 employees',
                    features: ['Open Source', 'Basic HR Functions', 'Community Support', '20-50 Employees'],
                    available: true
                },
                advanced: {
                    name: 'Advanced (Enterprise)',
                    pricing_model: 'Per Employee Per Month (PEPM)',
                    base_price: 4.00,
                    description: 'Enterprise-grade HR solution with implementation services, SLAs, and richer functionality.',
                    free_trial: '30-day free trial available',
                    features: ['Enterprise Features', 'Unlimited Employees', 'Priority Support', 'Implementation Services'],
                    available: true
                }
            };
            localStorage.setItem('orangehrm_pricing', JSON.stringify(pricingData));
        }

        // Initialize modules data
        if (!localStorage.getItem('orangehrm_modules')) {
            const modulesData = [
                {
                    id: 'recruitment',
                    name: 'Recruitment',
                    price: 1.50,
                    description: 'Streamline hiring with an advanced ATS',
                    starter: false,
                    advanced: true
                },
                {
                    id: 'onboarding',
                    name: 'Onboarding',
                    price: 1.00,
                    description: 'Welcome new hires with a smooth, engaging start',
                    starter: false,
                    advanced: true
                },
                {
                    id: 'performance',
                    name: 'Performance',
                    price: 2.00,
                    description: 'Performance management and reviews',
                    starter: false,
                    advanced: true
                },
                {
                    id: 'time_attendance',
                    name: 'Time & Attendance',
                    price: 1.75,
                    description: 'Time tracking and attendance management',
                    starter: false,
                    advanced: true
                },
                {
                    id: 'leave',
                    name: 'Leave Management',
                    price: 1.25,
                    description: 'PTO and absence tracking',
                    starter: false,
                    advanced: true
                },
                {
                    id: 'payroll',
                    name: 'Payroll',
                    price: 2.50,
                    description: 'Payroll processing and management',
                    starter: false,
                    advanced: true
                }
            ];
            localStorage.setItem('orangehrm_modules', JSON.stringify(modulesData));
        }

        // Initialize analytics data
        if (!localStorage.getItem('orangehrm_analytics')) {
            const analyticsData = {
                total_users: 5000000,
                active_users: 5000000,
                countries: 100,
                leave_requests: 10000000,
                operating_vacancies: 500000,
                conversion_rate: 23.5,
                avg_response_time: 4.2,
                monthly_growth: 12.3
            };
            localStorage.setItem('orangehrm_analytics', JSON.stringify(analyticsData));
        }

        // Initialize notifications
        if (!localStorage.getItem('orangehrm_notifications')) {
            const notifications = [
                {
                    id: this.generateId(),
                    type: 'new_quote',
                    message: 'New quote request from Tech Corp Solutions',
                    data: null,
                    timestamp: new Date(Date.now() - 3600000).toISOString(), // 1 hour ago
                    read: false
                },
                {
                    id: this.generateId(),
                    type: 'quote_updated',
                    message: 'StartUp Innovations quote status updated to contacted',
                    data: null,
                    timestamp: new Date(Date.now() - 7200000).toISOString(), // 2 hours ago
                    read: false
                }
            ];
            localStorage.setItem('orangehrm_notifications', JSON.stringify(notifications));
        }
    }

    // Generate unique ID
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }

    // Get all quotes
    getQuotes() {
        return JSON.parse(localStorage.getItem('orangehrm_quotes') || '[]');
    }

    // Get pricing data
    getPricing() {
        return JSON.parse(localStorage.getItem('orangehrm_pricing') || '{}');
    }

    // Update pricing data
    updatePricing(planType, pricingData) {
        const pricing = this.getPricing();
        pricing[planType] = { ...pricing[planType], ...pricingData };
        localStorage.setItem('orangehrm_pricing', JSON.stringify(pricing));
        return pricing[planType];
    }

    // Get modules data
    getModules() {
        return JSON.parse(localStorage.getItem('orangehrm_modules') || '[]');
    }

    // Update module
    updateModule(moduleId, moduleData) {
        const modules = this.getModules();
        const moduleIndex = modules.findIndex(m => m.id === moduleId);
        
        if (moduleIndex !== -1) {
            modules[moduleIndex] = { ...modules[moduleIndex], ...moduleData };
            localStorage.setItem('orangehrm_modules', JSON.stringify(modules));
            return modules[moduleIndex];
        }
        return null;
    }

    // Add new module
    addModule(moduleData) {
        const modules = this.getModules();
        const newModule = {
            id: this.generateId(),
            ...moduleData
        };
        modules.push(newModule);
        localStorage.setItem('orangehrm_modules', JSON.stringify(modules));
        return newModule;
    }

    // Get analytics data
    getAnalytics() {
        return JSON.parse(localStorage.getItem('orangehrm_analytics') || '{}');
    }

    // Update analytics
    updateAnalytics(analyticsData) {
        const analytics = this.getAnalytics();
        const updatedAnalytics = { ...analytics, ...analyticsData };
        localStorage.setItem('orangehrm_analytics', JSON.stringify(updatedAnalytics));
        return updatedAnalytics;
    }

    // Get notifications
    getNotifications() {
        return JSON.parse(localStorage.getItem('orangehrm_notifications') || '[]');
    }

    // Add notification
    addNotification(type, message, data = null) {
        const notifications = this.getNotifications();
        const newNotification = {
            id: this.generateId(),
            type,
            message,
            data,
            timestamp: new Date().toISOString(),
            read: false
        };
        notifications.unshift(newNotification); // Add to beginning
        
        // Keep only last 50 notifications
        if (notifications.length > 50) {
            notifications.splice(50);
        }
        
        localStorage.setItem('orangehrm_notifications', JSON.stringify(notifications));
        return newNotification;
    }

    // Mark notification as read
    markNotificationRead(notificationId) {
        const notifications = this.getNotifications();
        const notificationIndex = notifications.findIndex(n => n.id === notificationId);
        
        if (notificationIndex !== -1) {
            notifications[notificationIndex].read = true;
            localStorage.setItem('orangehrm_notifications', JSON.stringify(notifications));
            return notifications[notificationIndex];
        }
        return null;
    }

    // Mark all notifications as read
    markAllNotificationsRead() {
        const notifications = this.getNotifications();
        notifications.forEach(n => n.read = true);
        localStorage.setItem('orangehrm_notifications', JSON.stringify(notifications));
        return notifications;
    }

    // Get unread notifications count
    getUnreadNotificationsCount() {
        const notifications = this.getNotifications();
        return notifications.filter(n => !n.read).length;
    }

    // Get quote statistics
    getQuoteStatistics() {
        const quotes = this.getQuotes();
        return {
            pending: quotes.filter(q => q.status === 'pending').length,
            contacted: quotes.filter(q => q.status === 'contacted').length,
            converted: quotes.filter(q => q.status === 'converted').length,
            total: quotes.length
        };
    }

    // Get plan popularity statistics
    getPlanStatistics() {
        const quotes = this.getQuotes();
        return {
            starter: quotes.filter(q => q.selected_plan === 'starter').length,
            advanced: quotes.filter(q => q.selected_plan === 'advanced').length
        };
    }

    // Get module popularity statistics
    getModuleStatistics() {
        const quotes = this.getQuotes();
        const moduleCounts = {};
        
        quotes.forEach(quote => {
            if (quote.modules) {
                quote.modules.forEach(module => {
                    moduleCounts[module] = (moduleCounts[module] || 0) + 1;
                });
            }
        });
        
        return moduleCounts;
    }

    // Export data to CSV
    exportToCSV(data, filename) {
        if (!data || data.length === 0) {
            throw new Error('No data to export');
        }

        const headers = Object.keys(data[0]);
        const csvContent = [
            headers.join(','),
            ...data.map(row => 
                headers.map(header => {
                    const value = row[header];
                    return typeof value === 'string' && value.includes(',') 
                        ? `"${value}"` 
                        : value;
                }).join(',')
            )
        ].join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    }

    // Setup event listeners for cross-tab synchronization
    setupEventListeners() {
        // Listen for storage events to sync data across tabs
        window.addEventListener('storage', (e) => {
            if (e.key && e.key.startsWith('orangehrm_')) {
                // Trigger refresh of relevant data
                this.refreshData(e.key);
            }
        });
    }

    // Refresh specific data type
    refreshData(dataType) {
        switch(dataType) {
            case 'orangehrm_quotes':
                this.onQuotesUpdated();
                break;
            case 'orangehrm_notifications':
                this.onNotificationsUpdated();
                break;
            case 'orangehrm_pricing':
                this.onPricingUpdated();
                break;
            case 'orangehrm_modules':
                this.onModulesUpdated();
                break;
            case 'orangehrm_analytics':
                this.onAnalyticsUpdated();
                break;
        }
    }

    // Callback methods for data updates
    onQuotesUpdated() {
        // This will be overridden by the admin panel
        if (window.updateQuotesDisplay) {
            window.updateQuotesDisplay();
        }
    }

    onNotificationsUpdated() {
        // This will be overridden by the admin panel
        if (window.updateNotificationsDisplay) {
            window.updateNotificationsDisplay();
        }
    }

    onPricingUpdated() {
        // This will be overridden by the admin panel
        if (window.updatePricingDisplay) {
            window.updatePricingDisplay();
        }
    }

    onModulesUpdated() {
        // This will be overridden by the admin panel
        if (window.updateModulesDisplay) {
            window.updateModulesDisplay();
        }
    }

    onAnalyticsUpdated() {
        // This will be overridden by the admin panel
        if (window.updateAnalyticsDisplay) {
            window.updateAnalyticsDisplay();
        }
    }

    // Simulate real-time data updates
    startRealTimeSimulation() {
        // Simulate new quote requests every 2 minutes (for demo purposes)
        setInterval(() => {
            if (Math.random() > 0.7) { // 30% chance
                this.simulateNewQuote();
            }
        }, 120000); // 2 minutes
    }

    // Simulate new quote request
    simulateNewQuote() {
        const companies = ['Innovation Labs', 'Digital Solutions', 'Future Tech', 'Smart Systems', 'NextGen Corp'];
        const names = ['Alex Johnson', 'Maria Garcia', 'David Kim', 'Emma Wilson', 'James Brown'];
        const industries = ['technology', 'healthcare', 'finance', 'retail', 'manufacturing'];
        
        const sampleQuote = {
            company: companies[Math.floor(Math.random() * companies.length)],
            name: names[Math.floor(Math.random() * names.length)],
            job_title: 'HR Manager',
            email: `contact${Math.floor(Math.random() * 1000)}@example.com`,
            phone: `555-${Math.floor(Math.random() * 9000) + 1000}`,
            industry: industries[Math.floor(Math.random() * industries.length)],
            employees: ['1-10', '11-50', '51-100', '101-500', '501-1000', '1000+'][Math.floor(Math.random() * 6)],
            country: 'United States',
            selected_plan: Math.random() > 0.3 ? 'advanced' : 'starter',
            modules: Math.random() > 0.5 ? ['recruitment', 'performance'] : [],
            message: 'Interested in your HR solutions',
        };

        this.addQuote(sampleQuote);
    }

    // Sync with backend data
    async syncWithBackend() {
        try {
            const response = await fetch('data_sync.php?action=sync');
            const result = await response.json();
            
            if (result.success) {
                console.log('Backend sync successful:', result);
                
                // Load updated data from backend
                await this.loadFromBackend();
            }
        } catch (error) {
            console.log('Backend sync failed, using localStorage only:', error);
        }
    }

    // Load data from backend
    async loadFromBackend() {
        try {
            const response = await fetch('data_sync.php?action=get_quotes');
            const result = await response.json();
            
            if (result.success && result.data) {
                // Update localStorage with backend data
                localStorage.setItem('orangehrm_quotes', JSON.stringify(result.data));
                
                // Trigger display update
                this.onQuotesUpdated();
            }
        } catch (error) {
            console.log('Failed to load from backend:', error);
        }
    }

    // Override addQuote to also save to backend
    addQuote(quoteData) {
        const quotes = this.getQuotes();
        const newQuote = {
            id: this.generateId(),
            ...quoteData,
            status: 'pending',
            timestamp: new Date().toISOString()
        };
        quotes.push(newQuote);
        localStorage.setItem('orangehrm_quotes', JSON.stringify(quotes));
        
        // Add notification
        this.addNotification('new_quote', `New quote request from ${quoteData.company}`, newQuote);
        
        // Try to sync with backend
        this.syncWithBackend();
        
        return newQuote;
    }

    // Override updateQuoteStatus to also update backend
    async updateQuoteStatus(quoteId, newStatus) {
        const quotes = this.getQuotes();
        const quoteIndex = quotes.findIndex(q => q.id === quoteId);
        
        if (quoteIndex !== -1) {
            quotes[quoteIndex].status = newStatus;
            localStorage.setItem('orangehrm_quotes', JSON.stringify(quotes));
            
            // Try to update backend
            try {
                const response = await fetch('data_sync.php?action=update_status', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        id: quoteId,
                        status: newStatus
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    console.log('Backend status update successful');
                }
            } catch (error) {
                console.log('Backend status update failed:', error);
            }
            
            // Add notification
            this.addNotification('quote_updated', `${quotes[quoteIndex].company} quote status updated to ${newStatus}`, quotes[quoteIndex]);
            
            return quotes[quoteIndex];
        }
        return null;
    }

    // Override deleteQuote to also delete from backend
    async deleteQuote(quoteId) {
        const quotes = this.getQuotes();
        const updatedQuotes = quotes.filter(q => q.id !== quoteId);
        localStorage.setItem('orangehrm_quotes', JSON.stringify(updatedQuotes));
        
        // Try to delete from backend
        try {
            const response = await fetch('data_sync.php?action=delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id: quoteId
                })
            });
            
            const result = await response.json();
            if (result.success) {
                console.log('Backend deletion successful');
            }
        } catch (error) {
            console.log('Backend deletion failed:', error);
        }
        
        return true;
    }
}

// Initialize the data manager
window.dataManager = new OrangeHRMDataManager();

// Make it available globally
window.OrangeHRMDataManager = OrangeHRMDataManager;
