<?php
header("Content-Type: application/json");

// ===== INPUT USERNAME =====
$username = $_GET['username'] ?? null;
if (!$username) {
    echo json_encode([
        "error" => "Missing username parameter. Example: ?username=stephiesbx"
    ]);
    exit;
}

// Sanitize username for safety
$username = preg_replace('/[^a-zA-Z0-9._-]/', '', $username);

// ===== PATH TO USER FOLDER =====
$userFolder = __DIR__ . "/$username";
$userIdFile = "$userFolder/userid.txt";

// ===== Ensure folder exists =====
if (!is_dir($userFolder)) {
    echo json_encode([
        "error" => "Folder for username '$username' does not exist.",
        "expected_folder" => $userFolder
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// ===== Load sessionid.txt =====
$sessionFile = __DIR__ . "/sessionid.txt";
if (!file_exists($sessionFile)) {
    echo json_encode(["error" => "Missing sessionid.txt file. Please create it and put your Threads sessionid inside."]);
    exit;
}
$sessionid = trim(file_get_contents($sessionFile));
if (empty($sessionid)) {
    echo json_encode(["error" => "sessionid.txt is empty. Please add your Threads sessionid."]);
    exit;
}

// ===== If userid.txt already exists and has content, return it directly =====
if (file_exists($userIdFile)) {
    $existingId = trim(file_get_contents($userIdFile));
    if (!empty($existingId)) {
        echo json_encode([
            "status"   => "success",
            "username" => $username,
            "userID"   => $existingId,
            "message"  => "UserID already exists in userid.txt. No API call made.",
            "file_path"=> $userIdFile
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }
}

// ===== THREADS GRAPHQL ENDPOINT =====
$url = "https://www.threads.com/graphql/query";

// ===== HEADERS =====
$csrfToken = "DHj2dn8qXGmpBdmTZGECIfG4TbqQUZiM"; // Update if needed

$headers = [
    "accept: */*",
    "accept-language: en-US,en;q=0.9",
    "content-type: application/x-www-form-urlencoded",
    "priority: u=1, i",
    "sec-ch-prefers-color-scheme: dark",
    "sec-ch-ua: \"Chromium\";v=\"140\", \"Not=A?Brand\";v=\"24\", \"Google Chrome\";v=\"140\"",
    "sec-ch-ua-full-version-list: \"Chromium\";v=\"140.0.7339.129\", \"Not=A?Brand\";v=\"24.0.0.0\", \"Google Chrome\";v=\"140.0.7339.129\"",
    "sec-ch-ua-mobile: ?0",
    "sec-ch-ua-platform: \"Windows\"",
    "sec-fetch-dest: empty",
    "sec-fetch-mode: cors",
    "sec-fetch-site: same-origin",
    "x-asbd-id: 359341",
    "x-bloks-version-id: 3783b86142c3f9b563a4e7b4277e99523c234b1734f46a286474592c36a615d9",
    "x-csrftoken: {$csrfToken}",
    "cookie: csrftoken={$csrfToken}; ds_user_id=74214170932; sessionid={$sessionid};",
    "x-fb-friendly-name: BarcelonaUsernameHovercardImplDirectQuery",
    "x-fb-lsd: syHDTc78Y-j4jlOk6Cste8",
    "x-ig-app-id: 238260118697367",
    "x-root-field-name: xdt_text_app_user_by_username",
    "Referer: https://www.threads.com/"
];

// ===== VARIABLES =====
$variables = [
    "username" => $username,
    "__relay_internal__pv__BarcelonaIsInternalUserrelayprovider" => false,
    "__relay_internal__pv__BarcelonaIsLoggedInrelayprovider" => true,
    "__relay_internal__pv__BarcelonaHasSpoilerStylingInforelayprovider" => true,
    "__relay_internal__pv__BarcelonaShouldShowFediverseM1Featuresrelayprovider" => false,
    "__relay_internal__pv__BarcelonaHasEventBadgerelayprovider" => false
];
$encodedVariables = urlencode(json_encode($variables));

// ===== BODY =====
$body = "av=17841474247966771&__user=0&__a=1&__req=2a&__hs=20351.HYP%3Abarcelona_web_pkg.2.1...0&dpr=1&__ccg=EXCELLENT&__rev=1027381369"
      . "&variables={$encodedVariables}"
      . "&server_timestamps=true"
      . "&doc_id=24552639777737673";

// ===== CURL REQUEST =====
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => $body
]);

$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

// ===== HANDLE CURL ERROR =====
if ($error) {
    echo json_encode(["error" => "CURL Error: $error"], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// ===== PARSE RESPONSE =====
$data = json_decode($response, true);

// ===== DETECT EXPIRED OR BANNED SESSION =====
if (isset($data['errors'][0]['summary']) && $data['errors'][0]['summary'] === "Incorrect Query") {
    echo json_encode([
        "error" => "Session expired or invalid. Update sessionid.txt with a fresh sessionid.",
        "raw_response" => $data
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// ===== HANDLE USER NOT FOUND =====
if (!isset($data['data']['user']) || $data['data']['user'] === null) {
    echo json_encode([
        "username" => $username,
        "error" => "User not found or private. Check username or cookies.",
        "raw_response" => $data
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// ===== EXTRACT USER ID =====
$userID = $data['data']['user']['pk'] ?? null;
if (!$userID) {
    echo json_encode([
        "error" => "UserID not found in response.",
        "raw_response" => $data
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// ===== SAVE userID to userid.txt =====
file_put_contents($userIdFile, $userID);

// ===== SUCCESS OUTPUT =====
echo json_encode([
    "status"   => "success",
    "username" => $username,
    "userID"   => $userID,
    "message"  => "UserID successfully fetched and saved to $username/userid.txt",
    "file_path"=> $userIdFile
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
