<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../../helpers/auth.php';
require_once '../cloudflare.php';
require_once '../../vendor/autoload.php';
require_once '../../config/pusher.php';

use Pusher\Pusher;

$admin = requireAdmin();
$data = json_decode(file_get_contents('php://input'), true);

$id = $data['id'] ?? null;
$action = $data['action'] ?? null;

if (!$id || !$action) {
    sendError('Broadcast ID and action required', 400);
}

// Initialize Pusher
$pusher = new Pusher(PUSHER_KEY, PUSHER_SECRET, PUSHER_APP_ID, ['cluster' => PUSHER_CLUSTER]);

// Get the Cloudflare input ID for this broadcast
$stmt = $pdo->prepare("
    SELECT ls.*, li.cloudflare_input_id 
    FROM live_streams ls
    JOIN live_inputs li ON li.id = ls.live_input_id
    WHERE ls.id = ?
");
$stmt->execute([$id]);
$broadcast = $stmt->fetch();

if (!$broadcast) {
    sendError('Broadcast not found', 404);
}

if ($action === 'start') {
    // 1. Enable Cloudflare input
    if ($broadcast['cloudflare_input_id']) {
        $result = cf_update_live_input($broadcast['cloudflare_input_id'], true);
        if (!$result['success']) {
            sendError('Cloudflare error: ' . json_encode($result['errors']), 500);
        }
    }
    
    // 2. Get current Video UID if available
    $uid = null;
    if ($broadcast['cloudflare_input_id']) {
        $uid = cf_get_current_video_uid($broadcast['cloudflare_input_id']);
    }
    
    // 3. Update database
    $update = $pdo->prepare("UPDATE live_streams SET status = 'live', cf_video_uid = ? WHERE id = ?");
    $update->execute([$uid, $id]);
    
    // 4. Trigger Pusher event
    $pusher->trigger('live-status', 'stream-started', ['stream_id' => $id]);
    
    sendSuccess(['is_live' => true, 'cf_video_uid' => $uid], 'Stream started');
    
} elseif ($action === 'stop') {
    // 1. Disable Cloudflare input
    if ($broadcast['cloudflare_input_id']) {
        $result = cf_update_live_input($broadcast['cloudflare_input_id'], false);
        if (!$result['success']) {
            error_log("Cloudflare disable error: " . json_encode($result['errors']));
        }
    }
    
    // 2. Update database
    $update = $pdo->prepare("UPDATE live_streams SET status = 'ended' WHERE id = ?");
    $update->execute([$id]);
    
    // 3. Trigger Pusher event
    $pusher->trigger('live-status', 'stream-ended', ['stream_id' => $id]);
    
    sendSuccess(['is_live' => false], 'Stream stopped');
    
} else {
    sendError('Invalid action', 400);
}
?>