<?php
header('Content-Type: application/json');

$year = $_GET['year'] ?? date('Y');

// Search query
$query = "youtube commercials " . $year;
$searchUrl = "https://duckduckgo.com/lite/?q=" . urlencode($query);

// Use curl to get the search results
$html = shell_exec('curl -L --silent "' . $searchUrl . '"');

// Find all YouTube links in the HTML
preg_match_all('/(https?:\/\/www\.youtube\.com\/watch\?v=[a-zA-Z0-9_-]+)/', $html, $matches);

if (!empty($matches[0])) {
    // Pick a random video
    $videoUrl = $matches[0][array_rand($matches[0])];
    // Convert to embeddable URL
    $embedUrl = str_replace("watch?v=", "embed/", $videoUrl);
    echo json_encode(['videoUrl' => $embedUrl, 'source' => 'youtube-search']);
} else {
    // Fallback if no video is found
    echo json_encode(['videoUrl' => 'https://www.youtube.com/embed/dQw4w9WgXcQ', 'source' => 'fallback']);
}