<?php
/**
 * @package messenger
 * @author kputyr
 *
 * This script runs when a client connects to subscribe.
 * Works with both auth_request and nchan_authorize_request.
 */
namespace IMATHUZH\Qfq\Core\Messenger\Hooks;

require_once(__DIR__ . '/request.php');

$request = new NchanRequest();

// Check if connection is authorized
$authorized = $request->authorized();

if ($authorized) {
    $clientId = $request->getClientId();

    // Return 200 to allow the subscription
    http_response_code(200);

    // Send initial "hello" message with client ID
    $request->respond([
        MESSENGER_KEY_TYPE => MESSENGER_TYPE_CTL,
        MESSENGER_KEY_NAME => MESSENGER_EVENT_HELLO,
        MESSENGER_KEY_PAYLOAD => [MESSENGER_KEY_ID => $clientId]
    ]);

    // Notify controller about new subscription
    $request->notifyController([
        MESSENGER_KEY_TYPE => MESSENGER_TYPE_MESSAGE,
        MESSENGER_KEY_NAME => MESSENGER_EVENT_SUBSCRIBE,
        MESSENGER_KEY_PAYLOAD => [
            MESSENGER_KEY_CLIENT_ID => $clientId,
            MESSENGER_KEY_CHANNEL => $request->getChannel(),
            MESSENGER_KEY_GROUP => $request->getGroup(),
            MESSENGER_KEY_FE_USER_UID => $request->getFeUserUid(),
            MESSENGER_KEY_FE_USER => $request->getFeUser(),
            MESSENGER_KEY_TIMESTAMP => time()
        ]
    ]);
} else {
    // Deny connection
    http_response_code(403);
    echo "Access denied";

    // Notify controller about denied connection
    $request->notifyController([
        MESSENGER_KEY_TYPE => MESSENGER_TYPE_MESSAGE,
        MESSENGER_KEY_NAME => MESSENGER_EVENT_SUBSCRIBE_DENIED,
        MESSENGER_KEY_PAYLOAD => [
            MESSENGER_KEY_CHANNEL => $request->getChannel(),
            MESSENGER_KEY_GROUP => $request->getGroup(),
            MESSENGER_KEY_TIMESTAMP => time()
        ]
    ]);
}
