<?php
function fetchRedditPosts($defaultSubreddit = 'deutschland', $limit = 10, $after = '') {
    $debug = true; // Set to false in production

    // Get subreddit URL from query or use default
    $subredditUrl = isset($_GET['redditurl']) ? $_GET['redditurl'] : "https://www.reddit.com/r/$defaultSubreddit/";

    // Extract /r/{subreddit}
    if (preg_match('~reddit\.com/(r/[^/?#]+)~i', $subredditUrl, $matches)) {
        $subredditPath = $matches[1]; // e.g. r/deutschland
        $subreddit = basename($subredditPath); // e.g. deutschland
    } else {
        echo "<strong>Invalid subreddit URL.</strong>";
        return;
    }

    echo "<p>Fetching posts from: <strong>/r/$subreddit</strong></p>\n";

    // Construct Reddit API endpoint
    $baseUrl = "https://www.reddit.com/r/$subreddit.json?limit=$limit";
    if (!empty($after)) {
        $baseUrl .= "&after=" . urlencode($after);
    }

    // Initialize cURL
    $ch = curl_init($baseUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (RedditScraper/1.0)');
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo "<strong>cURL error:</strong> " . curl_error($ch);
        curl_close($ch);
        return;
    }

    curl_close($ch);
    $json = json_decode($response, true);

    // Check if response contains expected data
    if (!isset($json['data']['children'])) {
        echo "<strong>No posts found or unexpected response format.</strong><br>";
        if ($debug) {
            echo "<pre>Invalid response:\n" . htmlspecialchars($response) . "</pre>";
        }
        return;
    }

    // Output each post
    foreach ($json['data']['children'] as $item) {
        $post = $item['data'];
        $title = htmlspecialchars($post['title'], ENT_QUOTES);
        $link = 'https://www.reddit.com' . $post['permalink'];
        $text = isset($post['selftext']) ? strip_tags($post['selftext']) : '';
        $snippet = mb_substr($text, 0, 150);

        // Determine image
        $image = '';
        if (!empty($post['preview']['images'][0]['source']['url'])) {
            $image = html_entity_decode($post['preview']['images'][0]['source']['url']);
        } elseif (preg_match('/\.(jpg|jpeg|png|gif)$/i', $post['url'])) {
            $image = $post['url'];
        }

        // Output HTML
        echo "<h3><a href=\"$link\" target=\"_blank\">$title</a></h3>\n";
        echo "<a href=\"postfetch.php?url=$link\" style=\"font-size:1.2em\">&gt;&gt;</a><br>\n";
        if (!empty($image)) {
            echo "<img src=\"$image\" alt=\"Post image\" style=\"max-width:400px;\"><br>\n";
        }
        echo "<p>$snippet...</p>\n<hr>\n";
    }

    // Pagination
    if (!empty($json['data']['after'])) {
        $nextAfter = htmlspecialchars($json['data']['after'], ENT_QUOTES);
        $query = $_GET;
        $query['after'] = $nextAfter;
        $queryStr = http_build_query($query);
        echo "<a href=\"{$_SERVER['PHP_SELF']}?$queryStr\">Next Page →</a>";
    }
}

// Handle ?after= for pagination
$after = isset($_GET['after']) ? $_GET['after'] : '';
fetchRedditPosts('deutschland', 10, $after);
?>
