<?php
function getPixivUserArt($userId, $random, $page = 1) {
    $apiUrl = "https://www.pixiv.net/ajax/user/{$userId}/profile/all?useid={$userId}";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer: https://www.pixiv.net/'
    ));

    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);

    if (isset($data['body']['illusts'])) {
        $artworkIds = array_keys($data['body']['illusts']);
        $totalArtworks = count($artworkIds);
        $itemsPerPage = 5;
        $totalPages = ceil($totalArtworks / $itemsPerPage);
        $page = max(1, min($page, $totalPages));
        
        // Calculate start and end positions for current page
        $start = ($page - 1) * $itemsPerPage;
        $currentArtworkIds = array_slice($artworkIds, $start, $itemsPerPage);
        
        // Display navigation buttons
        echo "<div class='navigation' style='text-align: center; margin: 20px 0;'>";
        if ($page > 1) {
            echo "<button onclick='loadPage(".($page - 1).")' style='margin: 0 10px;'>&lt;&lt; Previous</button>";
        }
        echo "<span>Page {$page} of {$totalPages}</span>";
        if ($page < $totalPages) {
            echo "<button onclick='loadPage(".($page + 1).")' style='margin: 0 10px;'>Next &gt;&gt;</button>";
        }
        echo "</div>";
        
        // Start container for inline artworks
        echo "<div class='artworks-container' style='white-space: nowrap; text-align: center; margin: 0 auto; max-width: 100%; overflow: hidden;'>";
        
        // Display current batch of artworks in one line
        foreach ($currentArtworkIds as $artId) {
            $artLink = "https://www.pixiv.net/artworks/{$artId}";
            $artImageUrl = "https://embed.pixiv.net/artwork.php?illust_id={$artId}";
            
            // Fetch details only for the current artwork
            $html = @file_get_contents($artLink);
            $artTitle = "Untitled";
            
            if ($html !== false) {
                $dom = new DOMDocument();
                @$dom->loadHTML($html);
                $titleTag = $dom->getElementsByTagName('title')->item(0);
                $artTitle = $titleTag ? $titleTag->textContent : "Untitled";
                $artTitle = rtrim($artTitle, ' - pixiv');
            }
            
            echo "<div class='artwork-item' style='display: inline-block; width: 20%; min-width: 180px; margin: 0; padding: 5px; box-sizing: border-box; vertical-align: top;'>";


$safeTitle = htmlspecialchars(addslashes($artTitle), ENT_QUOTES);
$safeImageUrl = htmlspecialchars($artImageUrl, ENT_QUOTES);

echo "<img src='{$safeImageUrl}' alt='{$safeTitle}' title='{$safeTitle}' style='max-width: 100%; width: 100%; height: auto; cursor: pointer; border: 1px solid #eee;' onclick='openModal(\"{$safeImageUrl}\", \"{$safeTitle}\")'>";

            echo "<div class='artwork-title' style='white-space: normal; word-wrap: break-word; font-size: 12px; margin-top: 5px; height: 40px; overflow: hidden;'>";
            echo "<a href='{$artLink}' target='_blank' style='text-decoration: none; color: #0066cc;'>{$artTitle}</a>";
            echo "</div>";
            echo "</div>";
        }
        
        echo "</div>"; // Close artworks-container
        
        // Display navigation buttons again at bottom
        echo "<div class='navigation' style='text-align: center; margin: 20px 0;'>";
        if ($page > 1) {
            echo "<button onclick='loadPage(".($page - 1).")' style='margin: 0 10px;'>&lt;&lt; Previous</button>";
        }
        echo "<span>Page {$page} of {$totalPages}</span>";
        if ($page < $totalPages) {
            echo "<button onclick='loadPage(".($page + 1).")' style='margin: 0 10px;'>Next &gt;&gt;</button>";
        }
        echo "</div>";
        
        // Display total count
        echo "<div id='linkCount' style='text-align: center;'>Total artworks: {$totalArtworks}</div>";
        
        // Display all links in details section
        echo "<details style='margin: 20px; text-align: center;'>";
        echo "<summary style='cursor: pointer;'>Click to view all artwork links</summary>";
        echo "<pre style='white-space: pre-wrap; text-align: left; background: #f5f5f5; padding: 10px; border-radius: 5px;'>";
        foreach ($artworkIds as $artId) {
            echo "https://www.pixiv.net/artworks/{$artId}\n";
        }
        echo "</pre>";
        echo "</details>";
    } else {
        echo "<div style='text-align: center;'>No artworks found for the given user.</div>";
    }
}

// Get parameters from URL
$userId = isset($_GET['userId']) ? $_GET['userId'] : '75406576'; // Default user ID
$random = isset($_GET['random']);
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;

// Add user ID input form
echo '<div style="margin: 20px; text-align: center;">';
echo '<form method="get" action="">';
echo 'Pixiv User ID: <input type="text" name="userId" value="'.$userId.'" placeholder="Enter Pixiv User ID" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px;">';
echo '<input type="submit" value="Load Artworks" style="padding: 8px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; margin-left: 10px;">';
echo '<input type="hidden" name="page" value="1">';
echo '</form>';
echo '</div>';

// Display artworks
getPixivUserArt($userId, $random, $page);
?>

<!-- Modal Structure -->
<div id="myModal" class="modal">
    <span class="close" onclick="closeModal()">&times;</span>
    <img class="modal-content" id="modalImg">
    <div id="imgTitle" style="color: white; text-align: center; padding: 10px;"></div>
</div>

<script>
// Function to load a specific page
function loadPage(page) {
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.set('page', page);
    window.location.search = urlParams.toString();
}

// Function to open modal with image and title
function openModal(imageUrl, title) {
    document.getElementById("modalImg").src = imageUrl;
    document.getElementById("imgTitle").innerText = title;
    document.getElementById("myModal").style.display = "block";
}

// Function to close the modal
function closeModal() {
    document.getElementById("myModal").style.display = "none";
}

// Close modal when clicking outside
window.onclick = function(event) {
    if (event.target == document.getElementById("myModal")) {
        closeModal();
    }
}
</script>

<style>
/* Modal Styles */
.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255,255,255,0.9); 
}

.modal-content {
    display: block;
    margin: 5% auto;
    max-width: 80%;
    max-height: 80%;
    background-color: white; 
}

.close {
    position: absolute;
    top: 20px;
    right: 35px;
    color: white;
    font-size: 40px;
    font-weight: bold;
    cursor: pointer;
}

/* Navigation buttons */
.navigation button {
    padding: 8px 16px;
    background-color: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.navigation button:hover {
    background-color: #e0e0e0;
}

.navigation span {
    margin: 0 15px;
    font-weight: bold;
}

/* Artwork items */
.artwork-item {
    transition: transform 0.2s;
}

.artwork-item:hover {
    transform: scale(1.02);
}

.artwork-title a:hover {
    text-decoration: underline;
}
</style>
