<?php
// modules/stream_worker.php
// Youtube Multi-Stream Tracker
// Run via Cron: */5 * * * * php /path/to/stream_worker.php

error_reporting(E_ALL);
ini_set('display_errors', 1);
chdir(__DIR__);
require_once '../config/database.php';

try {
    echo "[" . date('Y-m-d H:i:s') . "] Checking streams...\n";

    // 1. Get Settings
    $settings = $pdo->query("SELECT setting_key, setting_value FROM settings")->fetchAll(PDO::FETCH_KEY_PAIR);
    $api_key = $settings['youtube_api_key'] ?? '';
    
    if (empty($api_key)) die("Error: usage - Missing API Key.\n");

    // 2. Get Active Streams
    $streams = $pdo->query("SELECT id, video_id, name FROM youtube_streams WHERE is_active = 1")->fetchAll();
    
    if (empty($streams)) die("No active streams to check.\n");

    // 3. Prepare Batch Request
    $video_map = []; // video_id => stream_id
    $ids = [];
    foreach ($streams as $s) {
        $ids[] = $s['video_id'];
        $video_map[$s['video_id']] = $s['id'];
    }
    
    $id_string = implode(',', array_slice($ids, 0, 50)); // Max 50 per call
    $url = "https://www.googleapis.com/youtube/v3/videos?part=liveStreamingDetails&id=" . urlencode($id_string) . "&key=" . urlencode($api_key);

    // 4. Call API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http !== 200) {
        // Log error status for all streams? Or just die
        // Better update them to 'error' status so dashboard sees it
        $pdo->query("UPDATE youtube_streams SET last_status = 'error' WHERE is_active = 1");
        die("API Error $http: $response\n");
    }

    $data = json_decode($response, true);
    $items = $data['items'] ?? [];
    
    // Convert API items to map for easy lookup
    $api_results = [];
    foreach ($items as $item) {
        $api_results[$item['id']] = $item;
    }

    // 5. Process Each Stream
    $log_stmt = $pdo->prepare("INSERT INTO youtube_auto_logs (stream_id, viewers) VALUES (?, ?)");
    $update_stmt = $pdo->prepare("UPDATE youtube_streams SET last_status = ? WHERE id = ?");

    foreach ($video_map as $vid => $sid) {
        $status = 'offline'; // Default
        $viewers = 0;

        if (isset($api_results[$vid])) {
            $details = $api_results[$vid]['liveStreamingDetails'] ?? null;
            if ($details && isset($details['concurrentViewers'])) {
                $status = 'live';
                $viewers = (int)$details['concurrentViewers'];
            } else {
                // Video exists but no concurrentViewers -> likely offline or simple video
                $status = 'offline';
            }
        } else {
            // Video ID not returned by API -> Deleted or invalid?
            $status = 'error';
        }

        // Log Data
        // Optimization: Only log if live? Or always?
        // Plan implies continuous logging for reports. Logging 0 is fine for "offline" gaps.
        // But maybe sparse logging is better.
        // Let's log if Live OR if it was previously Live (to mark end).
        // For simplicity, we log 0 if offline, so charts drop to 0.
        $log_stmt->execute([$sid, $viewers]);

        // Update Status Cache
        $update_stmt->execute([$status, $sid]);
        
        echo "Stream $sid ($vid): $status ($viewers viewers)\n";
    }

    echo "Done.\n";

} catch (Exception $e) {
    echo "Fatal Error: " . $e->getMessage() . "\n";
}
