<a target="_blank" href="confirmnewvid.html" style="color:blue" 
   onclick="this.href=this.href+(this.href.includes('?') ? '&' : '?')+'apikey='+new URLSearchParams(window.location.search).get('apikey');">
   NewVideo?
</a><hr>




<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // This part executes when the button is clicked

    // Extract API key from the URL if available
    $apiKey = isset($_GET['apikey']) ? $_GET['apikey'] : '';

    if (empty($apiKey)) {
        die('API key is missing. Please provide it as a URL parameter (?apikey=YOUR_API_KEY).');
    }

    // Get channel URLs from the hidden input
    $channelUrls = explode(',', $_POST['channelUrls']);

    // File to store results
    $outputFile = 'ytlist.txt';

    // Clear existing content in the file
    file_put_contents($outputFile, '');

    // Function to get the newest video for a given channel URL
    function fetchNewestVideo($channelUrl, $apiKey)
    {
        $channelId = null;
        if (preg_match('/channel\/([\w\-]+)/i', $channelUrl, $match)) {
            $channelId = $match[1];
        } elseif (preg_match('/@([\w\-]+)/i', $channelUrl, $match)) {
            // For handles, get the channelId using the YouTube API
            $apiUrl = "https://www.googleapis.com/youtube/v3/channels?part=id&forUsername={$match[1]}&key={$apiKey}";
            $response = json_decode(file_get_contents($apiUrl), true);
            if (!empty($response['items'][0]['id'])) {
                $channelId = $response['items'][0]['id'];
            }
        }

        if ($channelId) {
            $apiUrl = "https://www.googleapis.com/youtube/v3/search?key={$apiKey}&channelId={$channelId}&part=snippet&order=date&maxResults=1";
            $response = json_decode(file_get_contents($apiUrl), true);
            if (!empty($response['items'][0])) {
                $videoId = $response['items'][0]['id']['videoId'];
                $uploadDate = $response['items'][0]['snippet']['publishedAt'];
                return "{$channelUrl} - {$videoId} {$uploadDate}";
            }
        }
        return "{$channelUrl} - No videos found";
    }

    // Fetch newest video for each channel URL
    foreach ($channelUrls as $channelUrl) {
        $result = fetchNewestVideo(trim($channelUrl), $apiKey);
        file_put_contents($outputFile, $result . PHP_EOL, FILE_APPEND);
    }

    echo "Newest video data saved to ytlist.txt.";
    exit;
}

// Function to get full channel URL for a given YouTube link
function getFullChannelUrl($url) {
    // If the URL is a direct /channel link, return it as-is
    if (preg_match('/\/channel\/(UC[a-zA-Z0-9_-]{22})/', $url, $match)) {
        return "https://www.youtube.com/channel/" . $match[1];
    }

    // For handles like /@username, we need to use cURL to fetch the channel ID
    if (preg_match('/@([\w\-]+)/i', $url, $match)) {
        $username = $match[1];
        
        // Use cURL to fetch the HTML content of the page
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://m.youtube.com/@{$username}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $html = curl_exec($ch);
        curl_close($ch);
        
        // Regex pattern to find the channelID (starts with 'UC')
        $pattern = '/"externalId":"(UC[a-zA-Z0-9_-]{22})"/';
        
        // Check if the regex pattern matches and extract the channelID
        if (preg_match($pattern, $html, $matches)) {
            // Extracted channelID
            $channelID = $matches[1];
            
            // Construct the full channel URL
            return "https://www.youtube.com/channel/" . $channelID;
        } else {
            return "Channel ID not found for handle: @{$username}";
        }
    }

    // For short URL format like https://m.youtube.com/c/username, we need to use cURL to fetch the channel ID
    if (preg_match('/\/c\/([\w\-]+)/i', $url, $match)) {
        $username = $match[1];
        
        // Use cURL to fetch the HTML content of the page
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://m.youtube.com/c/{$username}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $html = curl_exec($ch);
        curl_close($ch);
        
        // Regex pattern to find the channelID (starts with 'UC')
        $pattern = '/"externalId":"(UC[a-zA-Z0-9_-]{22})"/';
        
        // Check if the regex pattern matches and extract the channelID
        if (preg_match($pattern, $html, $matches)) {
            // Extracted channelID
            $channelID = $matches[1];
            
            // Construct the full channel URL
            return "https://www.youtube.com/channel/" . $channelID;
        } else {
            return "Channel ID not found for handle: c/{$username}";
        }
    }
    
    // If URL doesn't match known patterns, return the original URL
    return "Invalid YouTube URL";
}

// Step 1: Fetch the webpage content
$url = 'https://alceawis.de/UnderratedContent.html';
$html = file_get_contents($url);

if ($html === FALSE) {
    die('Error fetching the webpage content.');
}

// Step 2: Define the URL pattern (combined for all types)
$pattern = '/https:\/\/m\.youtube\.com\/(@[\w\-]+|channel\/[\w\-]+|c\/[\w\-]+)/i';

// Step 3: Extract URLs in order of appearance
preg_match_all($pattern, $html, $matches);

// Step 4: Display the results with <br> tags
if (!empty($matches[0])) {
    echo "<form method='POST'>";
    echo "Found YouTube links in order of appearance:<br>";
    $fullLinks = [];
    foreach ($matches[0] as $link) {
        $fullLink = getFullChannelUrl(trim($link));
        //echo "Original URL: {$link}<br>";
        echo "{$fullLink}<br>";
        $fullLinks[] = $fullLink;
    }
    // Add a hidden input to store the full channel URLs
    echo "<input type='hidden' name='channelUrls' value='" . implode(',', $fullLinks) . "'>";
    // Add a button to fetch newest video details
    echo "<button type='submit'>Check for Newest Videos</button>";
    echo "</form>";
} else {
    echo "No matching YouTube links found.<br>";
}
?>
