<?php
// components/functions.php
function getYouTubeThumbnail($playlist_id, $api_key, $conn, $id, $table = 'programmes') {
    $thumbnail = 'default.jpg';

    // Always fetch the latest video from the playlist
    $url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=1&playlistId=$playlist_id&key=$api_key";
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code === 200 && $response) {
        $data = json_decode($response, true);
        if (!empty($data['items'][0]['snippet']['thumbnails']['medium']['url'])) {
            $thumbnail = $data['items'][0]['snippet']['thumbnails']['medium']['url'];
        }
    }

    // Update database with the latest thumbnail
    try {
        $update_stmt = $conn->prepare("UPDATE $table SET thumbnail = :thumbnail WHERE id = :id");
        $update_stmt->bindValue(':thumbnail', $thumbnail, PDO::PARAM_STR);
        $update_stmt->bindValue(':id', $id, PDO::PARAM_INT);
        $update_stmt->execute();
    } catch (PDOException $e) {
        error_log("Thumbnail update error: " . $e->getMessage());
    }

    return $thumbnail;
}
?>
