<?php
/**
 * Redirect legacy token URLs to the real 3x-ui subscription endpoint.
 */
include "../baseInfo.php";
include "../config.php";

$connection = new mysqli('localhost', $dbUserName, $dbPassword, $dbName);
if ($connection->connect_error) {
    exit("error " . $connection->connect_error);
}
$connection->set_charset("utf8mb4");

if (!isset($_GET['token'])) {
    echo "Wrong token";
    exit;
}

$token = $_GET['token'];
if (!preg_match('/[a-zA-Z0-9]{30}/', $token)) {
    echo "Wrong token";
    exit;
}

$stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `token` = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$info = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$info) {
    echo "Wrong token";
    exit;
}

$subLink = resolveCustomerSubLink($info['server_id'], $info['remark'], $token);
if (!empty($subLink)) {
    header('Location: ' . $subLink, true, 302);
    exit;
}

$stored = json_decode($info['link'], true);
if (is_array($stored) && !empty($stored[0]) && preg_match('#^https?://#i', $stored[0])) {
    header('Location: ' . $stored[0], true, 302);
    exit;
}

echo "Subscription link unavailable.";
