<?php
// auth.php - Authentication and permissions helpers for Team Mania Pro

require_once __DIR__ . '/config.php';

function is_logged_in() {
    return isset($_SESSION['user_id']);
}

function current_user() {
    global $pdo;
    if (!is_logged_in()) {
        return null;
    }
    
    static $user = null;
    if ($user !== null) {
        return $user;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT u.*, p.can_edit_pages, p.can_manage_inventory, p.can_manage_finance 
                               FROM users u 
                               LEFT JOIN permissions p ON u.id = p.user_id 
                               WHERE u.id = :id");
        $stmt->execute([':id' => $_SESSION['user_id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        return $user;
    } catch (PDOException $e) {
        return null;
    }
}

function require_login() {
    if (!is_logged_in()) {
        header("Location: index.php?view=login");
        exit;
    }
}

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

function require_role($roles) {
    require_login();
    if (!has_role($roles)) {
        header("Location: index.php?view=dashboard&error=access_denied");
        exit;
    }
}

// Check custom page editing permission (Admin, Vorstand, or custom override)
function can_edit_pages() {
    $user = current_user();
    if (!$user) return false;
    if ($user['role'] === 'admin' || $user['role'] === 'vorstand') return true;
    return !empty($user['can_edit_pages']);
}

// Check inventory management permission (Admin, Materialwart, or custom override)
function can_manage_inventory() {
    $user = current_user();
    if (!$user) return false;
    if ($user['role'] === 'admin' || $user['role'] === 'materialwart') return true;
    return !empty($user['can_manage_inventory']);
}

// Check financial management permission (Admin, Kassenwart, or custom override)
function can_manage_finance() {
    $user = current_user();
    if (!$user) return false;
    if ($user['role'] === 'admin' || $user['role'] === 'kassenwart') return true;
    return !empty($user['can_manage_finance']);
}

// Check role-based menu visibility
function is_menu_visible($menu_view) {
    $user = current_user();
    if (!$user) return false;
    if ($user['role'] === 'admin') return true;

    $visibility_json = get_setting('menu_visibility', '');
    $visibility = json_decode($visibility_json, true);
    
    $defaults = [
        'chat' => ['admin', 'vorstand', 'trainer', 'materialwart', 'member'],
        'forum' => ['admin', 'vorstand', 'trainer', 'materialwart', 'member'],
        'trainer' => ['admin', 'trainer'],
        'kassenwart' => ['admin', 'kassenwart'],
        'vorstand' => ['admin', 'vorstand'],
        'inventory' => ['admin', 'vorstand', 'trainer', 'materialwart', 'member']
    ];

    if (!$visibility) {
        $allowed = $defaults[$menu_view] ?? [];
    } else {
        $allowed = $visibility[$menu_view] ?? ($defaults[$menu_view] ?? []);
    }

    return in_array($user['role'], $allowed);
}
