<?php
require_once __DIR__ . '/../config/cloudflare.php';

function cf_request($endpoint, $method = 'GET', $data = null) {
    $url = "https://api.cloudflare.com/client/v4/accounts/" . CLOUDFLARE_ACCOUNT_ID . "/stream" . $endpoint;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . CLOUDFLARE_API_TOKEN,
        'Content-Type: application/json'
    ]);
    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }
    $response = curl_exec($ch);
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        error_log('cf_request: curl error for ' . $url . ' - ' . $error);
        return ['success' => false, 'errors' => [['message' => $error]], 'result' => null];
    }
    curl_close($ch);

    $decoded = json_decode($response, true);
    if (!is_array($decoded)) {
        error_log('cf_request: invalid JSON response for ' . $url . ' - ' . $response);
        return ['success' => false, 'errors' => [['message' => 'Invalid JSON response from Cloudflare']], 'result' => null];
    }
    return $decoded;
}

function cf_create_live_input($name, $recording_mode = 'automatic') {
    return cf_request('/live_inputs', 'POST', [
        'recording' => ['mode' => $recording_mode],
        'meta' => ['name' => $name]
    ]);
}

function cf_get_live_inputs() {
    return cf_request('/live_inputs');
}

function cf_update_live_input($input_id, $enabled) {
    return cf_request("/live_inputs/{$input_id}", 'PUT', ['enabled' => $enabled]);
}

function cf_delete_live_input($input_id) {
    return cf_request("/live_inputs/{$input_id}", 'DELETE');
}

function cf_get_live_status($input_id) {
    return cf_request("/live_inputs/{$input_id}/lifecycle");
}

function cf_get_recordings($input_id) {
    return cf_request("/live_inputs/{$input_id}/videos");
}

function cf_get_current_video_uid($input_id) {
    $response = cf_get_recordings($input_id);
    if ($response['success'] && isset($response['result'])) {
        foreach ($response['result'] as $video) {
            if ($video['status']['state'] === 'live-inprogress') {
                return $video['uid'];
            }
        }
    }
    return null;
}
?>