<?php
/*******************************************************************************************************************
| EasyStream API Endpoint
| RESTful API for EasyStream application
|*******************************************************************************************************************/

define('_ISVALID', true);

// Load core system
$main_dir = realpath(dirname(__FILE__) . '/../../');
set_include_path($main_dir);

if (!file_exists('f_core/config.core.php')) {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Core system not found']);
    exit;
}

include_once 'f_core/config.core.php';

// Set JSON response headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Get endpoint from query string
$endpoint = isset($_GET['endpoint']) ? $_GET['endpoint'] : '';
$method = $_SERVER['REQUEST_METHOD'];

// Basic API routing
switch ($endpoint) {
    case 'status':
        echo json_encode([
            'status' => 'online',
            'version' => '1.0.0',
            'timestamp' => date('c'),
            'container' => gethostname()
        ]);
        break;
        
    case 'health':
        // Redirect to health check
        include_once '../../health_check.php';
        break;
        
    case 'videos':
    case 'users':
    case 'live':
    case 'search':
    case 'analytics':
        // Redirect to v1 API
        $api = new VAPI();
        $data = [];
        
        if ($method === 'GET') {
            $data = $_GET;
        } else {
            $input = file_get_contents('php://input');
            if ($input) {
                $data = json_decode($input, true) ?: [];
            }
            $data = array_merge($data, $_POST);
        }
        
        $headers = getallheaders() ?: [];
        $response = $api->handleRequest($method, $endpoint, $data, $headers);
        
        http_response_code($response['status']);
        echo json_encode($response);
        break;
        
    default:
        http_response_code(404);
        echo json_encode([
            'error' => 'API endpoint not found',
            'endpoint' => $endpoint,
            'available_endpoints' => [
                'status',
                'health', 
                'videos',
                'users'
            ]
        ]);
        break;
}
?>