<?php
/*******************************************************************************************************************
| EasyStream REST API v1
| Main API endpoint handler for mobile apps and third-party integration
|*******************************************************************************************************************/

define('_ISVALID', true);
require_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, X-Requested-With');

try {
    $api = new VAPI();
    
    // Get request method and endpoint
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    $requestUri = $_SERVER['REQUEST_URI'] ?? '';
    
    // Parse endpoint from URI
    $basePath = '/api/v1/';
    $endpoint = '';
    
    if (strpos($requestUri, $basePath) !== false) {
        $endpoint = substr($requestUri, strpos($requestUri, $basePath) + strlen($basePath));
        $endpoint = strtok($endpoint, '?'); // Remove query parameters
    }
    
    // Get request data
    $data = [];
    if ($method === 'GET') {
        $data = $_GET;
    } else {
        $input = file_get_contents('php://input');
        if ($input) {
            $data = json_decode($input, true) ?: [];
        }
        // Merge with POST data if available
        $data = array_merge($data, $_POST);
    }
    
    // Get request headers
    $headers = getallheaders() ?: [];
    
    // Handle API request
    $response = $api->handleRequest($method, $endpoint, $data, $headers);
    
    // Set HTTP status code
    http_response_code($response['status']);
    
    // Return JSON response
    echo json_encode($response);
    
} catch (Exception $e) {
    // Log error
    $logger = VLogger::getInstance();
    $logger->error('API error', [
        'error' => $e->getMessage(),
        'method' => $_SERVER['REQUEST_METHOD'] ?? '',
        'uri' => $_SERVER['REQUEST_URI'] ?? '',
        'trace' => $e->getTraceAsString()
    ]);
    
    // Return error response
    http_response_code(500);
    echo json_encode([
        'status' => 500,
        'data' => ['error' => 'Internal server error'],
        'timestamp' => time(),
        'version' => 'v1'
    ]);
}
?>