<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 08/09/20
 * Time: 6:17 PM
 */

namespace IMATHUZH\Qfq\Api;

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

use IMATHUZH\Qfq\Core\Exception\ErrorHandler;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\QuickFormQuery;
use IMATHUZH\Qfq\Core\Store\Store;


/**
 * Return JSON encoded answer
 *
 * status: success|error
 * message: <message>
 * redirect: client|url|no
 * redirect-url: <url>
 *
 * Description:
 *
 * Save successful.
 *
 */

// 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');

$answer = array();

$answer[API_REDIRECT] = API_ANSWER_REDIRECT_NO;
$answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
$answer[API_MESSAGE] = '';
$status = HTTP_400_BAD_REQUEST;

try {
    try {
        ErrorHandler::useAsPhpErrorHandler();
        $qfq = new QuickFormQuery([T3DATA_BODYTEXT => ''], isApi: true);

        $data = $qfq->dataReport();

        // Get custom headers from record store
        $headers = Store::getInstance()->getVar(API_HEADER_VARIABLE_KEY, 'RE');
        if (!empty($headers)) {
            $headers = str_replace("\r\n", '$$SEP$$', $headers);
            $headers = str_replace("\n", '$$SEP$$', $headers);
            $headers = explode('$$SEP$$', $headers);
        } else {
            $headers = [];
        }

        $status = HTTP_200_OK;

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

// error output
if ($status === HTTP_400_BAD_REQUEST) {
    header('HTTP/1.0 ' . $status);
    header("Content-Type: application/json");
    echo json_encode($answer);
    exit();
}

// normal output
foreach ($headers as $header) {
    header($header);
}
echo $data;