<?php
// Location: taka26.site/public_html/aviator_launch.php

require_once __DIR__ . '/auth_helper.php';
require_once __DIR__ . '/aviator_bridge_config.php';

$user = authRequired();

function aviator_b64url_encode_home($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$userId = isset($user['id']) ? (string)$user['id'] : '';

if ($userId === '') {
    http_response_code(500);
    exit('User ID missing. Please login again.');
}

$payload = [
    'uid' => $userId,
    'exp' => time() + AVIATOR_TOKEN_TTL,
    'nonce' => bin2hex(random_bytes(8)),
];

$payloadJson = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

if ($payloadJson === false) {
    http_response_code(500);
    exit('Unable to create Aviator token.');
}

$body = aviator_b64url_encode_home($payloadJson);
$sig = hash_hmac('sha256', $body, AVIATOR_BRIDGE_SECRET);
$token = $body . '.' . $sig;

$remote = rtrim(AVIATOR_REMOTE_URL, '/') . '/index.php?token=' . rawurlencode($token);

header('Location: ' . $remote, true, 302);
exit;