<?php
// Function to check if a user is logged in
function is_logged_in() {
    return isset($_SESSION['user_id']);
}

// Function to check if the logged-in user is an admin
function is_admin() {
    return is_logged_in() && $_SESSION['user_role'] === 'admin';
}

// Function to enforce login (redirect if not logged in)
function require_login() {
    if (!is_logged_in()) {
        header('Location: index.php?msg=Please login to continue.');
        exit();
    }
}

// Function to enforce admin role (redirect if not admin)
function require_admin() {
    require_login();
    if (!is_admin()) {
        header('Location: studentdash.php?msg=Access denied. Admin privileges required.');
        exit();
    }
}

// Generates a random, secure password
function generate_random_password($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $characters[random_int(0, strlen($characters) - 1)];
    }
    return $password;
}

// Function to extract YouTube video ID from a URL
function get_youtube_embed_link($url) {
    $video_id = false;
    // Standard URL format
    if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|\w\/\w+\?v=)|youtu\.be\/)([^&?]+)/', $url, $matches)) {
        $video_id = $matches[1];
    }
    return $video_id ? "https://www.youtube.com/embed/{$video_id}?rel=0" : false;
}

// Function to get YouTube thumbnail URL
function get_youtube_thumbnail($url) {
    $video_id = get_youtube_embed_link($url);
    // Use maxresdefault for highest quality, or hqdefault as fallback
    return $video_id ? "https://img.youtube.com/vi/{$video_id}/maxresdefault.jpg" : 'https://placehold.co/480x360/cccccc/000000?text=No+Video+Found';
}

// Function to log analytical event
function log_analytics($pdo, $eventType, $userId = null, $packId = null) {
    try {
        $stmt = $pdo->prepare("INSERT INTO analytics_log (event_type, user_id, pack_id) VALUES (?, ?, ?)");
        $stmt->execute([$eventType, $userId, $packId]);
    } catch (PDOException $e) {
        error_log("Analytics logging failed: " . $e->getMessage());
    }
}
?>