<?php
// ===== Load session ID dynamically =====
$sessionFile = __DIR__ . '/sessionid.txt';

if (!file_exists($sessionFile)) {
    die(json_encode(["error" => "Missing sessionid.txt file. Please create it and add your Threads session ID."]));
}

$sessionId = trim(file_get_contents($sessionFile));
if (empty($sessionId)) {
    die(json_encode(["error" => "sessionid.txt is empty. Please add your Threads session ID."]));
}

// ===== Determine folder and userid.txt path =====
if (!isset($_GET['folder'])) {
    die(json_encode(["error" => "Missing 'folder' parameter in URL. Example: ?folder=stephiesbx"]));
}

$folder = basename($_GET['folder']); // sanitize folder
$userIdFile = __DIR__ . "/$folder/userid.txt";

// ===== If userid.txt is missing or empty → fetch it automatically =====
if (!file_exists($userIdFile) || trim(file_get_contents($userIdFile)) === '') {
    $getUserUrl = "https://{$_SERVER['HTTP_HOST']}" . dirname($_SERVER['SCRIPT_NAME']) . "/getuser.php?username=" . urlencode($folder);

    // Make internal HTTP request to getuser.php
    $ch = curl_init($getUserUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);

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

    if ($error) {
        die(json_encode(["error" => "Failed to fetch userID via getuser.php: $error"]));
    }

    $result = json_decode($response, true);

    if (!isset($result['userID']) || empty($result['userID'])) {
        die(json_encode([
            "error" => "getuser.php failed to return a valid userID.",
            "raw_response" => $result
        ]));
    }
}

// ===== Now load the userID safely =====
$userId = trim(file_get_contents($userIdFile));

// ===== Threads headers =====
$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.128\", \"Not=A?Brand\";v=\"24.0.0.0\", \"Google Chrome\";v=\"140.0.7339.128\"",
    "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: dq5eSEB5U8XD8qBr2FmP5HZCcwoVn5oa",
    "x-fb-friendly-name: BarcelonaProfileThreadsTabRefetchableDirectQuery",
    "x-fb-lsd: ABEaAm91qdVTXUVG9TWJfq",
    "x-ig-app-id: 238260118697367",
    "x-root-field-name: xdt_api__v1__text_feed__user_id__profile__connection",
    "cookie: csrftoken=dq5eSEB5U8XD8qBr2FmP5HZCcwoVn5oa; ds_user_id={$userId}; sessionid={$sessionId};",
    "Referer: https://www.threads.com/"
];

// ===== Build dynamic POST body =====
function buildBody($afterCursor = null) {
    global $userId;

    $variables = [
        "after" => $afterCursor,
        "before" => null,
        "first" => 20,
        "last" => null,
        "userID" => $userId,
        "__relay_internal__pv__BarcelonaIsLoggedInrelayprovider" => true,
        "__relay_internal__pv__BarcelonaHasProfileSelfReplyContextrelayprovider" => false,
        "__relay_internal__pv__BarcelonaHasInlineReplyComposerrelayprovider" => true,
        "__relay_internal__pv__BarcelonaIsReplyApprovalEnabledrelayprovider" => false,
        "__relay_internal__pv__BarcelonaIsReplyApprovalsConsumptionEnabledrelayprovider" => false,
        "__relay_internal__pv__BarcelonaHasEventBadgerelayprovider" => false,
        "__relay_internal__pv__BarcelonaIsSearchDiscoveryEnabledrelayprovider" => false,
        "__relay_internal__pv__BarcelonaHasSelfThreadCountrelayprovider" => false,
        "__relay_internal__pv__IsTagIndicatorEnabledrelayprovider" => true,
        "__relay_internal__pv__BarcelonaHasDeepDiverelayprovider" => false,
        "__relay_internal__pv__BarcelonaHasGhostPostConsumptionrelayprovider" => false,
        "__relay_internal__pv__BarcelonaHasSpoilerStylingInforelayprovider" => true,
        "__relay_internal__pv__BarcelonaOptionalCookiesEnabledrelayprovider" => true,
        "__relay_internal__pv__BarcelonaQuotedPostUFIEnabledrelayprovider" => false,
        "__relay_internal__pv__BarcelonaHasTopicTagsrelayprovider" => true,
        "__relay_internal__pv__BarcelonaIsCrawlerrelayprovider" => false,
        "__relay_internal__pv__BarcelonaHasDisplayNamesrelayprovider" => false,
        "__relay_internal__pv__BarcelonaCanSeeSponsoredContentrelayprovider" => false,
        "__relay_internal__pv__BarcelonaShouldShowFediverseM075Featuresrelayprovider" => false,
        "__relay_internal__pv__BarcelonaImplicitTrendsGKrelayprovider" => false,
        "__relay_internal__pv__BarcelonaIsInternalUserrelayprovider" => false
    ];

    $variablesEncoded = urlencode(json_encode($variables));

    return "av=17841474247966771&__user=0&__a=1&__req=7&__hs=20350.HYP%3Abarcelona_web_pkg.2.1...0&dpr=1&__ccg=EXCELLENT&__rev=1027328602"
         . "&variables={$variablesEncoded}"
         . "&server_timestamps=true"
         . "&doc_id=24076404572036726";
}
