<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 17.02.19
 * Time: 15:40
 */

namespace IMATHUZH\Qfq\Api;

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

use IMATHUZH\Qfq\Core\Exception\GenericException;
use IMATHUZH\Qfq\Core\Helper\OnString;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\QuickFormQuery;

// Detect API calls if this is defined. Do not try use "const QFQ_API 'Api call'" in Constanst.php : this will break detection of API Calls
define('QFQ_API', 'Api call');

$restId = array();
$restForm = array();

$status = HTTP_400_BAD_REQUEST;
$data = array();

try {
    try {
        $form = OnString::splitPathInfoToIdForm($_SERVER['PATH_INFO'] ?? '', $restId, $restForm);

        // get latest `ìd`
        $id = end($restId);

        // Fake Bodytext setup
        $bodytext = TYPO3_RECORD_ID . '=' . $id . PHP_EOL;
        $bodytext .= TYPO3_FORM . '=' . $form . PHP_EOL;

        $method = $_SERVER['REQUEST_METHOD'] ?? '';
        switch ($method) {
            case REQUEST_METHOD_GET:
                $status = HTTP_200_OK;
                break;

            case REQUEST_METHOD_POST:
                if ($id != 0) {
                    throw new \UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Forbidden: id>0 with HTTP method $method",
                        ERROR_MESSAGE_TO_DEVELOPER => '',
                        ERROR_MESSAGE_HTTP_STATUS => HTTP_400_BAD_REQUEST
                    ]), ERROR_REST_INVALID_ID);
                }

                $data = json_decode(file_get_contents('php://input'), true);
                $status = HTTP_201_CREATED;
                break;

            case REQUEST_METHOD_PUT:
                if ($id == 0) {
                    throw new \UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Forbidden: id==0 with HTTP method $method",
                        ERROR_MESSAGE_TO_DEVELOPER => '',
                        ERROR_MESSAGE_HTTP_STATUS => HTTP_400_BAD_REQUEST
                    ]), ERROR_REST_INVALID_ID);
                }
                $data = json_decode(file_get_contents('php://input'), true);
                $status = HTTP_200_OK;
                break;

            case REQUEST_METHOD_DELETE:
                if ($id == 0) {
                    throw new \UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Forbidden: id==0 with HTTP method $method",
                        ERROR_MESSAGE_TO_DEVELOPER => '',
                        ERROR_MESSAGE_HTTP_STATUS => HTTP_400_BAD_REQUEST
                    ]), ERROR_REST_INVALID_ID);
                }
                $status = HTTP_200_OK;
                break;

            default:
                throw new \UserFormException(json_encode([ERROR_MESSAGE_TO_USER => 'Unsupported/unknown HTTP request method',
                    ERROR_MESSAGE_TO_DEVELOPER => 'HTTP Code: ' . $method,
                    ERROR_MESSAGE_HTTP_STATUS => HTTP_403_METHOD_NOT_ALLOWED
                ]), ERROR_UNKNOWN_MODE);
                break;
        }

        if ($data === null) {
            throw new \UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Missing or broken JSON",
                ERROR_MESSAGE_TO_DEVELOPER => json_last_error_msg(),
                ERROR_MESSAGE_HTTP_STATUS => HTTP_400_BAD_REQUEST
            ]), ERROR_BROKEN_PARAMETER);
        }

        if (!empty($data)) {
            $_POST = $data;
        }

        $qfq = new QuickFormQuery([T3DATA_BODYTEXT => $bodytext], isApi: true);
        $answer = $qfq->rest($restId, $restForm);

    } catch (\CodeException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
        $status = $e->getHttpStatus();

    } catch (\UserFormException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
        $status = $e->getHttpStatus();

    } catch (\DbException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
        $status = $e->getHttpStatus();
    }

} catch (\Throwable $e) {
    $wrapped = Support::wrapUnexpectedException($e);
    $status = HTTP_400_BAD_REQUEST;
    try {
        $answer[API_MESSAGE] = $wrapped->formatException();
    } catch (\Throwable $exception) {
        $answer[API_MESSAGE] = 'An unexpected error occurred.';
    }
}

header('HTTP/1.0 ' . $status);
header("Content-Type: application/json");
echo json_encode($answer);
