<?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\Helper\HelperFile;
use IMATHUZH\Qfq\Core\Helper\Path;
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);

    // Get hostname
    $hostname = gethostname();

    $blacklistWords = [
        'DB_1_PASSWORD',
        'DB_2_PASSWORD',
        'DB_3_PASSWORD',
        'DB_4_PASSWORD',
        'LDAP_1_PASSWORD',
        'installToolPassword',
        'password',
        'secretKey',
        'forwardServiceSecret',
        'encryptionKey',
    ];

    // Get files
    $filePaths = [
        Path::absoluteConf(CONFIG_QFQ_JSON),
        Path::absoluteTypo3Conf('LocalConfiguration.php'),
    ];

    $contents = HelperFile::getFileContents($filePaths, $blacklistWords);

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

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

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

    $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);
