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

#
# This script runs when a client connects
#

namespace IMATHUZH\Messenger;

require_once 'request.php';

try {
    $request = NchanRequest::fromServerRequest()->generateUrls();
    logmsg("sub - INFO - request uri " . $request->requestUri);
    logHeaders('sub');

    # Nchan interpretation of HTTP code:
    #   200 OK            the response of this script is posted instead
    #   204 No content    the message is deleted
    #   304 Not modified  the message is posted on the channel

    $request->close(200);

    $channelData = $request->getChannelMetaData();
    array_unshift($channelData['sub'], "user." . $request->getClientId(), "ses." . $request->getSessionId());
    foreach ($channelData as $key => $value) {
        if (is_array($value)) $value = implode(", ", $value);
        logmsg("sub - INFO - $key: $value");
    }

    logmsg("sub - INFO - notifying {$request->controllerUrl}");
    $response = $request->notifyController('sub');

    logmsg("sub - INFO - sending meta data back to {$request->responseUrl}");
    $request->respond([
        'type' => 'ctl',
        'name' => 'hello',
        'payload' => $channelData
    ]);
    logmsg("sub - INFO - done");

} catch (\Throwable $e) {
    logmsg("sub - ERROR - " . $e->getMessage());
}