<?php

/**
 * Multi-Product Firmware API - Version Endpoint
 *
 * URL Format: /api/v1/{product}/{stage}/{device}/version
 * Example: /api/v1/climate-controller/prod/rm-e32-r6-b6/version
 *
 * Query Parameters:
 * - current_version: Current firmware version on device (optional)
 * - format: Response format (json, simple) - default: json
 *
 * Response Format:
 * {
 *   "update_available": true,
 *   "latest_version": "v1.2.3",
 *   "current_version": "v1.2.0",
 *   "download_url": "https://firmware.ryzer.one/products/climate-controller/prod/rm-e32-r6-b6/firmware.bin",
 *   "file_size": 1252464,
 *   "timestamp": 1757075710,
 *   "build_type": "prod",
 *   "product": "climate-controller",
 *   "device": "rm-e32-r6-b6",
 *   "stage": "prod",
 *   "metadata": {...}
 * }
 */

require_once 'common.php';

// Parse URL path to extract product, stage and device from REQUEST_URI
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
$pathInfo = parse_url($requestUri, PHP_URL_PATH);

// Extract path after /api/v1/ - handle both PATH_INFO and REQUEST_URI parsing
if (strpos($pathInfo, '/api/v1/') === 0) {
    $apiPath = substr($pathInfo, 8); // Remove '/api/v1/' prefix
    $pathParts = array_filter(explode('/', $apiPath));
} else {
    $pathInfo = $_SERVER['PATH_INFO'] ?? '';
    $pathParts = array_filter(explode('/', $pathInfo));
}

// Expected URL: /api/v1/{product}/{stage}/{device}/version
// pathParts should be: [product, stage, device, 'version']
if (count($pathParts) < 4) {
    sendError('Invalid URL format. Expected: /api/v1/{product}/{stage}/{device}/version', 400);
}

$product = $pathParts[0];
$stage = $pathParts[1];
$device = $pathParts[2];
$endpoint = $pathParts[3];

if ($endpoint !== 'version') {
    sendError('Unknown endpoint. Expected: version', 404);
}

// Validate parameters
$error = validateParameters($product, $stage, $device);
if ($error) {
    sendError($error['error'], 400);
}

// Get query parameters
$currentVersion = $_GET['current_version'] ?? null;
$format = $_GET['format'] ?? 'json';

// Log the access
logAccess($product, $stage, $device, 'version_check');

// Get latest firmware and all firmware files for comparison
$latestFirmware = getLatestFirmware($product, $stage, $device);
$allFirmwareFiles = getFirmwareFiles($product, $stage, $device);

if (!$latestFirmware) {
    sendError("No firmware found for device '$device' in product '$product' stage '$stage'", 404);
}

// Build response
$response = [
    'product' => $product,
    'device' => $device,
    'stage' => $stage,
    'latest_version' => $latestFirmware['version'] ?? 'unknown',
    'current_version' => $currentVersion ?? 'unknown',
    'update_available' => false,
    'download_url' => getDownloadUrl($product, $stage, $device, $latestFirmware['bin_file']),
    'file_size' => $latestFirmware['size'],
    'timestamp' => $latestFirmware['modified'],
    'build_type' => $latestFirmware['build_type'] ?? 'unknown'
];

// Check if update is available (using hybrid approach)
if ($currentVersion && isset($latestFirmware['version'])) {
    $response['update_available'] = checkUpdateAvailable(
        $currentVersion,
        $latestFirmware['version'],
        $stage,
        $allFirmwareFiles
    );
}

// Add metadata if available
if (isset($latestFirmware['metadata'])) {
    $response['metadata'] = $latestFirmware['metadata'];
}

// Handle different response formats
if ($format === 'simple') {
    // Simple format for basic clients
    $simple = [
        'version' => $response['latest_version'],
        'url' => $response['download_url'],
        'size' => $response['file_size'],
        'update' => $response['update_available']
    ];
    sendJsonResponse($simple);
} else {
    // Full JSON response
    sendJsonResponse($response);
}
