<?php
// HAVA75 - Oturum ve yetki kontrolü

declare(strict_types=1);

$secureCookie = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'domain' => '',
        'secure' => $secureCookie,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    session_start();
}

require_once __DIR__ . '/db.php';

function current_user(): ?array
{
    return $_SESSION['hava75_user'] ?? null;
}

function is_logged_in(): bool
{
    return current_user() !== null;
}

function require_login(): void
{
    if (!is_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

function is_yonetici(): bool
{
    $user = current_user();
    return $user && (($user['role'] ?? '') === 'yonetici');
}

function require_yonetici(): void
{
    require_login();
    if (!is_yonetici()) {
        http_response_code(403);
        exit('Bu işlem için yönetici yetkisi gereklidir.');
    }
}

function login_user(array $user): void
{
    session_regenerate_id(true);
    $_SESSION['hava75_user'] = [
        'id' => (int)$user['id'],
        'username' => $user['username'],
        'full_name' => $user['full_name'] ?: $user['username'],
        'role' => $user['role'],
    ];
}

function logout_user(): void
{
    $_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();
}
