<?php
/**
 * Created by PhpStorm.
 * User: enured
 * Date: 19.09.24
 * Time: 11:00
 */

namespace IMATHUZH\Qfq\Api;

require_once(__DIR__ . '/../../vendor/autoload.php');

use IMATHUZH\Qfq\Core\Store\Client;
use IMATHUZH\Qfq\Core\Store\Config;
use IMATHUZH\Qfq\Core\Store\Store;
use IMATHUZH\Qfq\Core\Store\T3Info;

// Detect API calls if this is defined.
define('QFQ_API', 'Api call');

try {
    // Get variables from qfq store and T3Info
    $store = Store::getInstance();
    $vars = T3Info::getVars();

    // Verify API token
    $headers = Client::getParam();
    $providedToken = $headers['Authorization'] ?? '';
    $validToken = $store::getVar(SYSTEM_QFQ_VERSION_API_TOKEN, STORE_SYSTEM);

    if (empty($validToken)) {
        throw new \Exception("Server configuration error: API token not set", 500);
    }

    if (empty($providedToken)) {
        throw new \Exception("No API token provided: " . $providedToken, 401);
    }

    if ($providedToken !== $validToken) {
        throw new \Exception("Invalid API token", 401);
    }

    // Get all extensions and their versions
    $extensions = T3Info::getAllExtensionsInfo();
    $extensions = Config::getExtVersion($extensions);

    // Get TYPO3 site name (project name)
    $siteName = $store::getVar(SYSTEM_T3_SITE_NAME, STORE_SYSTEM);

    // Get TYPO3 version
    $typo3Version = $vars['t3Version'] ?? 'unknown';

    $url = $store::getVar(SYSTEM_BASE_URL, STORE_SYSTEM);

    // Prepare response data
    $data = [
        'url' => $url,
        'project' => $siteName,
        'typo3' => $typo3Version,
    ];

    // Get deb packages
    $data['deb-packages'] = Config::getServerInfo();

    // Add extensions to response
    $data = array_merge($data, $extensions);

    $status = 200;
} catch (\Exception $e) {
    $status = $e->getCode() ?: 500;
    $data = [
        'error' => $e->getMessage(),
    ];
}

// Send response
header('HTTP/1.1 ' . $status);
header('Content-Type: application/json');
echo json_encode($data);
