<?php

/*
	hub.php
	-------
	ChatGPT OAuth hub entry point. Routes the authorise request to the last
	Collabit tenant that set the browser's last_found_collabit_server cookie.
*/

$oauth_ui_paths = [
	dirname(__DIR__) . '/functions/oauth/oauth_ui.php',
	'/opt/collabit/functions/oauth/oauth_ui.php'
];
foreach ($oauth_ui_paths as $oauth_ui_path) {
	if (is_file($oauth_ui_path)) {
		require_once $oauth_ui_path;
		break;
	}
}
if (!function_exists('collabit_oauth_status_exit')) {
	http_response_code(422);
	exit("Please sign into Collabit before attempting to connect.");
}

$savedPath = $_COOKIE['last_found_collabit_server'] ?? false;

if (!$savedPath) {
	collabit_oauth_status_exit('Please sign in to Collabit first', 'ChatGPT does not yet know which Collabit tenant to connect to.', [
		'status_code' => 422,
		'status_label' => 'Tenant not selected',
		'detail' => 'Open your normal Collabit tenant in this browser, sign in, then return to ChatGPT and connect the app again.',
		'primary_label' => ''
	]);
}

if (!is_string($savedPath) || preg_match('/^[a-z0-9.-]+(?:\/[A-Za-z0-9._~%-]+)?$/i', $savedPath) !== 1) {
	collabit_oauth_status_exit('Please sign in to Collabit first', 'The saved Collabit tenant could not be used for this connection.', [
		'status_code' => 422,
		'status_label' => 'Tenant selection invalid',
		'detail' => 'Open your normal Collabit tenant in this browser, sign in, then return to ChatGPT and connect the app again.',
		'primary_label' => ''
	]);
}

$queryString = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';

header("X-Frame-Options: ALLOW-FROM https://chatgpt.com");
header("Content-Security-Policy: frame-ancestors https://chatgpt.com");
header("Location: https://" . $savedPath . "/authorize.php" . $queryString);
exit;

?>
