<?php
// Initialize cURL
$ch = curl_init();

// Check if the vroidurl query string is present
if (isset($_GET['vroidurl'])) {
    // Sanitize the input to prevent security issues
    $url = filter_var($_GET['vroidurl'], FILTER_SANITIZE_URL);
} else {
    // Default URL if vroidurl is not provided
    $url = "https://hub.vroid.com/en/characters/7345373191746796787/models/3685792491167474217";
}

// Set the URL to fetch
curl_setopt($ch, CURLOPT_URL, $url);

// Set the user agent to Firefox
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0");

// Set options to return the result as a string and to follow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

// Execute the request
$response = curl_exec($ch);

// Check for cURL errors
if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    // Load the HTML into a DOMDocument object
    $dom = new DOMDocument();
    @$dom->loadHTML($response);

    // Create an XPath object for querying the DOM
    $xpath = new DOMXPath($dom);

    // Extract the title
    $title = $xpath->query('//title')->item(0)->nodeValue;

    // Extract the Open Graph image (or fallback to Twitter image if needed)
    $ogImage = $xpath->query('//meta[@property="og:image"]/@content')->item(0)->nodeValue;
    $twitterImage = $xpath->query('//meta[@name="twitter:image"]/@content')->item(0)->nodeValue;

    // Use the OG image or Twitter image
    $image = $ogImage ? $ogImage : $twitterImage;

    // Display the link with the title as the link text
    echo "<a href='$url' target='_blank'>$title</a> <a href='${url}/embed' target='_blank'>»</a><br>";

    // Display the image below the link, wrapped in an anchor tag
    if ($image) {
        echo "<a href='$url' target='_blank'><img src='$image' alt='$title Image' width=75%></a><br>";
    } else {
        echo "No image available.<br>";
    }
}

// Close the cURL session
curl_close($ch);
?>
