<?php
// Role-Based Access Control (RBAC) functions

// Define role hierarchy and permissions
define('ROLES', [
    'guest' => 0,
    'student' => 1,
    'instructor' => 2,
    'admin' => 3
]);

define('PERMISSIONS', [
    // Blog permissions
    'view_posts' => ['guest', 'student', 'instructor', 'admin'],
    'create_posts' => ['instructor', 'admin'],
    'edit_own_posts' => ['instructor', 'admin'],
    'edit_all_posts' => ['admin'],
    'delete_posts' => ['admin'],
    'manage_categories' => ['admin'],
    'manage_users' => ['admin'],
    'manage_site_settings' => ['admin'],
    'manage_announcements' => ['admin'],
    'view_admin_dashboard' => ['admin', 'instructor'],
    'manage_students' => ['instructor', 'admin'],
    'view_analytics' => ['admin'],

    // Course permissions
    'view_courses' => ['guest', 'student', 'instructor', 'admin'],
    'browse_courses' => ['guest', 'student', 'instructor', 'admin'],
    'enroll_course' => ['student', 'instructor', 'admin'],
    'view_enrolled_courses' => ['student', 'instructor', 'admin'],
    'create_course' => ['instructor', 'admin'],
    'edit_own_course' => ['instructor', 'admin'],
    'edit_all_courses' => ['admin'],
    'delete_course' => ['admin'],
    'manage_course_categories' => ['admin'],
    'view_course_analytics' => ['instructor', 'admin'],
    'manage_enrollments' => ['instructor', 'admin'],
    'view_course_content' => ['student', 'instructor', 'admin'],
    'manage_course_content' => ['instructor', 'admin'],
    'review_course' => ['student'],
    'moderate_reviews' => ['instructor', 'admin']
]);

/**
 * Check if user has a specific role
 */
function hasRole($role) {
    if (!isLoggedIn()) return false;
    return isset($_SESSION['role']) && $_SESSION['role'] === $role;
}

/**
 * Check if user has any of the specified roles
 */
function hasAnyRole($roles) {
    if (!isLoggedIn()) return false;
    return isset($_SESSION['role']) && in_array($_SESSION['role'], $roles);
}

/**
 * Check if user has permission
 */
function hasPermission($permission) {
    if (!isLoggedIn()) return false;

    $userRole = $_SESSION['role'] ?? 'guest';

    if (!isset(PERMISSIONS[$permission])) {
        return false;
    }

    return in_array($userRole, PERMISSIONS[$permission]);
}

/**
 * Require specific role, redirect if not authorized
 */
function requireRole($role, $redirectUrl = '/login.php') {
    if (!hasRole($role)) {
        header('Location: ' . $redirectUrl);
        exit;
    }
}

/**
 * Require any of the specified roles, redirect if not authorized
 */
function requireAnyRole($roles, $redirectUrl = '/login.php') {
    if (!hasAnyRole($roles)) {
        header('Location: ' . $redirectUrl);
        exit;
    }
}

/**
 * Require permission, redirect if not authorized
 */
function requirePermission($permission, $redirectUrl = '/login.php') {
    if (!hasPermission($permission)) {
        // For API endpoints, return JSON error instead of redirect
        if (strpos($_SERVER['REQUEST_URI'], 'enrollments.php') !== false ||
            strpos($_SERVER['REQUEST_URI'], '/api/') !== false) {
            http_response_code(403);
            echo json_encode(['success' => false, 'error' => 'Permission denied']);
            exit;
        }
        header('Location: ' . $redirectUrl);
        exit;
    }
}

/**
 * Get role hierarchy level
 */
function getRoleLevel($role) {
    return ROLES[$role] ?? 0;
}

/**
 * Check if user role is at or above specified level
 */
function hasRoleLevel($minLevel) {
    if (!isLoggedIn()) return false;
    $userRole = $_SESSION['role'] ?? 'guest';
    return getRoleLevel($userRole) >= $minLevel;
}

/**
 * Get all roles
 */
function getAllRoles() {
    return array_keys(ROLES);
}

/**
 * Get user role display name
 */
function getRoleDisplayName($role) {
    $displayNames = [
        'guest' => 'Guest',
        'student' => 'Student',
        'instructor' => 'Instructor',
        'admin' => 'Administrator'
    ];

    return $displayNames[$role] ?? ucfirst($role);
}

/**
 * Check if user can edit specific post
 */
function canEditPost($postAuthorId) {
    if (!isLoggedIn()) return false;

    $userId = $_SESSION['user_id'];
    $userRole = $_SESSION['role'];

    // Admin can edit all posts
    if ($userRole === 'admin') return true;

    // Instructor can edit their own posts
    if ($userRole === 'instructor' && $postAuthorId == $userId) return true;

    return false;
}

/**
 * Check if user can edit specific course
 */
function canEditCourse($courseInstructorId) {
    if (!isLoggedIn()) return false;

    $userId = $_SESSION['user_id'];
    $userRole = $_SESSION['role'];

    // Admin can edit all courses
    if ($userRole === 'admin') return true;

    // Instructor can edit their own courses
    if ($userRole === 'instructor' && $courseInstructorId == $userId) return true;

    return false;
}

/**
 * Check if user can view course content
 */
function canViewCourseContent($courseId, $enrollmentId = null) {
    if (!isLoggedIn()) return false;

    $userRole = $_SESSION['role'];
    $userId = $_SESSION['user_id'];

    // Admin and instructors can view all course content
    if (in_array($userRole, ['admin', 'instructor'])) return true;

    // Students can view content if enrolled
    if ($userRole === 'student' && $enrollmentId) {
        // Check if enrollment belongs to user
        $db = getDB();
        $stmt = $db->prepare("SELECT id FROM course_enrollments WHERE id = ? AND student_id = ?");
        $stmt->execute([$enrollmentId, $userId]);
        return $stmt->fetch() !== false;
    }

    return false;
}

/**
 * Check if user can enroll in course
 */
function canEnrollInCourse($courseId) {
    if (!isLoggedIn()) return false;

    $userRole = $_SESSION['role'];
    if (!in_array($userRole, ['student', 'instructor', 'admin'])) return false;

    $userId = $_SESSION['user_id'];

    // Check if already enrolled
    $db = getDB();
    $stmt = $db->prepare("SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ?");
    $stmt->execute([$courseId, $userId]);

    return $stmt->fetch() === false;
}

/**
 * Check if user can manage course enrollments
 */
function canManageEnrollments($courseInstructorId) {
    if (!isLoggedIn()) return false;

    $userId = $_SESSION['user_id'];
    $userRole = $_SESSION['role'];

    // Admin can manage all enrollments
    if ($userRole === 'admin') return true;

    // Instructor can manage enrollments for their courses
    if ($userRole === 'instructor' && $courseInstructorId == $userId) return true;

    return false;
}

/**
 * Get accessible dashboard URL based on role
 */
function getDashboardUrl() {
    if (!isLoggedIn()) return 'home.php';

    $role = $_SESSION['role'];

    switch ($role) {
        case 'admin':
            return 'admin/dashboard.php';
        case 'instructor':
            return 'instructor/dashboard.php';
        case 'student':
            return 'student/dashboard.php';
        default:
            return 'home.php';
    }
}
?>