<script>
document.addEventListener('DOMContentLoaded', function() {
  // Fix perennialte.ch links
  document.querySelectorAll('a[href^="https://pixiv.perennialte.ch"]').forEach(link => {
    link.href = link.href.replace("https://pixiv.perennialte.ch", "https://pixiv.net");
  });
});
</script>

<?php
// User navigation (optional, can be customized)
echo '<a href="?userId=115969453" style="color:blue">Cea</a> ';
echo '<a target="_blank" href="?userId=75406576" style="color:blue">Alcea</a>';
echo '<a target="_blank" href="https://pixivfe-docs.pages.dev/instance-list/#clearnet" style="color:gray">PixivFE instances</a><hr>';

/**
 * Gets the latest 5 artwork IDs from Pixiv user profile
 */
function getPixivArtworkIds($userId, $limit = 5) {
    $apiUrl = "https://www.pixiv.net/ajax/user/{$userId}/profile/all";
    
    $context = stream_context_create([
        'http' => [
            'header' => "User-Agent: Mozilla/5.0\r\nReferer: https://www.pixiv.net/"
        ],
        'ssl' => [
            'verify_peer' => false
        ]
    ]);
    
    $response = @file_get_contents($apiUrl, false, $context);
    if (!$response) return [];
    
    $data = json_decode($response, true);
    if (empty($data['body']['illusts'])) return [];
    
    // Get the most recent artwork IDs
    $artworkIds = array_keys($data['body']['illusts']);
    
    return array_slice($artworkIds, 0, $limit);
}

// Configuration: Default userId to Alcea's if not specified
$userId = $_GET['userId'] ?? '75406576';  // Default: Alcea

// Get the latest 5 artwork IDs
$artworkIds = getPixivArtworkIds($userId, 5);

// Loop through artwork IDs and fetch their data via the custom URL
foreach ($artworkIds as $artworkId) {
    // Generate the full URL to fetch the artwork
    $singlefetchUrl = "https://alceawis.de/other/extra/fetchdata/singlefetch.php?url=" . urlencode("https://www.pixiv.net/artworks/{$artworkId}");
    
    // Fetch the output from the generated URL
    $output = @file_get_contents($singlefetchUrl, false, stream_context_create([
        'http' => ['timeout' => 5]
    ]));
    
    // Display the result or an error message if loading failed
    echo $output ?: "Failed to load artwork: {$artworkId}<br>";
}
?>
