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

$sessionFile = __DIR__ . '/../sessionid.txt';
$sessionid = '';
if (file_exists($sessionFile)) {
    $sessionid = trim(file_get_contents($sessionFile));
}

// ===== STATIC 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-model: \"\"",
    "sec-ch-ua-platform: \"Windows\"",
    "sec-ch-ua-platform-version: \"15.0.0\"",
    "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=74214170932; sessionid={$sessionid}",
    "Referer: https://www.threads.com/"
];

// ===== USER ID (STATIC) =====
$USER_ID = "71569398008";

// ===== BUILD POST BODY =====
function buildBody($afterCursor = null) {
    global $USER_ID;
    $variables = [
        "after" => $afterCursor,
        "before" => null,
        "first" => 1,
        "last" => null,
        "userID" => $USER_ID,
        "__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";
}

// ===== CONFIG =====
$folder = $_GET['folder'] ?? "stephiebx24";
$folderPath = __DIR__ . '/' . basename($folder);
if (!is_dir($folderPath)) {
    mkdir($folderPath, 0777, true);
}
$OUTPUT_FILE = $folderPath . "/data.txt";
if (!file_exists($OUTPUT_FILE)) {
    file_put_contents($OUTPUT_FILE, json_encode([], JSON_PRETTY_PRINT));
}

// ===== DATE RANGE =====
$START_DATE = $_GET['start'] ?? "2025-09-15";
$END_DATE   = $_GET['end'] ?? "2025-09-19";

// ===== THREADS ENDPOINT =====
$url = "https://www.threads.net/graphql/query"; // FIXED to .net

// ===== LOAD EXISTING DATA =====
$existingData = [];
if (file_exists($OUTPUT_FILE)) {
    $jsonContent = file_get_contents($OUTPUT_FILE);
    $existingData = json_decode($jsonContent, true);
    if (!is_array($existingData)) $existingData = [];
}

// ---------- Helper Functions ----------
function fetchThreads($url, $headers, $afterCursor = null) {
    $body = buildBody($afterCursor);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_POSTFIELDS     => $body,
    ]);
    $result = curl_exec($ch);
    $error  = curl_error($ch);
    curl_close($ch);
    if ($error) return ['error' => $error];

    return json_decode($result, true);
}

// ===== SCRAPE STEP =====
$response = fetchThreads($url, $headers);

// Check if session expired or invalid
$sessionExpired = false;
$errorMessage   = "";

if (isset($response['errors'][0]['message']) && strtolower($response['errors'][0]['message']) === "execution error") {
    $sessionExpired = true;
    $errorMessage   = "SessionID is invalid or expired (execution error).";
}
elseif (isset($response['errors'][0]['code']) && $response['errors'][0]['code'] == 1675002) {
    $sessionExpired = true;
    $errorMessage   = "SessionID expired (code 1675002).";
}
elseif (isset($response['message']) && $response['message'] === "login_required") {
    $sessionExpired = true;
    $errorMessage   = "SessionID is invalid (login_required).";
}

echo json_encode([
    "raw_response"    => $response,
    "session_expired" => $sessionExpired,
    "message"         => $sessionExpired 
        ? $errorMessage 
        : "SessionID looks OK"
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
