<?php
// ================== INIT ==================
include_once __DIR__ . '/config.php';
include_once __DIR__ . '/telegram.php';
include_once __DIR__ . '/class.php';
include_once __DIR__ . '/jdf.php';
include_once __DIR__ . '/vray.php';
include_once __DIR__ . '/marz.php';

$telegram = new telegram(TOKEN, HOST, USERNAME, PASSWORD, DBNAME);
$telegram->db->exec("SET NAMES utf8mb4");

$time = time();
$linksFile = __DIR__ . '/links.json';

// ================== CHECK FILE ==================
if (!file_exists($linksFile)) {
    exit("links.json not found\n");
}

$data = json_decode(file_get_contents($linksFile), true);
if (!$data || count($data) === 0) {
    exit("no links left\n");
}

// ================== GET ONE LINK ==================
$item   = array_shift($data);
$userid = intval($item['userid']);
$text   = trim($item['link']);

// ================== REGISTER LINK ==================
if (preg_match('/\/sub\//', $text)) {

    $res = get_web_page($text);
    if (!$res) exit("sub fetch failed\n");

    $decoded = base64_decode($res);
    $firstLink = explode(PHP_EOL, $decoded)[0];

    if (preg_match('/^vmess:\/\//', $firstLink)) {
        $info = json_decode(base64_decode(str_replace('vmess://', '', $firstLink)));
        $username = $info->ps ?? '';
    } else {
        $firstLink = urldecode($firstLink);
        $info = parse_url($firstLink);
        $username = $info['fragment'] ?? '';
    }

    $username = explode(' | ', $username)[1] ?? null;
    if (!$username) exit("username not found\n");

    // ================== FIND SERVER ==================
    $servers = $telegram->db
        ->query("SELECT * FROM server_info WHERE ptype='marzban'")
        ->fetchAll(PDO::FETCH_ASSOC);

    $response = null;
    $server_id = 0;

    foreach ($servers as $server) {
        $server_id = $server['id'];
        $response = muser_detail($server_id, $username);
        if (isset($response->subscription_url)) break;
    }

    if (!$response || !isset($response->expire)) {
        exit("user not found in marzban\n");
    }

    $expire_date = intval($response->expire);

    // ================== INSERT DB ==================
    $telegram->db->query("
        INSERT INTO fl_order 
        VALUES (
            NULL,
            $userid,
            '',
            10,
            $server_id,
            0,
            '$username',
            'vless',
            $expire_date,
            '$text',
            '0',
            2,
            1,
            '$time',
            0
        )
    ");

    // ================== SAVE BACK JSON ==================
    file_put_contents(
        $linksFile,
        json_encode(array_values($data), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
    );

    echo "OK: $username\n";
    exit;
}

exit("invalid link\n");
