<?php
header('Content-Type: text/html; charset=utf-8');

$userAgent = 'Mozilla/5.0 (reddit-fetch/1.0; +https://example.com)';

if (empty($_GET['url'])) {
    exit('Error: Missing "url" query parameter.');
}

$inputUrl = $_GET['url'];

// Remove trailing slash if exists
$inputUrl = rtrim($inputUrl, '/');

// Append '.json' if not already there
if (!str_ends_with($inputUrl, '.json')) {
    $jsonUrl = $inputUrl . '/.json';
} else {
    $jsonUrl = $inputUrl;
}

// Extract base URL for user/permalink links
$parsedUrl = parse_url($inputUrl);
if (!$parsedUrl || !isset($parsedUrl['scheme'], $parsedUrl['host'])) {
    exit('Error: Invalid URL structure.');
}
$baseUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'];

// Fetch JSON
$ch = curl_init($jsonUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => $userAgent,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
    exit('cURL error: ' . curl_error($ch));
}
curl_close($ch);

$data = json_decode($response, true);
if (!$data || !isset($data[0]['data']['children'][0]['data'])) {
    exit('Error: Failed to fetch or parse Reddit data.');
}

$post = $data[0]['data']['children'][0]['data'];
$comments = $data[1]['data']['children'] ?? [];

function extract_images(array $post): array {
    $images = [];

    // Direct image URL in post url (jpg/png/gif)
    if (!empty($post['url']) && preg_match('~\.(jpe?g|png|gif)$~i', $post['url'])) {
        $images[] = html_entity_decode(str_replace('&amp;', '&', $post['url']));
    }

    // Preview images
    if (!empty($post['preview']['images'])) {
        foreach ($post['preview']['images'] as $img) {
            if (!empty($img['source']['url'])) {
                $url = html_entity_decode(str_replace('&amp;', '&', $img['source']['url']));
                if (!in_array($url, $images, true)) {
                    $images[] = $url;
                }
            }
        }
    }

    // Gallery images
    if (!empty($post['gallery_data']['items']) && !empty($post['media_metadata'])) {
        foreach ($post['gallery_data']['items'] as $item) {
            $mediaId = $item['media_id'] ?? null;
            if ($mediaId && !empty($post['media_metadata'][$mediaId]['s']['u'])) {
                $url = html_entity_decode(str_replace('&amp;', '&', $post['media_metadata'][$mediaId]['s']['u']));
                if (!in_array($url, $images, true)) {
                    $images[] = $url;
                }
            }
        }
    }

    return $images;
}

function render_comment(array $node, int $depth = 0, string $baseUrl = '', string $postPermalink = ''): void {
    if (($node['kind'] ?? '') !== 't1') return;
    $c = $node['data'];

    $author = htmlspecialchars($c['author']);
    $authorLink = '<a href="' . $baseUrl . '/user/' . $author . '" target="_blank" rel="noopener noreferrer">u/' . $author . '</a>';

    $commentId = $c['id'] ?? '';
    $commentPermalink = rtrim($baseUrl, '/') . $postPermalink . $commentId;

    echo '<div style="margin-left:' . ($depth * 20) . 'px; border-left: 2px solid #ccc; padding-left:10px; margin-top:10px;">';
    echo '<p><strong>' . $authorLink . '</strong> (' . intval($c['score']) . ' pts) ';
    echo '<a href="' . htmlspecialchars($commentPermalink) . '" target="_blank" rel="noopener noreferrer" style="font-weight:normal; font-size:0.85em; margin-left:10px;">[link]</a></p>';
    echo '<div>' . html_entity_decode($c['body_html'], ENT_QUOTES | ENT_HTML5) . '</div>';
    echo '</div>';

    if (!empty($c['replies']['data']['children'])) {
        foreach ($c['replies']['data']['children'] as $child) {
            render_comment($child, $depth + 1, $baseUrl, $postPermalink);
        }
    }
}

$images = extract_images($post);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title><?= htmlspecialchars($post['title']) ?></title>
<style>
body { font-family: Arial,sans-serif; max-width: 900px; margin: 30px auto; color: #222; }
h1 a { color: #0079d3; text-decoration: none; }
h1 a:hover { text-decoration: underline; }
img { max-width: 100%; height: auto; margin: 15px 0; }
a { color: #0079d3; text-decoration: none; }
a:hover { text-decoration: underline; }
.post-text { margin: 15px 0; line-height: 1.4em; }
</style>
</head>
<body>

<h1><a href="<?= htmlspecialchars($baseUrl . $post['permalink']) ?>" target="_blank" rel="noopener noreferrer">
    <?= htmlspecialchars($post['title']) ?></a></h1>

<p>Posted by 
<a href="<?= htmlspecialchars($baseUrl . '/user/' . $post['author']) ?>" target="_blank" rel="noopener noreferrer">u/<?= htmlspecialchars($post['author']) ?></a>
in 
<a href="<?= htmlspecialchars($baseUrl . '/r/' . $post['subreddit']) ?>" target="_blank" rel="noopener noreferrer">r/<?= htmlspecialchars($post['subreddit']) ?></a><br>
<?= date('F j, Y \a\t H:i', $post['created_utc']) ?> | <?= intval($post['score']) ?> points | <?= intval($post['num_comments']) ?> comments
</p>

<?php if (!empty($post['selftext_html'])): ?>
    <div class="post-text"><?= html_entity_decode($post['selftext_html'], ENT_QUOTES | ENT_HTML5) ?></div>
<?php elseif (!empty($post['selftext'])): ?>
    <div class="post-text"><?= nl2br(htmlspecialchars($post['selftext'])) ?></div>
<?php endif; ?>

<?php if ($images): ?>
<h2>Images</h2>
<?php foreach ($images as $img): ?>
    <img src="<?= htmlspecialchars($img) ?>" alt="Reddit image" />
<?php endforeach; ?>
<?php endif; ?>

<h2>Comments</h2>
<?php foreach ($comments as $comment): ?>
    <?php render_comment($comment, 0, $baseUrl, $post['permalink']); ?>
<?php endforeach; ?>

</body>
</html>
