<?php declare(strict_types=1);
/**
 * @package messenger
 * @author kputyr
 * @date 10.02.2026
 */

namespace IMATHUZH\Messenger;

function logmsg(string $message) {
    static $request = null;

    if (!$request) {
        $request = bin2hex(random_bytes(3));
        file_put_contents(__DIR__ . '/hooks.log', "-------------------------------------------------\n", FILE_APPEND|LOCK_EX);
    }
    $time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
    file_put_contents(__DIR__ . '/hooks.log', "[$time] $request: $message\n", FILE_APPEND|LOCK_EX);
}

function logHeaders(string $prompt) {
    $prefix = "HTTP_X_";
    $prefixSize = strlen($prefix);
    foreach(['REQUEST_URI', 'HTTP_AUTHORIZATION', 'HTTP_COOKIE', 'HTTP_UPGRADE', 'HTTP_CONNECTION'] as $header) {
        if (isset($_SERVER[$header])) {
            logmsg("$prompt - HTTP - $header: {$_SERVER[$header]}");
        }
    }
    foreach($_SERVER as $key => $value) {
        if (str_starts_with($key, $prefix)) {
            logmsg("$prompt - HTTP - " . substr($key, $prefixSize) . ' ' . $value);
        }
    }
}

function logTokens(string $prompt) {
    logmsg("$prompt - TOKEN - session " . session_name() . "=" . session_id());
    foreach($_SESSION ?? [] as $token => $data) {
        if (strlen($token) === 16) {
            logmsg("$prompt - TOKEN - token $token: $data");
        }
    }
}
