<?php
/**
 * LEAD Marketing Conference - YouTube Video Fetcher
 * Pulls all videos from the channel and outputs a CSV
 * with title, URL, date, and YouTube description.
 *
 * Usage: php fetch_lead_videos.php
 * Output: lead_videos.csv
 */

// ─── CONFIG ──────────────────────────────────────────────────────────────────

$YOUTUBE_API_KEY = 'AIzaSyAbnVbipcyBPiDzpCQTcYYMfai3Ho8t8Hc';       // Replace with your key
$CHANNEL_ID      = 'UCh1a-GcToUxQNhG0xCwW63Q';
$OUTPUT_FILE     = 'lead_videos.csv';

// ─── STEP 1: GET UPLOADS PLAYLIST ID ─────────────────────────────────────────

function get_uploads_playlist_id($channel_id, $api_key) {
    $url = "https://www.googleapis.com/youtube/v3/channels?"
         . http_build_query([
               'part' => 'contentDetails',
               'id'   => $channel_id,
               'key'  => $api_key,
           ]);

    $response = json_decode(file_get_contents($url), true);

    if (empty($response['items'])) {
        die("ERROR: Could not find channel. Check CHANNEL_ID and API key.\n");
    }

    return $response['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
}

// ─── STEP 2: FETCH ALL VIDEOS ─────────────────────────────────────────────────

function get_all_videos($playlist_id, $api_key) {
    $videos     = [];
    $page_token = null;

    do {
        $params = [
            'part'       => 'snippet',
            'playlistId' => $playlist_id,
            'maxResults' => 50,
            'key'        => $api_key,
        ];
        if ($page_token) {
            $params['pageToken'] = $page_token;
        }

        $url      = "https://www.googleapis.com/youtube/v3/playlistItems?" . http_build_query($params);
        $response = json_decode(file_get_contents($url), true);

        if (isset($response['error'])) {
            die("YouTube API error: " . $response['error']['message'] . "\n");
        }

        foreach ($response['items'] as $item) {
            $snippet  = $item['snippet'];
            $video_id = $snippet['resourceId']['videoId'];

            $videos[] = [
                'title'       => $snippet['title'],
                'url'         => "https://www.youtube.com/watch?v={$video_id}",
                'date'        => substr($snippet['publishedAt'], 0, 10),
                'description' => trim($snippet['description']),
            ];
        }

        $page_token = $response['nextPageToken'] ?? null;

    } while ($page_token);

    return $videos;
}

// ─── MAIN ─────────────────────────────────────────────────────────────────────

echo "Fetching uploads playlist ID...\n";
$playlist_id = get_uploads_playlist_id($CHANNEL_ID, $YOUTUBE_API_KEY);
echo "Playlist ID: {$playlist_id}\n";

echo "Fetching videos...\n";
$videos = get_all_videos($playlist_id, $YOUTUBE_API_KEY);
echo "Found " . count($videos) . " videos.\n";

$fh = fopen($OUTPUT_FILE, 'w');
fputcsv($fh, ['Title', 'URL', 'Date Published', 'Description']);

foreach ($videos as $video) {
    fputcsv($fh, [
        $video['title'],
        $video['url'],
        $video['date'],
        $video['description'],
    ]);
}

fclose($fh);
echo "Done. Output written to: {$OUTPUT_FILE}\n";
