<?php
/**
 * SmartThink3 LMS - Admin Dashboard
 * 
 * Main administration interface for the LMS platform
 */

require_once __DIR__ . '/../config/database.php';

// Check if user is logged in and has admin privileges
requireLogin();
requireAnyRole(['admin', 'super_admin']);

// Get database instance
$db = Database::getInstance();

// Get dashboard statistics
$stats = getDashboardStats();

// Get recent activities
$recentActivities = getRecentActivities();

// Get system alerts
$alerts = getSystemAlerts();

function getDashboardStats() {
    global $db;
    
    $stats = [];
    
    // User statistics
    $stats['users'] = $db->get("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
               SUM(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as new
        FROM users
    ");
    
    // Course statistics
    $stats['courses'] = $db->get("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN status = 'published' THEN 1 ELSE 0 END) as published,
               SUM(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as new
        FROM courses
    ");
    
    // Enrollment statistics
    $stats['enrollments'] = $db->get("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
               SUM(CASE WHEN enrollment_date >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as new
        FROM course_enrollments
    ");
    
    // Revenue statistics
    $stats['revenue'] = $db->get("
        SELECT COALESCE(SUM(amount), 0) as total,
               COALESCE(SUM(CASE WHEN paid_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN amount ELSE 0 END), 0) as monthly
        FROM payments
        WHERE payment_status = 'completed'
    ");
    
    // Regional statistics
    $stats['regions'] = $db->getAll("
        SELECT region, COUNT(*) as users
        FROM users
        WHERE status = 'active'
        GROUP BY region
        ORDER BY users DESC
    ");
    
    return $stats;
}

function getRecentActivities() {
    global $db;
    
    return $db->getAll("
        SELECT al.*, u.first_name, u.last_name, u.username
        FROM activity_logs al
        LEFT JOIN users u ON al.user_id = u.id
        ORDER BY al.created_at DESC
        LIMIT 10
    ");
}

function getSystemAlerts() {
    global $db;
    
    $alerts = [];
    
    // Check for pending enrollments
    $pendingEnrollments = $db->get("
        SELECT COUNT(*) as count
        FROM course_enrollments
        WHERE payment_status = 'pending'
        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    
    if ($pendingEnrollments['count'] > 0) {
        $alerts[] = [
            'type' => 'warning',
            'message' => "{$pendingEnrollments['count']} pending enrollments awaiting payment confirmation",
            'icon' => 'clock'
        ];
    }
    
    // Check for failed payments
    $failedPayments = $db->get("
        SELECT COUNT(*) as count
        FROM payments
        WHERE payment_status = 'failed'
        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    
    if ($failedPayments['count'] > 0) {
        $alerts[] = [
            'type' => 'danger',
            'message' => "{$failedPayments['count']} failed payments in the last 24 hours",
            'icon' => 'exclamation-triangle'
        ];
    }
    
    // Check for system errors
    $systemErrors = $db->get("
        SELECT COUNT(*) as count
        FROM activity_logs
        WHERE action LIKE '%error%' OR action LIKE '%failed%'
        AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    
    if ($systemErrors['count'] > 5) {
        $alerts[] = [
            'type' => 'danger',
            'message' => "High number of system errors detected ({$systemErrors['count']})",
            'icon' => 'bug'
        ];
    }
    
    return $alerts;
}

$pageTitle = "Admin Dashboard";
include __DIR__ . '/includes/header.php';
?>

<div class="dashboard-container">
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">Dashboard Overview</h1>
            <p class="text-muted mb-0">Welcome back, <?php echo htmlspecialchars($_SESSION['username']); ?>!</p>
        </div>
        <div>
            <span class="badge bg-success">System Online</span>
            <span class="badge bg-info ms-2"><?php echo date('Y-m-d H:i:s'); ?></span>
        </div>
    </div>

    <!-- System Alerts -->
    <?php if (!empty($alerts)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <?php foreach ($alerts as $alert): ?>
            <div class="alert alert-<?php echo $alert['type']; ?> alert-dismissible fade show" role="alert">
                <i class="fas fa-<?php echo $alert['icon']; ?> me-2"></i>
                <?php echo htmlspecialchars($alert['message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title"><?php echo number_format($stats['users']['total']); ?></h4>
                            <p class="card-text">Total Users</p>
                            <small><?php echo number_format($stats['users']['active']); ?> active</small>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-users fa-2x"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-between">
                    <small>New users: <?php echo number_format($stats['users']['new']); ?></small>
                    <small>Last 30 days</small>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title"><?php echo number_format($stats['courses']['total']); ?></h4>
                            <p class="card-text">Total Courses</p>
                            <small><?php echo number_format($stats['courses']['published']); ?> published</small>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-graduation-cap fa-2x"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-between">
                    <small>New courses: <?php echo number_format($stats['courses']['new']); ?></small>
                    <small>Last 30 days</small>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title"><?php echo number_format($stats['enrollments']['total']); ?></h4>
                            <p class="card-text">Total Enrollments</p>
                            <small><?php echo number_format($stats['enrollments']['completed']); ?> completed</small>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-user-graduate fa-2x"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-between">
                    <small>New enrollments: <?php echo number_format($stats['enrollments']['new']); ?></small>
                    <small>Last 30 days</small>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-4">
            <div class="card bg-warning text-dark">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title">$<?php echo number_format($stats['revenue']['total'], 2); ?></h4>
                            <p class="card-text">Total Revenue</p>
                            <small>This month: $<?php echo number_format($stats['revenue']['monthly'], 2); ?></small>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-dollar-sign fa-2x"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-between">
                    <small>Conversion rate: 3.2%</small>
                    <small>Average</small>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Regional Distribution -->
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">Regional Distribution</h5>
                    <button class="btn btn-sm btn-outline-primary">View Details</button>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php foreach ($stats['regions'] as $region): ?>
                        <div class="col-4 mb-3">
                            <div class="text-center">
                                <div class="h4 mb-1"><?php echo number_format($region['users']); ?></div>
                                <div class="text-muted text-uppercase"><?php echo htmlspecialchars($region['region']); ?></div>
                                <div class="progress mt-2" style="height: 4px;">
                                    <?php 
                                    $totalUsers = array_sum(array_column($stats['regions'], 'users'));
                                    $percentage = ($region['users'] / $totalUsers) * 100;
                                    ?>
                                    <div class="progress-bar" style="width: <?php echo $percentage; ?>%"></div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Activities -->
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">Recent Activities</h5>
                    <button class="btn btn-sm btn-outline-primary">View All</button>
                </div>
                <div class="card-body">
                    <div class="activity-feed">
                        <?php foreach ($recentActivities as $activity): ?>
                        <div class="activity-item">
                            <div class="activity-icon">
                                <i class="fas fa-<?php echo getActivityIcon($activity['action']); ?>"></i>
                            </div>
                            <div class="activity-content">
                                <div class="activity-title">
                                    <?php 
                                    if ($activity['username']) {
                                        echo htmlspecialchars($activity['username']);
                                    } else {
                                        echo 'System';
                                    }
                                    ?>
                                    <span class="text-muted"><?php echo getActivityDescription($activity['action']); ?></span>
                                </div>
                                <div class="activity-time">
                                    <small class="text-muted"><?php echo formatTimeAgo($activity['created_at']); ?></small>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <a href="users.php" class="btn btn-outline-primary w-100 h-100 d-flex flex-column align-items-center justify-content-center">
                                <i class="fas fa-users fa-2x mb-2"></i>
                                <span>Manage Users</span>
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="courses.php" class="btn btn-outline-success w-100 h-100 d-flex flex-column align-items-center justify-content-center">
                                <i class="fas fa-graduation-cap fa-2x mb-2"></i>
                                <span>Manage Courses</span>
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="enrollments.php" class="btn btn-outline-info w-100 h-100 d-flex flex-column align-items-center justify-content-center">
                                <i class="fas fa-user-graduate fa-2x mb-2"></i>
                                <span>Enrollments</span>
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="reports.php" class="btn btn-outline-warning w-100 h-100 d-flex flex-column align-items-center justify-content-center">
                                <i class="fas fa-chart-bar fa-2x mb-2"></i>
                                <span>Reports</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- System Status -->
    <div class="row">
        <div class="col-lg-8 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">System Status</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>Database Connection</span>
                                <span class="badge bg-success">Healthy</span>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>File Storage</span>
                                <span class="badge bg-success">Available</span>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>Email Service</span>
                                <span class="badge bg-success">Active</span>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>WhatsApp API</span>
                                <span class="badge bg-success">Connected</span>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>Payment Gateway</span>
                                <span class="badge bg-success">Active</span>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>CDN Service</span>
                                <span class="badge bg-warning">Limited</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">System Information</h5>
                </div>
                <div class="card-body">
                    <table class="table table-sm">
                        <tr>
                            <td>PHP Version</td>
                            <td><?php echo PHP_VERSION; ?></td>
                        </tr>
                        <tr>
                            <td>MySQL Version</td>
                            <td><?php echo $db->getConnection()->getAttribute(PDO::ATTR_SERVER_VERSION); ?></td>
                        </tr>
                        <tr>
                            <td>Server Load</td>
                            <td>2.4%</td>
                        </tr>
                        <tr>
                            <td>Memory Usage</td>
                            <td>64MB / 256MB</td>
                        </tr>
                        <tr>
                            <td>Disk Space</td>
                            <td>45GB / 100GB</td>
                        </tr>
                        <tr>
                            <td>Uptime</td>
                            <td>15 days</td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Helper functions
function getActivityIcon($action) {
    $icons = [
        'login' => 'sign-in-alt',
        'logout' => 'sign-out-alt',
        'course_created' => 'plus-circle',
        'course_updated' => 'edit',
        'course_enrolled' => 'user-plus',
        'profile_update' => 'user-edit',
        'password_change' => 'key',
        'email_verified' => 'check-circle'
    ];
    
    return $icons[$action] ?? 'circle';
}

function getActivityDescription($action) {
    $descriptions = [
        'login' => 'logged in',
        'logout' => 'logged out',
        'course_created' => 'created a new course',
        'course_updated' => 'updated a course',
        'course_enrolled' => 'enrolled in a course',
        'profile_update' => 'updated their profile',
        'password_change' => 'changed their password',
        'email_verified' => 'verified their email'
    ];
    
    return $descriptions[$action] ?? 'performed an action';
}

function formatTimeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return 'just now';
    } elseif ($diff < 3600) {
        return floor($diff / 60) . ' minutes ago';
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . ' hours ago';
    } else {
        return date('M j, Y', $time);
    }
}

include __DIR__ . '/includes/footer.php';
?>
