<?php

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

function start_session_if_needed(): void
{
    if (session_status() === PHP_SESSION_NONE) {
        $app = app_config();
        session_name($app['session_name']);
        session_start();
    }
}

function login_user(array $user): void
{
    start_session_if_needed();

    $_SESSION['user_id'] = (int)$user['id'];
    $_SESSION['username'] = (string)$user['username'];
    $_SESSION['global_role'] = (string)($user['global_role'] ?? 'user');
    $_SESSION['ui_language'] = (string)($user['ui_language'] ?? 'de');
}

function logout_user(): void
{
    start_session_if_needed();

    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params['path'],
            $params['domain'],
            $params['secure'],
            $params['httponly']
        );
    }

    session_destroy();
}

function current_user(): ?array
{
    start_session_if_needed();

    if (empty($_SESSION['user_id'])) {
        return null;
    }

    $stmt = platform_db()->prepare(
        'SELECT
            id,
            username,
            email,
            display_name,
            global_role,
            ui_language,
            is_active
         FROM users
         WHERE id = ?
           AND is_active = 1
         LIMIT 1'
    );
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        return null;
    }

    $_SESSION['username'] = (string)$user['username'];
    $_SESSION['global_role'] = (string)$user['global_role'];
    $_SESSION['ui_language'] = (string)$user['ui_language'];

    return $user;
}

function current_user_id(): ?int
{
    $user = current_user();
    return $user ? (int)$user['id'] : null;
}

function current_user_global_role(): ?string
{
    $user = current_user();
    return $user ? (string)$user['global_role'] : null;
}

function current_user_language(): string
{
    $user = current_user();
    if (!$user) {
        return 'de';
    }

    $lang = trim((string)($user['ui_language'] ?? 'de'));
    return $lang !== '' ? $lang : 'de';
}

function require_login(): void
{
    if (current_user() === null) {
        header('Location: /login.php');
        exit;
    }
}

function authenticate_user(string $username, string $password): ?array
{
    $stmt = platform_db()->prepare(
        'SELECT *
         FROM users
         WHERE username = ?
         LIMIT 1'
    );
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        return null;
    }

    if ((int)$user['is_active'] !== 1) {
        throw new RuntimeException('Dieses Benutzerkonto wurde deaktiviert.');
    }

    if (!password_verify($password, $user['password_hash'])) {
        return null;
    }

    return $user;
}

function current_user_is_superadmin(): bool
{
    $user = current_user();

    if (!$user) {
        return false;
    }

    return (string)$user['global_role'] === 'superadmin';
}

/**
 * Prüft eine globale Plattform-Berechtigung.
 *
 * Superadmins besitzen implizit alle globalen Berechtigungen.
 * Normale Benutzer erhalten Berechtigungen ausschließlich über
 * permissions + user_permissions.
 */
function current_user_can(string $permissionKey): bool
{
    $user = current_user();

    if (!$user) {
        return false;
    }

    if ((string)$user['global_role'] === 'superadmin') {
        return true;
    }

    $permissionKey = trim($permissionKey);

    if (
        $permissionKey === ''
        || preg_match('/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/', $permissionKey) !== 1
    ) {
        return false;
    }

    $stmt = platform_db()->prepare(
        'SELECT 1
         FROM user_permissions up
         JOIN permissions p
           ON p.id = up.permission_id
         WHERE up.user_id = ?
           AND p.permission_key = ?
         LIMIT 1'
    );

    $stmt->execute([
        (int)$user['id'],
        $permissionKey,
    ]);

    return (bool)$stmt->fetchColumn();
}

/**
 * Erzwingt eine globale Plattform-Berechtigung.
 */
function require_permission(string $permissionKey): void
{
    require_login();

    if (!current_user_can($permissionKey)) {
        http_response_code(403);
        echo 'Zugriff verweigert.';
        exit;
    }
}

function require_superadmin(): void
{
    if (!current_user_is_superadmin()) {
        http_response_code(403);
        echo 'Zugriff verweigert.';
        exit;
    }
}
