<?php
require_once 'config/database.php';
requireAdmin(); // Ensure only admins can access this page

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Enhanced Dashboard</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Dashboard</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Demo Toast Notifications -->
            <div class="row mb-3">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Toast Notifications Demo</h3>
                        </div>
                        <div class="card-body">
                            <button class="btn btn-success" onclick="showToastDemo('success')">Success Toast</button>
                            <button class="btn btn-info" onclick="showToastDemo('info')">Info Toast</button>
                            <button class="btn btn-warning" onclick="showToastDemo('warning')">Warning Toast</button>
                            <button class="btn btn-danger" onclick="showToastDemo('error')">Error Toast</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Enhanced Statistics Cards -->
            <div class="row">
                <div class="col-12 col-sm-6 col-md-3">
                    <div id="stat-members"></div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div id="stat-events"></div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div id="stat-income"></div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div id="stat-pending"></div>
                </div>
            </div>

            <!-- Dashboard Widgets Row -->
            <div class="row">
                <!-- Chart Widget -->
                <div class="col-md-8">
                    <div id="member-growth-chart"></div>
                </div>
                
                <!-- Quick Actions -->
                <div class="col-md-4">
                    <div id="quick-actions"></div>
                </div>
            </div>

            <!-- Second Widget Row -->
            <div class="row">
                <!-- Progress Widget -->
                <div class="col-md-6">
                    <div id="progress-widget"></div>
                </div>
                
                <!-- Activity Feed -->
                <div class="col-md-6">
                    <div id="activity-feed"></div>
                </div>
            </div>

            <!-- Enhanced Timeline -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Activity Timeline</h3>
                            <div class="card-tools">
                                <button class="btn btn-sm btn-primary" onclick="refreshTimeline()">
                                    <i class="fas fa-sync-alt"></i> Refresh
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div id="kso-timeline"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize enhanced dashboard components
    initializeDashboard();
    
    // Initialize timeline
    initializeTimeline();
    
    // Load dashboard data
    loadDashboardData();
});

function initializeDashboard() {
    // Create stat cards
    window.ksoWidgets.createStatCard('stat-members', {
        value: '250',
        label: 'Total Members',
        change: '+12%',
        changeType: 'positive',
        gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    });

    window.ksoWidgets.createStatCard('stat-events', {
        value: '15',
        label: 'Active Events',
        change: '+5%',
        changeType: 'positive',
        gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)'
    });

    window.ksoWidgets.createStatCard('stat-income', {
        value: '₹50,000',
        label: 'Total Income',
        change: '+8%',
        changeType: 'positive',
        gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
    });

    window.ksoWidgets.createStatCard('stat-pending', {
        value: '8',
        label: 'Pending Approvals',
        change: '-2%',
        changeType: 'negative',
        gradient: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)'
    });

    // Create chart widget
    const chartData = {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [{
            label: 'New Members',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 2,
            fill: true
        }]
    };

    window.ksoWidgets.createChartWidget('member-growth-chart', 'line', chartData, {
        title: 'Member Growth Trend',
        chartOptions: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: 'Monthly Member Registration'
                }
            }
        }
    });

    // Create quick actions
    const quickActions = [
        { label: 'Add Member', icon: 'fas fa-user-plus', href: 'member-registration.php' },
        { label: 'Create Event', icon: 'fas fa-calendar-plus', href: 'events.php' },
        { label: 'View Reports', icon: 'fas fa-chart-bar', href: 'reports.php' },
        { label: 'Send Notification', icon: 'fas fa-bell', href: 'notifications.php' },
        { label: 'Manage Finance', icon: 'fas fa-coins', href: 'finance.php' },
        { label: 'System Settings', icon: 'fas fa-cog', href: 'settings.php' }
    ];

    window.ksoWidgets.createQuickActions('quick-actions', quickActions, {
        title: 'Quick Actions'
    });

    // Create progress widget
    const progressItems = [
        { label: 'Membership Goal', value: 75, color: '#28a745' },
        { label: 'Event Attendance', value: 60, color: '#007bff' },
        { label: 'Fee Collection', value: 90, color: '#ffc107' },
        { label: 'Document Approval', value: 45, color: '#dc3545' }
    ];

    window.ksoWidgets.createProgressWidget('progress-widget', progressItems, {
        title: 'Progress Overview'
    });

    // Create activity feed
    const activities = [
        {
            title: 'New Member Registration',
            description: 'John Doe registered as a new member',
            time: '2 minutes ago',
            icon: 'fas fa-user-plus',
            color: '#28a745'
        },
        {
            title: 'Event Created',
            description: 'Cultural Night event scheduled for next week',
            time: '1 hour ago',
            icon: 'fas fa-calendar-plus',
            color: '#007bff'
        },
        {
            title: 'Payment Received',
            description: 'Membership fee payment of ₹1,000 received',
            time: '3 hours ago',
            icon: 'fas fa-credit-card',
            color: '#ffc107'
        },
        {
            title: 'Document Uploaded',
            description: 'Annual report uploaded to documents section',
            time: '1 day ago',
            icon: 'fas fa-file-upload',
            color: '#17a2b8'
        }
    ];

    window.ksoWidgets.createActivityFeed('activity-feed', activities, {
        title: 'Recent Activity'
    });
}

function initializeTimeline() {
    const timelineData = [
        {
            title: 'Member Registration Approved',
            description: 'John Doe\'s membership application has been approved and activated.',
            type: 'success',
            icon: 'fas fa-check-circle',
            time: '10:30 AM',
            date: new Date(),
            user: {
                name: 'Admin User',
                avatar: 'dist/img/user-placeholder.png'
            }
        },
        {
            title: 'Event Registration Opened',
            description: 'Registration for Cultural Night 2024 is now open for all members.',
            type: 'info',
            icon: 'fas fa-calendar-alt',
            time: '09:15 AM',
            date: new Date(),
            user: {
                name: 'Event Manager',
                avatar: 'dist/img/user-placeholder.png'
            }
        },
        {
            title: 'Payment Reminder Sent',
            description: 'Membership fee payment reminders sent to 25 members.',
            type: 'warning',
            icon: 'fas fa-exclamation-triangle',
            time: '08:45 AM',
            date: new Date(Date.now() - 86400000), // Yesterday
            user: {
                name: 'Finance Team',
                avatar: 'dist/img/user-placeholder.png'
            }
        },
        {
            title: 'System Backup Completed',
            description: 'Daily system backup completed successfully with all data secured.',
            type: 'success',
            icon: 'fas fa-database',
            time: '03:00 AM',
            date: new Date(Date.now() - 86400000), // Yesterday
            user: {
                name: 'System',
                avatar: 'dist/img/user-placeholder.png'
            }
        }
    ];

    window.ksoTimeline = new KSOTimeline('kso-timeline', {
        showIcons: true,
        showTime: true,
        showDates: true,
        groupByDate: true,
        animations: true
    });

    window.ksoTimeline.loadData(timelineData);
}

function loadDashboardData() {
    // Fetch real dashboard statistics from API
    fetch('api/dashboard/fetch_dashboard_stats.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update stat cards with real data
                window.ksoWidgets.updateStatCard('stat-members', data.data.total_members || '0', data.data.member_growth || '0%', 'positive');
                window.ksoWidgets.updateStatCard('stat-events', data.data.total_events || '0', data.data.event_growth || '0%', 'positive');
                window.ksoWidgets.updateStatCard('stat-income', '₹' + (data.data.total_income || '0'), data.data.income_growth || '0%', 'positive');
                window.ksoWidgets.updateStatCard('stat-pending', data.data.pending_registrations || '0', data.data.pending_growth || '0%', 'positive');
                
                // Show success notification
                window.ksoToast.success('Dashboard data loaded successfully!', {
                    title: 'Data Updated',
                    duration: 3000
                });
            } else {
                // Show error notification
                window.ksoToast.error('Failed to load dashboard data: ' + (data.message || 'Unknown error'), {
                    title: 'Data Load Error',
                    duration: 5000
                });
            }
        })
        .catch(error => {
            console.error('Error loading dashboard data:', error);
            window.ksoToast.error('Failed to connect to server', {
                title: 'Connection Error',
                duration: 5000
            });
        });
}

function showToastDemo(type) {
    const messages = {
        success: 'Operation completed successfully!',
        info: 'Here is some important information.',
        warning: 'Please review this carefully.',
        error: 'An error occurred while processing.'
    };

    window.ksoToast[type](messages[type], {
        title: `${type.charAt(0).toUpperCase() + type.slice(1)} Demo`,
        duration: 5000
    });
}

function refreshTimeline() {
    window.ksoToast.info('Refreshing timeline...', {
        title: 'Loading',
        duration: 2000
    });
    
    // Simulate refresh
    setTimeout(() => {
        window.ksoTimeline.refresh();
        window.ksoToast.success('Timeline refreshed!', {
            title: 'Success',
            duration: 3000
        });
    }, 1000);
}

// Theme change handler
window.addEventListener('themeChanged', function(event) {
    const theme = event.detail.theme;
    window.ksoToast.info(`Switched to ${theme} mode`, {
        title: 'Theme Changed',
        duration: 3000
    });
});
</script>

<?php
require_once 'templates/footer.php';
?>
