<?php

require_once __DIR__ . '/env_loader.php';

function checkSession(): void
{
    if (session_status() === PHP_SESSION_NONE) {
        $domain = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
        if ($domain) {
            $parsed = parse_url($domain);
            $host = $parsed['host'] ?? $_SERVER['HTTP_HOST'] ?? '';
            session_set_cookie_params([
                'lifetime' => 0,
                'path' => '/',
                'domain' => $host,
                'secure' => true,
                'httponly' => true,
                'samesite' => 'Strict'
            ]);
        }
        session_start();
    }

    validateSessionDomain();

    if (!isset($_SESSION['user_id'])) {
        $appUrl = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
        $parsed = parse_url($appUrl);
        $scheme = $parsed['scheme'] ?? 'https';
        $host = $parsed['host'] ?? $_SERVER['HTTP_HOST'] ?? 'localhost';
        header('Location: ' . $scheme . '://' . $host . '/login.php');
        exit;
    }
}

function validateSessionDomain(): void
{
    $allowedDomain = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? '';
    
    if (empty($allowedDomain)) {
        return;
    }
    
    $parsed = parse_url($allowedDomain);
    $allowedHost = $parsed['host'] ?? '';
    $currentHost = $_SERVER['HTTP_HOST'] ?? '';
    
    if (strcasecmp($allowedHost, $currentHost) !== 0) {
        session_unset();
        session_destroy();
        $scheme = $parsed['scheme'] ?? 'https';
        $loginUrl = $scheme . '://' . $allowedHost . '/login.php';
        header('Location: ' . $loginUrl);
        exit;
    }
}

function isAdmin(): bool
{
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

function requireAdmin(): void
{
    checkSession();
    
    if (!isAdmin()) {
        header('HTTP/1.1 403 Forbidden');
        echo 'Acceso denegado';
        exit;
    }
}

function getCurrentUserId(): int
{
    return $_SESSION['user_id'] ?? 0;
}

function getCurrentUsername(): string
{
    return $_SESSION['username'] ?? '';
}

function getCurrentUserRole(): string
{
    return $_SESSION['role'] ?? 'guest';
}
