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

/**************************************************************
 * Configuration constants
 * 
 * Please modify as needed
 **************************************************************/

const SESSION_COOKIE = '';
const SESSION_KEY = 'example';
const REST_BASE_URL = '/messenger/rest/';
const LOG_FILE =  __DIR__ . '/../logs/hooks.log';

/* Common part for hooks. Do not modify unless you know exactly what you are doing. */

use IMATHUZH\Messenger\TokenStorage;
use IMATHUZH\Messenger\TokenStorageInterface;

/* Class autoloader for hooks */

spl_autoload_register(function($className) {
    $classPath = strtr($className, '\\', '/');
    if (str_starts_with($classPath, 'Psr/Log/')) {
        include __DIR__ . '/vendor/psr/log/src/' . substr($classPath, 8) . '.php';
    } elseif (str_starts_with($classPath, 'IMATHUZH/Messenger/')) {
        include dirname(__DIR__) . '/php/Classes/' . substr($classPath, 19) . '.php';
    } else {
        trigger_error("class not found: $className");
    }
});

/**
 * A helper function to immediately reject a request
 */
function reject(string $message): bool
{
    throw new \Exception($message);    
}

/**
 * Opens a PHP session unless one is already active or $_SESSION array
 * exists and read-only access has been requested.
 * 
 * @param bool $readonly   if true, then the session is closed immediately
 *                         after populating $_SESSION array
 */
function openSession(bool $readonly=false): void
{
    if (session_status() !== PHP_SESSION_ACTIVE || !($readonly && isset($_SESSION))) {
        session_name(SESSION_COOKIE);
        session_start(['read_and_close' => $readonly]);
    }
    if (!isset($_SESSION[SESSION_KEY])) {
        $_SESSION[SESSION_KEY] = [];
    }
}

/**
 * Creates a new TokenStorage instance using the session for storage.
 * 
 * A PHP session is started when needed.
 * 
 * @param bool $readonly   if true, then the session is closed immediately
 *                         after populating $_SESSION array
 */
function loadTokenStorage(bool $readonly = false): TokenStorageInterface
{
    openSession($readonly);
    return new TokenStorage($_SESSION[SESSION_KEY]);
}


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

    if (!$request) {
        $request = bin2hex(random_bytes(3));
        file_put_contents(LOG_FILE, "-------------------------------------------------\n", FILE_APPEND|LOCK_EX);
    }
    $time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
    file_put_contents(LOG_FILE, "[$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) {
    if (!isset($_SESSION)) {
        session_start(['read_and_close' => true]);
    }
    logmsg("$prompt - TOKEN - session " . session_name() . "=" . session_id());
    foreach($_SESSION[SESSION_KEY] ?? [] as $token => $data) {
        if (\strlen($token) === 16) {
            logmsg("$prompt - TOKEN - token $token: $data");
        }
    }
}
