<?php
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../helpers/response.php';
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/cloudflare.php';

$admin = requireAdmin();
$method = $_SERVER['REQUEST_METHOD'];

// GET - List all live inputs
if ($method === 'GET') {
    try {
        $stmt = $pdo->query("SELECT id, name, rtmps_url, stream_key, created_at FROM live_inputs ORDER BY name ASC");
        $inputs = $stmt->fetchAll();
        sendSuccess($inputs);
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
}
// POST - Create a new live input
elseif ($method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $name = $data['name'] ?? '';
    
    if (!$name) {
        sendError('Name is required', 400);
    }
    
    // Create live input in Cloudflare
    $result = cf_create_live_input($name, 'automatic');
    
    if (!$result['success']) {
        sendError('Cloudflare error: ' . json_encode($result['errors']), 500);
    }
    
    $cf_input = $result['result'];
    
    // Save to database
    $stmt = $pdo->prepare("
        INSERT INTO live_inputs (name, rtmps_url, stream_key, cloudflare_input_id)
        VALUES (?, ?, ?, ?)
    ");
    $stmt->execute([
        $name,
        $cf_input['rtmps']['url'],
        $cf_input['rtmps']['streamKey'],
        $cf_input['uid']
    ]);
    
    sendSuccess(['id' => $pdo->lastInsertId()], 'Live input created');
}
// DELETE - Delete a live input
elseif ($method === 'DELETE') {
    $id = $_GET['id'] ?? null;
    
    if (!$id) {
        sendError('ID required', 400);
    }
    
    // Get cloudflare_input_id
    $stmt = $pdo->prepare("SELECT cloudflare_input_id FROM live_inputs WHERE id = ?");
    $stmt->execute([$id]);
    $input = $stmt->fetch();
    
    if (!$input) {
        sendError('Live input not found', 404);
    }
    
    // Delete from Cloudflare
    cf_delete_live_input($input['cloudflare_input_id']);
    
    // Delete from database
    $stmt = $pdo->prepare("DELETE FROM live_inputs WHERE id = ?");
    $stmt->execute([$id]);
    
    sendSuccess(null, 'Live input deleted');
}
else {
    sendError('Method not allowed', 405);
}
?>