<?php
// Get URL from query parameter
if (!isset($_GET['url']) || !filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
    die("Invalid or missing 'url' parameter.");
}

$url = $_GET['url'];

// Fetch HTML using cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
$html = curl_exec($ch);
curl_close($ch);

if (!$html) {
    die("Failed to fetch page.");
}

// Parse HTML
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
libxml_clear_errors();

$xpath = new DOMXPath($dom);
$images = $xpath->query("//img");

$poipikuImages = [];

foreach ($images as $img) {
    $src = $img->getAttribute('src');

    // Normalize URLs
    if (strpos($src, '//') === 0) {
        $src = 'https:' . $src;
    } elseif (strpos($src, '/') === 0) {
        $parsed = parse_url($url);
        $src = $parsed['scheme'] . '://' . $parsed['host'] . $src;
    }

    // Filter img.poipiku.com images
    if (preg_match('#^https?://img\.poipiku\.com/user_img\d+/.*#', $src)) {
        $poipikuImages[] = $src;
    }
}

// Output as <img> tags
if (!empty($poipikuImages)) {
    foreach ($poipikuImages as $imgUrl) {
        $imgUrl = str_replace('_640', '_360', $imgUrl);
        echo '<img src="' . htmlspecialchars($imgUrl) . '" style="max-width:300px; margin:10px;">' . PHP_EOL;
    }
} else {
    echo "";
}
?>
