<?php
$base_url = 'https://hub.vroid.com';
$user_url = $base_url . '/en/users/75406576';

$options = array(
    'http' => array(
        'method' => 'GET',
        'header' => 'Referer: ' . $base_url . "\r\n"
    ),
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false
    )
);
$context = stream_context_create($options);
$html = file_get_contents($user_url, false, $context);

if ($html === false) {
    die('Failed to retrieve user profile.');
}

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//a[starts-with(@href, "/characters/")]');

$unique_urls = array();
foreach ($nodes as $node) {
    $full_url = $base_url . $node->getAttribute('href');
    if (!in_array($full_url, $unique_urls)) {
        $unique_urls[] = $full_url;
    }
}

// Limit to 7 characters
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 3;
$limit = max(1, min($limit, count($unique_urls)));
$unique_urls = array_slice($unique_urls, 0, $limit);

// Fetch details for each character
foreach ($unique_urls as $character_url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $character_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $character_html = curl_exec($ch);
    curl_close($ch);

    $character_doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $character_doc->loadHTML($character_html);
    libxml_clear_errors();
    $character_xpath = new DOMXPath($character_doc);

    // Extract character name
    $linkNode = $character_xpath->query('//a[contains(@class, "sc-d72b35f1-3 hdzTgz")]');
    if ($linkNode->length > 0) {
        $characterName = trim($linkNode->item(0)->nodeValue);
    } else {
        $characterName = "Unknown Character";
    }

    // Extract heart count
    $elements = $character_xpath->query('//span[contains(@class, "gmUKUe")]');
    $heartCount = ($elements->length > 0) ? trim($elements[0]->nodeValue) : 'Not Found';

    // Display results
    echo "<a href=\"$character_url\" target=\"_blank\">$characterName</a>";
    echo " - Hearts: $heartCount<br>";
}
?>
