<?php
// includes/check-permission.php - Permission Check Middleware

if(!isset($_SESSION['user_id'])) {
    header('Location: ../auth.php');
    exit;
}

// If admin, allow everything
if(($_SESSION['user_role'] ?? '') == 'admin') {
    return;
}

// If not instructor, redirect
if(($_SESSION['user_role'] ?? '') != 'instructor') {
    header('Location: ../dashboard.php');
    exit;
}

// Get instructor permissions
global $pdo;
$instructor_id = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT * FROM instructor_permissions WHERE instructor_id = ?");
$stmt->execute([$instructor_id]);
$perms = $stmt->fetch();

// If no permissions set, use defaults (allow basic)
if(!$perms) {
    $perms = [
        'can_create_course' => 1,
        'can_manage_lessons' => 1,
        'can_create_quiz' => 1,
        'can_upload_files' => 1,
        'can_create_live_class' => 1,
        'can_send_sms' => 0,
        'can_view_students' => 1,
        'can_manage_enrollments' => 0,
        'can_view_revenue' => 0,
        'is_active' => 1,
    ];
}

// Check if active
if(!$perms['is_active']) {
    session_destroy();
    header('Location: ../auth.php?error=account_disabled');
    exit;
}

// Store permissions in session for quick access
$_SESSION['instructor_perms'] = $perms;

// Permission check functions
function can($permission) {
    if(($_SESSION['user_role'] ?? '') == 'admin') return true;
    return $_SESSION['instructor_perms'][$permission] ?? false;
}
?>