<?php
#
# This script runs when a client connects
# Works with both auth_request and nchan_authorize_request
#
namespace IMATHUZH\Qfq\Core\Messenger\Hooks;

// Include the file with your NchanRequest class
require_once(__DIR__ . '/request.php');

// Create log file for debugging
$logFile = '/tmp/hook_debug.log';
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Hook starting\n", FILE_APPEND);

// Log headers and server variables
$headers = getallheaders();
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Headers: " . print_r($headers, true) . "\n", FILE_APPEND);
file_put_contents($logFile, date('Y-m-d H:i:s') . " - SERVER: " . print_r($_SERVER, true) . "\n", FILE_APPEND);

// Detect which authorization method is being used
$isNchanAuth = isset($_SERVER['HTTP_X_SUBSCRIBER_TYPE']) && !isset($_SERVER['HTTP_X_FORWARDED_FOR']);
$authMethod = $isNchanAuth ? 'nchan_authorize_request' : 'auth_request';
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Detected auth method: $authMethod\n", FILE_APPEND);

try {
    // Create the NchanRequest object
    $request = new NchanRequest();
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - NchanRequest created\n", FILE_APPEND);

    // Check if connection is authorized
    $authorized = $request->authorized();
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - Authorization: " . ($authorized ? 'true' : 'false') . "\n", FILE_APPEND);

    if ($authorized) {
        $clientId = $request->getClientId();
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - Client ID: $clientId\n", FILE_APPEND);

        if ($isNchanAuth) {
            // nchan_authorize_request method
            header('X-Accel-Redirect: /nchan_authorize_request');

            // With nchan auth, we can send an initial message
            $request->respond([
                'type' => 'ctl',
                'name' => 'hello',
                'payload' => [ 'id' => $clientId ]
            ]);
        } else {
            // auth_request method
            http_response_code(200);
            echo "Authorized";
        }

        // Notify controller in both cases
        $request->notifyController([
            'type' => 'message',
            'name' => 'auth',
            'payload' => [
                'clientId' => $clientId,
                'originalUrl' => $request->requestUri,
                'nchanVersion' => $request->nchanVersion,
                'subscriberType' => $request->subscriberType,
                'authorized' => true,
                'method' => $authMethod,
                'timestamp' => time()
            ]
        ]);
    } else {
        // Deny connection - same for both methods
        http_response_code(403);
        echo "Access denied";

        // Notify controller
        $request->notifyController([
            'type' => 'message',
            'name' => 'auth',
            'payload' => [
                'originalUrl' => $request->requestUri,
                'authorized' => false,
                'method' => $authMethod,
                'timestamp' => time()
            ]
        ]);
    }

    file_put_contents($logFile, date('Y-m-d H:i:s') . " - Auth completed successfully\n\n", FILE_APPEND);

} catch (\Throwable $e) {
    // Log any errors
    file_put_contents($logFile,
        date('Y-m-d H:i:s') . " - ERROR: " . $e->getMessage() .
        "\nFile: " . $e->getFile() . " Line: " . $e->getLine() .
        "\nTrace: " . $e->getTraceAsString() . "\n\n",
        FILE_APPEND);

    // Return an error
    http_response_code(500);
    echo "Error: " . $e->getMessage();
}