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

// ===== Load sessionid.txt =====
$sessionFile = __DIR__ . "/sessionid.txt";
if (!file_exists($sessionFile)) {
    echo json_encode(["error" => "Missing sessionid.txt"]);
    exit;
}
$sessionid = trim(file_get_contents($sessionFile));
if (empty($sessionid)) {
    echo json_encode(["error" => "sessionid.txt is empty"]);
    exit;
}

// ===== URL =====
$url = "https://www.threads.com/graphql/query";

// ===== HEADERS =====
$headers = [
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:143.0) Gecko/20100101 Firefox/143.0",
    "Accept: */*",
    "Accept-Language: en-US,en;q=0.5",
    "Content-Type: application/x-www-form-urlencoded",
    "X-FB-Friendly-Name: BarcelonaFeedPaginationDirectQuery",
    "X-BLOKS-VERSION-ID: 9c2a3a2c148f47e6c93f568b766d8faac1230c4cd1107ef10bae6d0f5d364126",
    "X-CSRFToken: aTIvAWkVifvI8DxSDx2809sOYFOgGAfO",
    "X-IG-App-ID: 238260118697367",
    "X-Root-Field-Name: xdt_api__v1__feed__text_post_app_timeline__connection",
    "X-FB-LSD: soz9rxp2gSexoOlqfJber1",
    "X-ASBD-ID: 359341",
    "Alt-Used: www.threads.com",
    "Sec-Fetch-Dest: empty",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Site: same-origin",
    "Cookie: csrftoken=aTIvAWkVifvI8DxSDx2809sOYFOgGAfO; sessionid={$sessionid};"
];

// ===== Fixed Variables =====
$baseVariables = [
    "before" => null,
    "data" => [
        "feed_view_info" => "[]",
        "pagination_source" => "text_post_feed_threads",
        "reason" => "pagination"
    ],
    "first" => 20,  // request batch size
    "last" => null,
    "variant" => "for_you",
    "__relay_internal__pv__BarcelonaIsLoggedInrelayprovider" => true,
    "__relay_internal__pv__BarcelonaHasInlineReplyComposerrelayprovider" => true,
    "__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,
    "__relay_internal__pv__BarcelonaIsReplyApprovalEnabledrelayprovider" => false
];

// ===== Fixed Body Data =====
$baseBodyData = [
    "av" => "17841474247966771",
    "__user" => "0",
    "__a" => "1",
    "__req" => "13",
    "__hs" => "20363.HYP:barcelona_web_pkg.2.1...0",
    "dpr" => "1",
    "__ccg" => "UNKNOWN",
    "__rev" => "1027914693",
    "__s" => "fhln9g:agt1ts:mkbzsq",
    "__hsi" => "7556764194784155699",
    "__dyn" => "7xeUmwlEnwn8K2Wmh0no6u5U4e0yoW3q32360CEbo1nEhw2nVE4W0qa0FE2awgo9oO0n24oaEd82lwv89k2C1Fwc60D85m1mzXwae4UaEW0Loco5G0zK5o4q0HU1IEGdwtU2ewbS1LwTwKG0hq1Iwqo9Epxq261bg26wHxW17y9UjgbVE-2G7E2own85SU7y0gS",
    "__csr" => "ghNAx2WbWsky8RPmYhOO6QQWAlemh2unHK68W5GUqyE9F4icyu0x8aoeE01u-8eU6CayNaUjgKa2U0Zq5UgwdFwaDwqh74e2it0Lxe0IoG0PUbo2gwpUGcGh02780xCAi05UVkm0YQ781mwn6zZ0haf4wODwXwLic0g2i12xuzKFeqm9Wc3eu0HU3Wo1dEW48aAm1giQ3G36Ph8hBw90GUB7AEU5Wy5CFowoV2N0lwNwdimpo6i0fx403MEzl1O3l0mo06GCi5kle3e2-0blBhk0XU3Xg1AU1Lrwc-Ww",
    "__hsdp" => "g8QW6Eb5i0jZxqP7168PBy3wEyx4EBawWzEh6iQlFV9nb5MRyC4xgUl3BjJyh0AmqwIpIQ6EBF0gQ9Ew2pS1VwgE3ip8760zU1d81r85ybDx23S",
    "__hblp" => "4g1h44okwwwDyKpwhU-l90ywby784SEiU8EkwRwCwNUgUbobpEvzEpxaawPxaq1Jxa1pwXwkE6u5E5y1wAzUzwwx6iiq7Q4Eb84W2JosUvxC1sCyF8S7A7k",
    "__sjsp" => "g8QWNr2Fkw4_omINMw7OwZyCoEBawWzEh6iQlFailO2uwRyC4xgUl3BjzN0EkqwIp4c",
    "__comet_req" => "29",
    "fb_dtsg" => "NAfuM3D3Nyr_axMYBYKnftZdf_N8WYPqeNLT1HQx-1gx-d2Gon6iH4w:17864863018060157:1759248342",
    "jazoest" => "26243",
    "lsd" => "soz9rxp2gSexoOlqfJber1",
    "__spin_r" => "1027914693",
    "__spin_b" => "trunk",
    "__spin_t" => "1759446271",
    "__jssesw" => "2",
    "__crn" => "comet.threads.BarcelonaHomeRoute",
    "fb_api_caller_class" => "RelayModern",
    "fb_api_req_friendly_name" => "BarcelonaFeedPaginationDirectQuery",
    "server_timestamps" => "true",
    "doc_id" => "25089044884026128"
];

$allPosts = [];
$after = null;

for ($i = 0; $i < 30; $i++) {
    // wait 15 seconds before each request (skip waiting on first run if you want)
    if ($i > 0) {
        sleep(3);
    }

    $variables = $baseVariables;
    if ($after) {
        $variables["after"] = $after;
    }

    $bodyData = $baseBodyData;
    $bodyData["variables"] = json_encode($variables);
    $body = http_build_query($bodyData);

    $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);

    if ($error) {
        echo json_encode(["error" => $error]);
        exit;
    }

    $json = json_decode($response, true);

    if (isset($json['data']['feedData']['edges'])) {
        foreach ($json['data']['feedData']['edges'] as $edge) {
            $post = $edge['node']['text_post_app_thread']['thread_items'][0]['post'] ?? null;
            if (!$post) continue;

            $caption = $post['caption']['text'] ?? '';
            $likeCount = $post['like_count'] ?? 0;
            $replyCount = $post['direct_reply_count'] ?? 0;
            $repostCount = $post['repost_count'] ?? 0;
            $quoteCount = $post['quote_count'] ?? 0;

            $engagement = $likeCount + $replyCount + $repostCount + $quoteCount;

            // only keep posts with engagement > 499
            if ($engagement > 499) {
                // detect type
                $type = "text";
                if (!empty($post['carousel_media'])) {
                    $type = "carousel";
                } elseif (!empty($post['video_versions'])) {
                    $type = "video";
                } elseif (!empty($post['image_versions2']['candidates'])) {
                    $type = "image";
                }

                // convert timestamp
                $timePosted = isset($post['taken_at']) ? date("Y-m-d H:i:s", $post['taken_at']) : null;

                $allPosts[] = [
                    "caption" => $caption,
                    "total_engagement" => $engagement,
                    "type" => $type,
                    "time_posted" => $timePosted
                ];
            }
        }

        $pageInfo = $json['data']['feedData']['page_info'] ?? null;
        if ($pageInfo && !empty($pageInfo['has_next_page']) && !empty($pageInfo['end_cursor'])) {
            $after = $pageInfo['end_cursor'];
        } else {
            break; // stop if no more pages
        }
    } else {
        break; // stop if response is invalid
    }
}

// ===== After scraping finishes =====
echo json_encode(["posts" => $allPosts], JSON_PRETTY_PRINT);

// ===== Save captions to captions.txt =====
$captions = array_column($allPosts, 'caption');
$decodedCaptions = [];

foreach ($captions as $caption) {
    if (!$caption) continue;

    // Decode UTF-8 safely (handles emojis, Unicode, etc.)
    $caption = json_decode('"' . addcslashes($caption, '"\\') . '"');

    // Fallback if decoding fails
    if ($caption === null) {
        $caption = $caption;
    }

    // Replace real line breaks with visible "\n"
    $caption = str_replace(["\r\n", "\r", "\n"], " \\n ", $caption);

    // Clean up double spaces (optional)
    $caption = preg_replace('/\s+/', ' ', $caption);

    // Trim and store
    $decodedCaptions[] = trim($caption);
}

// Join all captions separated by *real* newlines
$captionsText = implode(PHP_EOL, $decodedCaptions);

// Save to file
file_put_contents(__DIR__ . '/captions.txt', $captionsText);

echo "\nSaved " . count($decodedCaptions) . " captions to captions.txt\n";
