<?php
// Function to fetch the list of channels and their old video IDs from a file
function fetchYTList($ytListUrl) {
    $ytList = [];
    
    // Read the ytlist.txt file
    $lines = file($ytListUrl, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    foreach ($lines as $line) {
        // Split each line by ' - ' to get the URL and old video ID
        $parts = explode(' - ', trim($line));
        
        if (count($parts) == 2) {
            $url = trim($parts[0]);
            $oldVideoId = trim($parts[1]);
            $channelId = basename($url);  // Extract channel ID from the URL
            
            $ytList[] = ['channelUrl' => $url, 'oldVideoId' => $oldVideoId, 'channelId' => $channelId];
        }
    }
    
    return $ytList;
}

// Function to check for new videos using YouTube RSS feed
function checkForNewVideos($ytList) {
    $videoStatus = '';
    
    foreach ($ytList as $channel) {
        $rssUrl = 'https://www.youtube.com/feeds/videos.xml?channel_id=' . $channel['channelId'];
        
        // Fetch the RSS feed
        $rssContent = file_get_contents($rssUrl);
        
        if ($rssContent !== false) {
            // Parse the RSS feed (XML)
            $xml = simplexml_load_string($rssContent);
            $latestVideoEntry = $xml->entry;
            
            if ($latestVideoEntry) {
                // Correct extraction of video ID without 'yt%3A' and decoding it properly
                $latestVideoId = (string)$latestVideoEntry->id;
                $latestVideoId = urldecode(substr($latestVideoId, strpos($latestVideoId, ':') + 1)); // Decode and remove 'yt:'

                if ($latestVideoId !== $channel['oldVideoId']) {
                    // If the latest video ID is different from the old one, show a clickable link
                    $videoLink = 'https://www.youtube.com/watch?v=' . $latestVideoId;
                    $videoStatus .= "<p>New video found for <a href=\"$videoLink\" target=\"_blank\">{$channel['channelUrl']}</a></p>";
                } else {
                    // Otherwise, display '[OK@]'
                    $videoStatus .= "<p>OK@ for <strong>{$channel['channelUrl']}</strong></p>";
                }
            }
        } else {
            $videoStatus .= "<p>Error fetching data from YouTube RSS feed for {$channel['channelUrl']}</p>";
        }
    }
    
    return $videoStatus;
}

// Define the path to the ytlist.txt file
$ytListUrl = 'ytlist.txt';

// Fetch the list of channels and old video IDs
$ytList = fetchYTList($ytListUrl);

// Check for new videos and get the HTML output
$videoStatus = checkForNewVideos($ytList);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Channel Video Check</title>
</head>
<body>
    <h1>Check for New YouTube Videos</h1>

    <div id="videoStatus">
        <?php echo $videoStatus; ?>
    </div>
</body>
</html>
