<?php
// app/lib/auth.php
require_once __DIR__ . '/db.php';

session_start();

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

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

function require_role($roles) {
    $u = current_user();
    if (!$u) { header('Location: login.php'); exit; }
    if (!in_array($u['role'], $roles, true)) {
        http_response_code(403);
        echo "Acceso denegado."; exit;
    }
}

function login($username, $password) {
    $u = one("SELECT id, username, password_hash, role, active FROM users WHERE username = ?", [$username]);
    if (!$u) return false;
    if ((int)$u['active'] !== 1) return false;
    if (!password_verify($password, $u['password_hash'])) return false;

    unset($u['password_hash']);
    $_SESSION['user'] = $u;
    return true;
}

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