<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require 'functions.php';
require 'db_connect.php'; // This already sets $conn

$api_key = 'AIzaSyBAON_ChCgF5BEXX7ijp--GImeRmAHdUBY';
// Specific details for the Events/Shorts sync
$shorts_api_key = 'AIzaSyBtWZ66L-tJPYfTk1gHpHYpHNr5gn0KlLY';
$shorts_playlist_id = 'PLxlWBAWnGBcf63dIRA1zgl48q601n2sWm';

// Get current date and time in readable format
$currentTime = date('Y-m-d H:i:s');

echo "<h1>Global Sync started at: $currentTime</h1>";

// -----------------------------
// 1. Teledramas Sync
// -----------------------------
$startTeledrama = date('Y-m-d H:i:s');
echo "<p><b>Teledrama sync started at:</b> $startTeledrama</p>";

$totalTeledramas = updateTeledramasAndEpisodes($conn, $api_key, 0);

echo "<p>Teledrama sync completed. Total updated: $totalTeledramas</p><hr>";

// -----------------------------
// 2. Programmes Sync
// -----------------------------
$startProgramme = date('Y-m-d H:i:s');
echo "<p><b>Programme sync started at:</b> $startProgramme</p>";

$totalProgrammes = updateProgrammesAndEpisodes($conn, $api_key, 0);

echo "<p>Programme sync completed. Total updated: $totalProgrammes</p><hr>";

// -----------------------------
// 3. Events (YouTube Shorts) Sync - NEW
// -----------------------------
$startEvents = date('Y-m-d H:i:s');
echo "<p><b>Events (Shorts) sync started at:</b> $startEvents</p>";

$eventCount = 0;
$url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=$shorts_playlist_id&key=$shorts_api_key";
$response = @file_get_contents($url);

if ($response) {
    $data = json_decode($response, true);
    if (isset($data['items'])) {
        $stmt = $conn->prepare("INSERT IGNORE INTO youtube_shorts_events (video_id, title, thumbnail_url, published_at) VALUES (?, ?, ?, ?)");
        
        foreach ($data['items'] as $item) {
            $v_id   = $item['snippet']['resourceId']['videoId'];
            $title  = $item['snippet']['title'];
            $thumb  = $item['snippet']['thumbnails']['high']['url'] ?? '';
            $pub_at = date('Y-m-d H:i:s', strtotime($item['snippet']['publishedAt']));

            if (!in_array($title, ["Private video", "Deleted video"])) {
                if($stmt->execute([$v_id, $title, $thumb, $pub_at])) {
                    $eventCount++;
                }
            }
        }
        echo "<p>Events sync completed. New shorts processed: $eventCount</p>";
    }
} else {
    echo "<p style='color:red;'>Events sync failed: Could not connect to YouTube API.</p>";
}

$finished = date('Y-m-d H:i:s');
echo "<hr><h3>All syncs finished at: $finished</h3>";
?>