<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is admin
adminOnly();

$user = getUserContext();
$page_title = 'Analytics Dashboard';

include 'includes/admin_header.php';
?>

<div class="analytics-dashboard">
    <!-- Overview Stats -->
    <div class="dashboard-stats" id="overview-stats">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-users"></i>
            </div>
            <div class="stat-info">
                <h3 id="total-users">-</h3>
                <p>Total Users</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-graduation-cap"></i>
            </div>
            <div class="stat-info">
                <h3 id="total-courses">-</h3>
                <p>Total Courses</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-user-check"></i>
            </div>
            <div class="stat-info">
                <h3 id="total-enrollments">-</h3>
                <p>Total Enrollments</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-user-clock"></i>
            </div>
            <div class="stat-info">
                <h3 id="active-users">-</h3>
                <p>Active Users (30d)</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-dollar-sign"></i>
            </div>
            <div class="stat-info">
                <h3 id="total-revenue">$0</h3>
                <p>Total Revenue</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-info">
                <h3 id="completion-rate">0%</h3>
                <p>Completion Rate</p>
            </div>
        </div>
    </div>

    <!-- Charts Section -->
    <div class="analytics-charts">
        <div class="chart-container">
            <h3>User Growth Trend</h3>
            <canvas id="user-growth-chart"></canvas>
        </div>
        <div class="chart-container">
            <h3>Course Popularity</h3>
            <canvas id="course-popularity-chart"></canvas>
        </div>
        <div class="chart-container">
            <h3>Revenue Trend</h3>
            <canvas id="revenue-trend-chart"></canvas>
        </div>
    </div>

    <!-- Recent Activities -->
    <div class="dashboard-section">
        <h2>Recent User Activities</h2>
        <div class="activity-list" id="recent-activities">
            <div class="loading">Loading activities...</div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="dashboard-section">
        <h2>Analytics Tools</h2>
        <div class="quick-actions">
            <a href="logs.php" class="action-card">
                <i class="fas fa-history"></i>
                <span>System Logs</span>
            </a>
            <a href="#" onclick="exportData('user_data')" class="action-card">
                <i class="fas fa-download"></i>
                <span>Export Users</span>
            </a>
            <a href="#" onclick="exportData('course_data')" class="action-card">
                <i class="fas fa-file-export"></i>
                <span>Export Courses</span>
            </a>
            <a href="#" onclick="showComplianceReport()" class="action-card">
                <i class="fas fa-shield-alt"></i>
                <span>Compliance Report</span>
            </a>
            <a href="#" onclick="showRealTimeStats()" class="action-card">
                <i class="fas fa-tachometer-alt"></i>
                <span>Real-time Stats</span>
            </a>
        </div>
    </div>
</div>

<!-- Compliance Report Modal -->
<div id="compliance-modal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Compliance Report</h3>
            <span class="modal-close" onclick="closeModal('compliance-modal')">&times;</span>
        </div>
        <div class="modal-body" id="compliance-content">
            <div class="loading">Generating compliance report...</div>
        </div>
    </div>
</div>

<!-- Real-time Stats Modal -->
<div id="realtime-modal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Real-time Statistics</h3>
            <span class="modal-close" onclick="closeModal('realtime-modal')">&times;</span>
        </div>
        <div class="modal-body" id="realtime-content">
            <div class="loading">Loading real-time statistics...</div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let userGrowthChart, coursePopularityChart, revenueTrendChart;

document.addEventListener('DOMContentLoaded', function() {
    loadDashboardStats();
    initializeCharts();
});

function loadDashboardStats() {
    fetch('../api/analytics/index.php?action=dashboard_stats')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateOverviewStats(data.data.overview);
                updateCharts(data.data.charts);
                updateRecentActivities(data.data.recent_activities);
            } else {
                console.error('Failed to load dashboard stats:', data.message);
            }
        })
        .catch(error => {
            console.error('Error loading dashboard stats:', error);
        });
}

function updateOverviewStats(overview) {
    document.getElementById('total-users').textContent = overview.total_users;
    document.getElementById('total-courses').textContent = overview.total_courses;
    document.getElementById('total-enrollments').textContent = overview.total_enrollments;
    document.getElementById('active-users').textContent = overview.active_users;
    document.getElementById('total-revenue').textContent = '$' + overview.total_revenue;
    document.getElementById('completion-rate').textContent = overview.completion_rate + '%';
}

function initializeCharts() {
    // User Growth Chart
    const userGrowthCtx = document.getElementById('user-growth-chart').getContext('2d');
    userGrowthChart = new Chart(userGrowthCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'New Users',
                data: [],
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // Course Popularity Chart
    const coursePopularityCtx = document.getElementById('course-popularity-chart').getContext('2d');
    coursePopularityChart = new Chart(coursePopularityCtx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: [{
                label: 'Enrollments',
                data: [],
                backgroundColor: '#28a745',
                borderColor: '#28a745',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // Revenue Trend Chart
    const revenueTrendCtx = document.getElementById('revenue-trend-chart').getContext('2d');
    revenueTrendChart = new Chart(revenueTrendCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Revenue ($)',
                data: [],
                borderColor: '#ffc107',
                backgroundColor: 'rgba(255, 193, 7, 0.1)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
            }
        }
    });
}

function updateCharts(charts) {
    // Update User Growth Chart
    if (charts.user_growth && userGrowthChart) {
        userGrowthChart.data.labels = charts.user_growth.map(item => item.date);
        userGrowthChart.data.datasets[0].data = charts.user_growth.map(item => item.count);
        userGrowthChart.update();
    }

    // Update Course Popularity Chart
    if (charts.course_popularity && coursePopularityChart) {
        coursePopularityChart.data.labels = charts.course_popularity.map(item => item.title.substring(0, 20) + (item.title.length > 20 ? '...' : ''));
        coursePopularityChart.data.datasets[0].data = charts.course_popularity.map(item => item.enrollments);
        coursePopularityChart.update();
    }

    // Update Revenue Trend Chart
    if (charts.revenue_trend && revenueTrendChart) {
        revenueTrendChart.data.labels = charts.revenue_trend.map(item => item.date);
        revenueTrendChart.data.datasets[0].data = charts.revenue_trend.map(item => item.revenue);
        revenueTrendChart.update();
    }
}

function updateRecentActivities(activities) {
    const container = document.getElementById('recent-activities');
    if (!activities || activities.length === 0) {
        container.innerHTML = '<p class="no-activity">No recent activities found.</p>';
        return;
    }

    container.innerHTML = activities.map(activity => `
        <div class="activity-item">
            <div class="activity-icon">
                <i class="fas fa-circle"></i>
            </div>
            <div class="activity-content">
                <p>${activity.action_description}</p>
                <small>
                    <strong>${activity.username}</strong> -
                    ${new Date(activity.created_at).toLocaleDateString()}
                </small>
            </div>
        </div>
    `).join('');
}

function exportData(type) {
    const link = document.createElement('a');
    link.href = `../api/analytics/index.php?action=export_data&type=${type}&format=csv`;
    link.download = `${type}_export.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function showComplianceReport() {
    const modal = document.getElementById('compliance-modal');
    const content = document.getElementById('compliance-content');

    modal.style.display = 'block';
    content.innerHTML = '<div class="loading">Generating compliance report...</div>';

    fetch('../api/analytics/index.php?action=compliance_report&type=user_activity')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                content.innerHTML = generateComplianceReportHTML(data.data);
            } else {
                content.innerHTML = '<p class="error">Failed to generate compliance report.</p>';
            }
        })
        .catch(error => {
            content.innerHTML = '<p class="error">Error generating compliance report.</p>';
        });
}

function generateComplianceReportHTML(data) {
    return `
        <div class="compliance-report">
            <h4>User Activity Report</h4>
            <div class="report-summary">
                <p><strong>Total Users:</strong> ${data.length}</p>
                <p><strong>Report Generated:</strong> ${new Date().toLocaleString()}</p>
            </div>
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Total Activities</th>
                        <th>Last Activity</th>
                    </tr>
                </thead>
                <tbody>
                    ${data.map(user => `
                        <tr>
                            <td>${user.username}</td>
                            <td>${user.email}</td>
                            <td>${user.role}</td>
                            <td>${user.total_activities}</td>
                            <td>${user.last_activity ? new Date(user.last_activity).toLocaleDateString() : 'Never'}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

function showRealTimeStats() {
    const modal = document.getElementById('realtime-modal');
    const content = document.getElementById('realtime-content');

    modal.style.display = 'block';
    content.innerHTML = '<div class="loading">Loading real-time statistics...</div>';

    fetch('../api/analytics/index.php?action=real_time_stats')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                content.innerHTML = generateRealTimeStatsHTML(data.data);
            } else {
                content.innerHTML = '<p class="error">Failed to load real-time statistics.</p>';
            }
        })
        .catch(error => {
            content.innerHTML = '<p class="error">Error loading real-time statistics.</p>';
        });
}

function generateRealTimeStatsHTML(data) {
    return `
        <div class="realtime-stats">
            <div class="stat-grid">
                <div class="stat-item">
                    <h4>${data.active_users}</h4>
                    <p>Active Users (5 min)</p>
                </div>
                <div class="stat-item">
                    <h4>${data.ongoing_exams}</h4>
                    <p>Ongoing Exams</p>
                </div>
                <div class="stat-item">
                    <h4>${data.system_load.active_sessions}</h4>
                    <p>Active Sessions</p>
                </div>
                <div class="stat-item">
                    <span class="status-indicator status-${data.system_load.status}"></span>
                    <p>System Load: ${data.system_load.status.toUpperCase()}</p>
                </div>
            </div>
            <h4>Recent Activities</h4>
            <div class="recent-activities-list">
                ${data.recent_activities.map(activity => `
                    <div class="activity-item">
                        <small>${activity.action_description} by ${activity.username}</small>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// Close modal when clicking outside
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
}
</script>

<style>
.analytics-dashboard {
    padding: 20px;
}

.dashboard-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #007bff;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
}

.stat-info h3 {
    margin: 0;
    font-size: 28px;
    font-weight: bold;
    color: #333;
}

.stat-info p {
    margin: 5px 0 0 0;
    color: #666;
    font-size: 14px;
}

.analytics-charts {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.chart-container {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-container h3 {
    margin-top: 0;
    margin-bottom: 15px;
    color: #333;
}

.dashboard-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.dashboard-section h2 {
    margin-top: 0;
    margin-bottom: 15px;
    color: #333;
}

.quick-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
}

.action-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    text-decoration: none;
    color: #333;
    transition: all 0.3s ease;
}

.action-card:hover {
    background: #007bff;
    color: white;
    transform: translateY(-2px);
}

.action-card i {
    font-size: 24px;
    margin-bottom: 10px;
}

.action-card span {
    font-size: 14px;
    text-align: center;
}

.activity-list {
    max-height: 300px;
    overflow-y: auto;
}

.activity-item {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
}

.activity-item:last-child {
    border-bottom: none;
}

.activity-icon {
    color: #007bff;
    margin-top: 2px;
}

.activity-content p {
    margin: 0;
    color: #333;
}

.activity-content small {
    color: #666;
}

.loading {
    text-align: center;
    padding: 20px;
    color: #666;
}

.error {
    color: #dc3545;
    text-align: center;
    padding: 20px;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 5% auto;
    padding: 0;
    border-radius: 8px;
    width: 90%;
    max-width: 800px;
    max-height: 80vh;
    overflow-y: auto;
}

.modal-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
}

.modal-close {
    font-size: 28px;
    font-weight: bold;
    color: #aaa;
    cursor: pointer;
}

.modal-close:hover {
    color: #000;
}

.modal-body {
    padding: 20px;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 15px;
}

.data-table th,
.data-table td {
    padding: 8px 12px;
    text-align: left;
    border-bottom: 1px solid #eee;
}

.data-table th {
    background: #f8f9fa;
    font-weight: bold;
}

.stat-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.stat-item {
    text-align: center;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

.stat-item h4 {
    margin: 0 0 5px 0;
    font-size: 24px;
    color: #007bff;
}

.stat-item p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.status-indicator {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 5px;
}

.status-low { background: #28a745; }
.status-medium { background: #ffc107; }
.status-high { background: #dc3545; }

.recent-activities-list {
    max-height: 200px;
    overflow-y: auto;
}

.recent-activities-list .activity-item {
    padding: 5px 0;
    border-bottom: 1px solid #f0f0f0;
}

.recent-activities-list .activity-item:last-child {
    border-bottom: none;
}
</style>

<?php include 'includes/admin_footer.php'; ?>