<?php
require_once __DIR__ . '/../db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function current_user() {
    if (!isset($_SESSION['user_id'])) {
        return null;
    }
    static $user = null;
    if ($user !== null) return $user;

    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? AND active = 1");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    if (!$user) {
        session_destroy();
        return null;
    }
    return $user;
}

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

function require_admin() {
    $user = current_user();
    if (!$user || $user['role'] !== 'admin') {
        http_response_code(403);
        echo "Acesso negado.";
        exit;
    }
}

function login($email, $password): bool {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND active = 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id'];
        return true;
    }
    return false;
}

function logout() {
    session_destroy();
}
