// Neuroconnect Therapy Centre Management System - Main Application Logic

class NeuroConnectApp {
    constructor() {
        this.currentSection = 'dashboard';
        this.data = {
            staff: JSON.parse(localStorage.getItem('staff')) || [],
            patients: JSON.parse(localStorage.getItem('patients')) || [],
            expenses: JSON.parse(localStorage.getItem('expenses')) || [],
            schedules: JSON.parse(localStorage.getItem('schedules')) || [],
            stock: JSON.parse(localStorage.getItem('stock')) || [],
            directors: this.getDefaultDirectors() // Always use fresh directors data
        };
        
        // Update localStorage with fresh directors data
        localStorage.setItem('directors', JSON.stringify(this.data.directors));
        
        this.init();
    }

    init() {
        this.setupNavigation();
        this.loadDashboard();
        this.setupEventListeners();
    }

    getDefaultDirectors() {
        return [
            { id: 1, name: 'Dr. Achieng Fwaya', position: 'CEO', phone: '0728420815' },
            { id: 2, name: 'Dr. Felix Tindi', position: 'Finance', phone: '0725748918' },
            { id: 3, name: 'Dr. Tom Okwaroh', position: 'HR', phone: '0722619115' },
            { id: 4, name: 'Mr. George Ougo', position: 'Branding', phone: '0723250979' },
            { id: 5, name: 'Mr. Dominic Omollo', position: 'Director', phone: '0724501143' }
        ];
    }

    setupNavigation() {
        const navLinks = document.querySelectorAll('.nav-link');
        const actionButtons = document.querySelectorAll('.action-btn');

        navLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const section = link.getAttribute('data-section');
                this.showSection(section);
            });
        });

        actionButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                const section = button.getAttribute('data-section');
                if (section) {
                    this.showSection(section);
                }
            });
        });
    }

    showSection(sectionId) {
        // Update navigation
        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
        });
        document.querySelector(`[data-section="${sectionId}"]`).classList.add('active');

        // Update content
        document.querySelectorAll('.content-section').forEach(section => {
            section.classList.remove('active');
        });
        document.getElementById(sectionId).classList.add('active');

        // Update page title
        const titles = {
            dashboard: 'Dashboard',
            staff: 'Staff Management',
            expenses: 'Office Expenses',
            patients: 'Patient Records',
            schedule: 'Therapy Schedule',
            stock: 'Stock Control',
            reports: 'Reports'
        };
        document.getElementById('page-title').textContent = titles[sectionId] || sectionId;

        this.currentSection = sectionId;
        this.loadSectionData(sectionId);
    }

    loadSectionData(sectionId) {
        switch (sectionId) {
            case 'dashboard':
                this.loadDashboard();
                break;
            case 'staff':
                this.loadStaffSection();
                break;
            case 'expenses':
                this.loadExpensesSection();
                break;
            case 'patients':
                this.loadPatientsSection();
                break;
            case 'schedule':
                this.loadScheduleSection();
                break;
            case 'stock':
                this.loadStockSection();
                break;
            case 'reports':
                this.loadReportsSection();
                break;
        }
    }

    loadDashboard() {
        // Update statistics
        document.getElementById('total-patients').textContent = this.data.patients.length;
        document.getElementById('total-staff').textContent = this.data.staff.length;
        
        // Calculate monthly revenue and expenses
        const currentMonth = new Date().getMonth();
        const currentYear = new Date().getFullYear();
        
        const monthlyExpenses = this.data.expenses
            .filter(expense => {
                const expenseDate = new Date(expense.date);
                return expenseDate.getMonth() === currentMonth && expenseDate.getFullYear() === currentYear;
            })
            .reduce((total, expense) => total + parseFloat(expense.amount || 0), 0);
        
        document.getElementById('monthly-expenses').textContent = this.formatCurrency(monthlyExpenses);
        
        // For revenue, we'll calculate based on therapy sessions (simplified)
        const monthlyRevenue = this.data.schedules
            .filter(schedule => {
                const scheduleDate = new Date(schedule.date);
                return scheduleDate.getMonth() === currentMonth && scheduleDate.getFullYear() === currentYear;
            })
            .length * 7500; // Assuming average Ksh 7,500 per session
        
        document.getElementById('monthly-revenue').textContent = this.formatCurrency(monthlyRevenue);

        // Load directors
        this.loadDirectors();
    }

    loadDirectors() {
        const directorsContainer = document.getElementById('directors-list');
        const filter = document.getElementById('director-filter');
        
        const filteredDirectors = filter.value ? 
            this.data.directors.filter(director => director.position === filter.value) : 
            this.data.directors;

        directorsContainer.innerHTML = filteredDirectors.map(director => `
            <div class="director-card">
                <h4>${director.name}</h4>
                <div class="position">${this.getPositionFullName(director.position)}</div>
                <div> ${director.phone}</div>
            </div>
        `).join('');

        // Setup filter event listener
        filter.addEventListener('change', () => this.loadDirectors());
    }

    getPositionFullName(position) {
        const positions = {
            'CEO': 'C.E.O',
            'HR': 'Director - HR & Welfare',
            'Finance': 'Director - Finance',
            'Director': 'Director',
            'Branding': 'Director - Branding'
        };
        return positions[position] || position;
    }

    loadStaffSection() {
        if (typeof loadStaffData === 'function') {
            loadStaffData();
        }
    }

    loadExpensesSection() {
        if (typeof loadExpensesData === 'function') {
            loadExpensesData();
        }
    }

    loadPatientsSection() {
        if (typeof loadPatientsData === 'function') {
            loadPatientsData();
        }
    }

    loadScheduleSection() {
        if (typeof loadScheduleData === 'function') {
            loadScheduleData();
        }
    }

    loadStockSection() {
        if (typeof loadStockData === 'function') {
            loadStockData();
        }
    }

    loadReportsSection() {
        if (typeof loadReportsData === 'function') {
            loadReportsData();
        }
    }

    setupEventListeners() {
        // Close modal when clicking outside
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-overlay')) {
                this.closeModal();
            }
        });

        // Close modal with Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeModal();
            }
        });
    }

    showModal(modalContent) {
        const overlay = document.getElementById('modal-overlay');
        overlay.innerHTML = modalContent;
        overlay.style.display = 'flex';
    }

    closeModal() {
        const overlay = document.getElementById('modal-overlay');
        overlay.style.display = 'none';
        overlay.innerHTML = '';
    }

    saveData(type, data) {
        this.data[type] = data;
        localStorage.setItem(type, JSON.stringify(data));
        
        // Refresh dashboard if it's currently active
        if (this.currentSection === 'dashboard') {
            this.loadDashboard();
        }
    }

    getData(type) {
        return this.data[type] || [];
    }

    generateId(type) {
        const items = this.getData(type);
        return items.length > 0 ? Math.max(...items.map(item => item.id || 0)) + 1 : 1;
    }

    formatCurrency(amount) {
        return 'Ksh ' + new Intl.NumberFormat('en-KE', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(amount);
    }

    formatDate(date) {
        return new Date(date).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    }

    formatTime(time) {
        return new Date(`2000-01-01T${time}`).toLocaleTimeString('en-US', {
            hour: 'numeric',
            minute: '2-digit',
            hour12: true
        });
    }

    showNotification(message, type = 'success') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
                <span>${message}</span>
            </div>
        `;

        // Add styles
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${type === 'success' ? 'var(--success)' : 'var(--error)'};
            color: white;
            padding: 1rem 1.5rem;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            z-index: 3000;
            animation: slideIn 0.3s ease-out;
        `;

        // Add animation styles
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            .notification-content {
                display: flex;
                align-items: center;
                gap: 0.5rem;
            }
        `;
        document.head.appendChild(style);

        // Add to page
        document.body.appendChild(notification);

        // Remove after 3 seconds
        setTimeout(() => {
            notification.style.animation = 'slideIn 0.3s ease-out reverse';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    exportToCSV(data, filename) {
        const csvContent = this.convertToCSV(data);
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }

    convertToCSV(data) {
        if (data.length === 0) return '';
        
        const headers = Object.keys(data[0]);
        const csvRows = [headers.join(',')];
        
        for (const row of data) {
            const values = headers.map(header => {
                const value = row[header];
                return typeof value === 'string' && value.includes(',') ? `"${value}"` : value;
            });
            csvRows.push(values.join(','));
        }
        
        return csvRows.join('\n');
    }
}

// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.app = new NeuroConnectApp();
});

// Global helper functions
function showAddStaffModal() {
    if (typeof showStaffModal === 'function') {
        showStaffModal();
    }
}

function generatePayroll() {
    if (typeof generateStaffPayroll === 'function') {
        generateStaffPayroll();
    }
}
