<!--https://alcea-wisteria.de/PHP//0demo/2023-06-17-YT-Tools/API-RSS-Save/save-feed.php?channelid=UCrltGih11A_Nayz6hG5XtIw&apikey=insertapikey&save-->
<?php
error_reporting(0);
?>

<?php ini_set('display_errors', 0); ?>

<?php
$API_KEY = $_GET['apikey'] ?? ''; // Extract the apiKey from the query string
if (empty($API_KEY)) {
  echo 'No apiKey provided';
  exit;
}
$channelId = $_GET['channelid'] ?? ''; // Extract the channelId from the query string
if (empty($channelId)) {
  echo 'No channelId provided';
  exit;
}
$MAX_RESULTS = 15;
$url = "https://www.googleapis.com/youtube/v3/search?key={$API_KEY}&channelId={$channelId}&part=snippet,id&order=date&maxResults={$MAX_RESULTS}";
$response = file_get_contents($url);
if ($response === false) {
  echo 'Error fetching videos';
  exit;
}
$data = json_decode($response, true);
if (!isset($data['items'])) {
  echo 'No videos found';
  exit;
}
$pageOutput = '';
foreach ($data['items'] as $item) {
  $videoId = $item['id']['videoId'];
  $title = $item['snippet']['title'];
  $link = "https://www.youtube.com/watch?v={$videoId}";
  $pageOutput .= "<a href='{$link}' target='_blank'>{$title}</a><br><br>";
}
// Check if "save" query string exists
if (isset($_GET['save'])) {
  // Read the contents of autoscroll.html
  $autoscrollContent = file_get_contents('autoscroll.html');
  // Replace "INJECT" with the current page output
  $modifiedContent = str_replace('INJECT', $pageOutput, $autoscrollContent);
  // Save the modified content to a new file
  $filename = "rss-scrolling-source-{$channelId}.html";
  file_put_contents($filename, $modifiedContent);
  echo "Modified content saved to {$filename}";
} else {
  // Output the page content
  echo $pageOutput;
}
?>
