<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| HYRO ONE Shared Helpers
|--------------------------------------------------------------------------
*/

function hyro_escape(?string $value): string
{
    return htmlspecialchars(
        $value ?? '',
        ENT_QUOTES,
        'UTF-8'
    );
}

function hyro_redirect(string $url): never
{
    header('Location: ' . $url);
    exit;
}

function hyro_old(
    string $key,
    array $source = []
): string {
    return hyro_escape(
        isset($source[$key])
            ? (string) $source[$key]
            : ''
    );
}

function hyro_log(
    string $channel,
    string $message,
    array $context = []
): void {
    $safeChannel = preg_replace(
        '/[^a-zA-Z0-9_-]/',
        '',
        $channel
    );

    $file = HYRO_LOG_PATH
        . '/'
        . ($safeChannel ?: 'application')
        . '.log';

    $record = [
        'datetime' => date('Y-m-d H:i:s'),
        'message' => $message,
        'context' => $context,
    ];

    file_put_contents(
        $file,
        json_encode(
            $record,
            JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE
        ) . PHP_EOL,
        FILE_APPEND | LOCK_EX
    );
}

function hyro_json_response(
    array $payload,
    int $statusCode = 200
): never {
    http_response_code($statusCode);

    header(
        'Content-Type: application/json; charset=UTF-8'
    );

    echo json_encode(
        $payload,
        JSON_UNESCAPED_SLASHES |
        JSON_UNESCAPED_UNICODE
    );

    exit;
}
