<?php declare(strict_types=1);

namespace App\Controller;

use UnhandledMatchError;

error_reporting(error_level: E_ALL);

class ApiController
{

    /**
     * @param String $requestType
     * @param String $serverName
     * @param int $versionIP
     * @param String $apiKey
     * @param String $command
     * @param String $serverType
     * @param array $body
     *
     * @return array
     */
    function sendCommand(string $requestType, string $serverName, int $versionIP, string $apiKey, string $command, string $serverType, array $body = []): array
    {
        $error = false;
        $curl = curl_init();

        try {
            match ($serverType) {
                'panel' => curl_setopt(handle: $curl, option: CURLOPT_URL, value: "https://$serverName/api/v2/" . $command),
                'nameserver' => curl_setopt(handle: $curl, option: CURLOPT_URL, value: "https://$serverName/api/" . $command)
            };
        } catch (UnhandledMatchError) {
            exit('Unhandled match: ' . $serverType .' in ' . __FILE__ . ' on line ' . __LINE__ . PHP_EOL);
        }

        curl_setopt(handle: $curl, option: CURLOPT_RETURNTRANSFER, value: 1);
        curl_setopt(handle: $curl, option: CURLOPT_TIMEOUT_MS, value: 19999);
        curl_setopt(handle: $curl, option: CURLOPT_HTTP_VERSION, value: CURL_HTTP_VERSION_2TLS);

        if ($versionIP == 4) {
            curl_setopt(handle: $curl, option: CURLOPT_IPRESOLVE, value: CURL_IPRESOLVE_V4);
        } else {
            curl_setopt(handle: $curl, option: CURLOPT_IPRESOLVE, value: CURL_IPRESOLVE_V6);
        }

        curl_setopt(handle: $curl, option: CURLOPT_HTTPHEADER, value: ["X-API-Key:$apiKey"]);

        if ($requestType == "POST") {
            curl_setopt(handle: $curl, option: CURLOPT_POST, value: true);
            curl_setopt(handle: $curl, option: CURLOPT_POSTFIELDS, value: $body);
        }
        if ($requestType == "PUT") {
            curl_setopt(handle: $curl, option: CURLOPT_CUSTOMREQUEST, value: 'PUT');
            curl_setopt(handle: $curl, option: CURLOPT_POSTFIELDS, value: json_encode(value: $body));
        }

        curl_setopt(handle: $curl, option: CURLOPT_CUSTOMREQUEST, value: $requestType);

        if ($resultJSON = curl_exec(handle: $curl)) {
            $httpResponse = curl_getinfo(handle: $curl)['http_code'];

            switch ($httpResponse) {
                case 200:
                    $apiResult = json_decode(json: $resultJSON);
                    if ($command == "ping") {
                        if ($apiResult->response == "pong") {
                            $result = $apiResult->response;
                        } else {
                            $result = $apiResult;
                        }
                    } else {
                        $result = $resultJSON;
                    }
                    break;
                case 400:
                    $result = $resultJSON;
                    break;
                case 401:
                    $result = 'Missing or wrong API Key';
                    $error = true;
                    break;
                case 404:
                    $result = '404 Not Found';
                    break;
                case 500:
                    $result = 'server error';
                    break;
                default:
                    $result = 'Unhandled error: ' . $httpResponse;
            }
        } else {
            $error = true;
            $result = curl_error(handle: $curl);
        }

        $info = curl_getinfo(handle: $curl);
        $responseTime = $info['total_time'];

        curl_close(handle: $curl);
        return [
            'responseTime' => $responseTime,
            'error' => $error,
            'data' => $result,
            'header' => $httpResponse ?? ''
        ];
    }

    function fileGetContents(string $url, int $versionIP): ?array
    {
        $curl = curl_init(url: $url);

        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_AUTOREFERER    => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT        => 120,
            CURLOPT_MAXREDIRS      => 10,
        );

        if ($versionIP == 4) {
            curl_setopt(handle: $curl, option: CURLOPT_IPRESOLVE, value: CURL_IPRESOLVE_V4);
        } else {
            curl_setopt(handle: $curl, option: CURLOPT_IPRESOLVE, value: CURL_IPRESOLVE_V6);
        }

        curl_setopt_array(handle: $curl, options: $options);
        $content = curl_exec(handle: $curl);
        $error = curl_errno(handle: $curl);
        $errorMessage = curl_error(handle: $curl);
        $header = curl_getinfo(handle: $curl);
        curl_close(handle: $curl);

        $header['error']   = $error;
        $header['errorMessage']  = $errorMessage;
        $header['content'] = $content;

        return $header;
    }
}
