<?php
// /esp32/dashboard/auth.php
// Disclaimer: This example code is part of a research prototype.
// It is provided “as is”, without any warranty of any kind.
// Please review, adapt, and test carefully before using it in production.

require_once __DIR__ . '/db.php';

// Start a PHP session if one is not already active.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Generate (or return existing) CSRF token for the current session.
 */
function csrf_token(): string
{
    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf'];
}

/**
 * Validate a CSRF token received from a form.
 */
function csrf_check($token): bool
{
    return is_string($token) && hash_equals($_SESSION['csrf'] ?? '', $token);
}

/**
 * Return the currently logged-in user as an associative array
 * with keys: id, email, role.
 */
function current_user(): ?array
{
    return $_SESSION['user'] ?? null;
}

/**
 * Redirect to the login page if not logged in.
 */
function require_login(): void
{
    if (!current_user()) {
        $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'] ?? BASE_URL . '/';
        header('Location: ' . BASE_URL . '/login.php');
        exit;
    }
}

/**
 * Return HTTP 403 if the current user is not an administrator.
 */
function require_admin(): void
{
    $user = current_user();
    if (!$user || ($user['role'] ?? '') !== 'admin') {
        http_response_code(403);
        header('Content-Type: text/plain; charset=utf-8');
        exit('Forbidden (admin only)');
    }
}

/**
 * Attempt to authenticate the user with the given email and password.
 *
 * The users table is expected to contain:
 *   id, email, password_hash, role
 */
function login_user(string $email, string $password): bool
{
    $stmt = pdo()->prepare('SELECT id, email, password_hash, role FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['user'] = [
            'id'    => (int)$user['id'],
            'email' => $user['email'],
            'role'  => $user['role'],
        ];
        return true;
    }

    return false;
}

/**
 * Log out the current user by clearing session data and cookies.
 */
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();
}
