<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

function check_auth() {
    if (!isset($_SESSION['user_id'])) {
        header("Location: login.php");
        exit;
    }
}

function current_user() {
    if (!isset($_SESSION['user_id'])) {
        return null;
    }
    
    global $db;
    if (!isset($db)) {
        $db = db();
    }
    
    // Check cache first (optional, but good for performance)
    if (isset($_SESSION['user_cache']) && $_SESSION['user_cache']['id'] == $_SESSION['user_id']) {
        return $_SESSION['user_cache'];
    }

    $stmt = $db->prepare("
        SELECT u.*, r.slug as role_slug, r.permissions 
        FROM users u 
        JOIN roles r ON u.role_id = r.id 
        WHERE u.id = ? AND u.active = 1
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user) {
        $_SESSION['user_cache'] = $user;
        return $user;
    }
    
    // User not found or inactive, logout
    session_destroy();
    header("Location: login.php");
    exit;
}

function has_role($role_slug) {
    $user = current_user();
    if (!$user) return false;
    
    if ($user['role_slug'] === 'admin') return true; // Admin has all roles
    
    return $user['role_slug'] === $role_slug;
}

function has_permission($permission) {
    $user = current_user();
    if (!$user) return false;
    
    if ($user['role_slug'] === 'admin') return true; // Admin has all permissions
    
    // Decode permissions JSON
    $perms = json_decode($user['permissions'], true);
    if (!$perms) return false;
    
    if (in_array('*', $perms)) return true;
    
    return in_array($permission, $perms);
}

function require_role($role_slug) {
    if (!has_role($role_slug)) {
        http_response_code(403);
        die("Access Denied: You do not have the required role.");
    }
}

function require_permission($permission) {
    if (!has_permission($permission)) {
        http_response_code(403);
        die("Access Denied: You do not have the required permission: " . htmlspecialchars($permission));
    }
}

function is_admin() {
    return has_role('admin');
}
