<a target="_blank" href="checkchannels.php" style=color:blue>ReFetch</a><hr>
<?php

// Function to get the latest video URL and title from the YouTube RSS feed
function getLatestVideoFromRSS($channelId) {
    // YouTube RSS feed URL for a channel
    $rssUrl = "https://www.youtube.com/feeds/videos.xml?channel_id=$channelId";

    // Load the RSS feed data
    $rssData = simplexml_load_file($rssUrl);

    if ($rssData) {
        // Get the URL of the latest video (first entry) and the video title
        $latestVideoUrl = (string)$rssData->entry[0]->link['href'];
        $videoTitle = (string)$rssData->entry[0]->title;
        return ['url' => $latestVideoUrl, 'title' => $videoTitle];
    }
    return null;
}

// Read the ytlistt.txt file
$ytListFile = 'ytlist.txt';
$lines = file($ytListFile, FILE_IGNORE_NEW_LINES);

// Loop through each line in the file and compare with the latest video
foreach ($lines as $line) {
    // Split the line into channel URL, video URL, and timestamp
    preg_match('/(https:\/\/www\.youtube\.com\/channel\/[a-zA-Z0-9_-]+)\s-\s(https:\/\/www\.youtube\.com\/watch\?v=[a-zA-Z0-9_-]+)\s(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00)/', $line, $matches);
    
    if (count($matches) == 4) {
        $channelUrl = $matches[1];
        $videoUrl = $matches[2];
        $timestamp = $matches[3];
        
        // Extract the channel ID from the URL
        preg_match('/channel\/([a-zA-Z0-9_-]+)/', $channelUrl, $channelMatches);
        $channelId = $channelMatches[1];

        // Get the latest video URL and title from the RSS feed
        $latestVideo = getLatestVideoFromRSS($channelId);

        if ($latestVideo) {
            // Check if the latest video matches the video URL in the file
            $linkText = htmlspecialchars($latestVideo['title']); // Escape special HTML characters for the title
            $linkUrl = $latestVideo['url'];
            
            // Output the line with clickable video links and color formatting
            if ($linkUrl === $videoUrl) {
                // Gray and bold for "same"
                echo $line . " <span style='color: gray; font-weight: bold;'>same</span> <a href='$linkUrl' target='_blank'>$linkText</a><br>\n";
            } else {
                // Green and bold for "new"
                echo $line . " <span style='color: green; font-weight: bold;'>new</span> <a href='$linkUrl' target='_blank'>$linkText</a><br>\n";
            }
        } else {
            echo "Error retrieving RSS for channel: $channelUrl\n";
        }
    } else {
        echo "Invalid format in line: $line\n";
    }
}
?>
