<?php
// api/public/live-streams.php - No authentication required
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../cloudflare.php';

// Allow public access - NO requireAuth() here!

try {
    // Get all streams with thumbnail and additional data
    $stmt = $pdo->prepare("
        SELECT 
            ls.id, 
            ls.title, 
            ls.description, 
            ls.status, 
            ls.cf_video_uid,
            ls.chat_enabled,
            ls.scheduled_start,
            ls.thumbnail,
            ls.created_at,
            li.name as input_name,
            li.cloudflare_input_id
        FROM live_streams ls
        LEFT JOIN live_inputs li ON li.id = ls.live_input_id
        ORDER BY 
            CASE ls.status 
                WHEN 'live' THEN 1 
                WHEN 'scheduled' THEN 2 
                ELSE 3 
            END,
            ls.scheduled_start ASC
    ");
    $stmt->execute();
    $streams = $stmt->fetchAll();
    
    // Add thumbnail URL and check live status from Cloudflare
    define('R2_PUBLIC_URL', 'https://pub-4a26074f63ae4203a6de95f3b950b21c.r2.dev');
    
    foreach ($streams as &$stream) {
        // Add thumbnail URL
        if ($stream['thumbnail']) {
            $stream['thumbnail_url'] = R2_PUBLIC_URL . '/' . $stream['thumbnail'];
        } else {
            $stream['thumbnail_url'] = null;
        }
        
        // Check if actually live from Cloudflare (for live streams)
        $stream['is_live'] = ($stream['status'] === 'live');
        if ($stream['status'] === 'live' && $stream['cloudflare_input_id']) {
            $status = cf_get_live_status($stream['cloudflare_input_id']);
            $stream['is_live'] = $status['success'] && isset($status['result']['live']) && $status['result']['live'];
            
            // Auto-update Video UID if missing
            if ($stream['is_live'] && !$stream['cf_video_uid']) {
                $uid = cf_get_current_video_uid($stream['cloudflare_input_id']);
                if ($uid) {
                    $stream['cf_video_uid'] = $uid;
                    // Update database
                    $update = $pdo->prepare("UPDATE live_streams SET cf_video_uid = ? WHERE id = ?");
                    $update->execute([$uid, $stream['id']]);
                }
            }
        }
        
        // Format for frontend
        $stream['viewer_count'] = rand(100, 500); // Mock viewer count
    }
    
    sendSuccess($streams);
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>