<?php
$forceFresh = isset($_GET['fresh']) && $_GET['fresh'] === '1';

function getTitle($url) {
    $html = @file_get_contents($url);
    if ($html === false) return 'No Title (Failed to load)';

    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    libxml_clear_errors();

    $titles = $doc->getElementsByTagName('title');
    if ($titles->length === 0) return 'No Title';

    $fullTitle = $titles->item(0)->textContent;
    $cleanTitle = preg_replace('/\s*-\s*alcea.*$/', '', $fullTitle);
    return trim($cleanTitle);
}

$cacheKey = 'poipiku_cache';
$foundUrls = [];

if ($forceFresh || !isset($_COOKIE[$cacheKey])) {
    $url = 'https://poipiku.com/11331041';
    $html = file_get_contents($url);

    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    libxml_clear_errors();

    $xpath = new DOMXPath($doc);
    $links = $xpath->query('//a[@href]');
    foreach ($links as $link) {
        $href = $link->getAttribute('href');
        if (preg_match('#^/11331041/\d+\.html$#', $href)) {
            $fullUrl = 'https://poipiku.com' . $href;
            if (!in_array($fullUrl, $foundUrls)) {
                $foundUrls[] = $fullUrl;
                if (count($foundUrls) >= 3) break;
            }
        }
    }

    // Cache for 1 day
    setcookie($cacheKey, json_encode($foundUrls), time() + 86400, "/");
} else {
    $foundUrls = json_decode($_COOKIE[$cacheKey], true);
}

// Output HTML with iframe for each link
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Poipiku Cache</title>
</head>
<body>
<a href="?fresh=1">[~]</a><br><br>
<?php
foreach ($foundUrls as $pageUrl) {
    $title = htmlspecialchars(getTitle($pageUrl), ENT_QUOTES, 'UTF-8');
    echo "<iframe src=\"PoipikuGetImage.php?url=" . urlencode($pageUrl) . "\" width=\"400\" height=\"400\" frameborder=\"0\"></iframe><br>\n";
    echo "<a href=\"$pageUrl\" target=\"_blank\">$title</a><br>\n";
}
?>
</body>
</html>
