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

#
# This script runs when a client connects
#

namespace IMATHUZH\Messenger\Example;

use IMATHUZH\Messenger\Nchan\NchanRequest;

require_once 'common.php';

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

    // Close the request, so that the client can connect and receive the hello message
    $request->close(200);
    logmsg("sub - INFO - notifying {$request->controllerUrl}");
    $response = $request->notifyController('sub');

    // Prepend dedicated user and session channels to listener channels
    $channelData = $request->getChannelMetaData();
    array_unshift(
        $channelData['sub'],
        "user." . $request->getClientId(),
        "ses." . $request->getSessionId()
    );
    // Log values
    foreach ($channelData as $key => $value) {
        if (is_array($value)) $value = implode(", ", $value);
        logmsg("sub - INFO - $key: $value");
    }

    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());
}