
<!---https://github.com/daydreamer-json/pixiv-ajax-api-docs?tab=readme-ov-file#get-user-information-focus-on-artwork-->
<?php
// Default URL base
$defaultBaseUrl = "https://www.pixiv.net/artworks/";

// --- CONFIGURATION ---
// Set the maximum number of comments to fetch in a single call
$COMMENT_LIMIT = 30;
$COMMENT_OFFSET = 0; // Start at the first page

// Get ?url= parameter if exists
$inputUrl = $_GET['url'] ?? null;
$artworkId = null;

// Extract artwork ID (number at end) from given URL or fallback
if ($inputUrl) {
    if (preg_match('#/(\d+)(?:[/?]|$)#', $inputUrl, $matches)) {
        $artworkId = $matches[1];
    }
}

// Fallback to a default artwork if no ID found
$artworkId = $artworkId ?? "127908186";


// --- FUNCTIONS ---

/**
 * Fetch Pixiv Artwork Metadata via API
 */
function fetchPixivData($illust_id) {
    $apiUrl = "https://www.pixiv.net/ajax/illust/{$illust_id}";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
            'Referer: https://www.pixiv.net/',
            // 'Cookie: PHPSESSID=XXX;', // Uncomment if needed for private/NSFW works
        ],
        CURLOPT_ENCODING       => 'gzip',
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        return ['error' => true, 'message' => "HTTP {$httpCode} - API request failed for artwork"];
    }
    
    return json_decode($response, true);
}

/**
 * Fetch a single page of Pixiv Artwork Comments (Max 30)
 * Uses the API endpoint confirmed by user testing: /illusts/comments/roots
 */
function fetchPixivCommentsPage($illust_id, $limit, $offset) {
    // Confirmed working endpoint
    $apiUrl = "https://www.pixiv.net/ajax/illusts/comments/roots?illust_id={$illust_id}&offset={$offset}&limit={$limit}";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
            // Essential for API access
            'Referer: https://www.pixiv.net/artworks/' . $illust_id, 
        ],
        CURLOPT_ENCODING       => 'gzip',
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        return ['error' => true, 'message' => "HTTP {$httpCode} - API request failed for comments"];
    }
    
    return json_decode($response, true);
}


// --- MAIN EXECUTION ---

// 1. Fetch artwork metadata
$artworkData = fetchPixivData($artworkId);

if (isset($artworkData['error']) && $artworkData['error']) {
    die("Error: " . ($artworkData['message'] ?? 'Failed to fetch artwork'));
}

// Extract metadata
$title = $artworkData['body']['title'] ?? 'No Title';
$imageUrl = $artworkData['body']['urls']['original'] ?? $artworkData['body']['urls']['regular'] ?? null;
$views = $artworkData['body']['viewCount'] ?? 0;
$bookmarks = $artworkData['body']['bookmarkCount'] ?? 0;
$likes = $artworkData['body']['likeCount'] ?? 0;
$totalComments = $artworkData['body']['commentCount'] ?? 0;
$artworkUrl = $defaultBaseUrl . $artworkId;


// 2. Display Artwork Info
echo '<br><a href="' . htmlspecialchars($artworkUrl) . '" target="_blank">' 
     . htmlspecialchars($title) . '</a> ';

if ($imageUrl) {
    // Use a proxy to avoid referer issues when hotlinking the image preview
    $proxyImageUrl = "https://i.pixiv.re/" . preg_replace('#^https?://i\.pximg\.net/#', '', $imageUrl);
    echo '<a href="' . htmlspecialchars($imageUrl) . '" target="_blank">'
         . '<img src="' . htmlspecialchars($proxyImageUrl) . '" alt="preview" style="height:20px; vertical-align:middle;"></a> ';
}

echo sprintf(
    'Views: %s | Bookmarks: %s | Likes: %s | Comments: %s',
    htmlspecialchars($views),
    htmlspecialchars($bookmarks),
    htmlspecialchars($likes),
    htmlspecialchars($totalComments)
);

// --- 3. Fetch and Display the first page of Comments ---
echo '<hr><h3>First ' . $COMMENT_LIMIT . ' Comments (Offset: ' . $COMMENT_OFFSET . ')</h3>';

if ($totalComments > 0) {
    // Perform the single API call for the first page
    $commentData = fetchPixivCommentsPage($artworkId, $COMMENT_LIMIT, $COMMENT_OFFSET);

    if (isset($commentData['error']) && $commentData['error']) {
        echo "<i>Could not load comments: " . htmlspecialchars($commentData['message']) . "</i>";
    } else {
        $allComments = $commentData['body']['comments'] ?? [];
        
        if (empty($allComments)) {
            echo "<i>The API returned no comments for this offset.</i>";
        } else {
            echo '<h4>Displaying ' . count($allComments) . ' comments:</h4>';
            echo '<ul style="font-size: 0.9em; list-style-type: none; padding-left: 10px;">';
            foreach ($allComments as $comment) {
                $userName = $comment['userName'] ?? 'Unknown User';
                // Clean comment text for display
                $commentText = nl2br(htmlspecialchars(strip_tags($comment['comment']))); 
                
                echo '<li style="margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 5px;">';
                echo '<strong>' . htmlspecialchars($userName) . ':</strong>';
                echo '<blockquote style="margin: 5px 0 0 15px; padding: 0; color: #333;">' . $commentText . '</blockquote>';
                echo '</li>';
            }
            echo '</ul>';
        }
    }
} else {
    echo "<i>No comments to display.</i>";
}

?>