<?php
    require('config.php');
    date_default_timezone_set('Europe/Paris');
    $date = new DateTime('now');
    
    function elapsed_days() {
	// Count the number of full days between now and a reference time
	$now = new DateTime();
	$diff = $now->diff(TIME_ZERO);
	return $diff->days;
    }
    
    function video_of_the_day($folder) {
        // Authorized video extensions
        $file_pattern = "*.{mp4,webm,mkv}";
        // List all media files in folder
        $media_files = glob($folder . $file_pattern, GLOB_BRACE);
        // Get path to random media file
	$n_files = count($media_files);
	// Get "random" video based on the elapsed days since a reference time
	// This allows us to get a nicely increasing rotation of videos
	$today_video = $media_files[elapsed_days() % $n_files];
	
	$video_filename = basename($today_video);
	$json_file = $folder . pathinfo($video_filename, PATHINFO_FILENAME) . ".info.json";

	// Extract metadata from JSON sidecar file
	$json = file_get_contents($json_file);
	$metadata = json_decode($json, true);

	$title = $metadata["title"];
	$author = $metadata["channel"];
	$url = $metadata["webpage_url"];

	return [
		"title" => $title,
		"author" => $author,
		"url" => $url,
		"path" => $today_video,
	];
    }

    $video = video_of_the_day(MEDIA_FOLDER);
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Duck Clip of the Day</title>
        <link rel="stylesheet" type="text/css" href="ducks.css">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
	<main>
        <header>
            <h1>&lt;&nbsp;Duck Clip of the Day&nbsp;&gt;</h1>
            <?php if (CONFIG_CLOCK) { ?>
            <div id="clock">Today is <?php echo $date->format('l j F Y'); ?> and the video is</div>
            <?php } ?>
        </header>
        <section>
		<h2><?php echo $video["title"] ?></h2>
		<h3>by <a href="<?php echo $video["url"] ?>"><?php echo $video["author"] ?></a></h3>
		<div class="video-wrapper">
		<video controls width="auto">
			<source src="<?php echo $video["path"] ?>" />
		</video>
		</div>
        </section>
        <footer>
		<a href="https://altay.fr">Altay</a> - 2025
        </footer>
	</main>
    </body>
</html>
