<?php
/**
 * Created by PhpStorm.
 * User: ep
 * Date: 12/23/15
 * Time: 6:16 PM
 */

namespace IMATHUZH\Qfq\Api;

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

use IMATHUZH\Qfq\Core\Exception\ErrorHandler;
use IMATHUZH\Qfq\Core\Exception\GenericException;
use IMATHUZH\Qfq\Core\Helper\OnString;
use IMATHUZH\Qfq\Core\Helper\Path;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\QuickFormQuery;
use IMATHUZH\Qfq\Core\Store\Store;
use IMATHUZH\Qfq\Core\Typo3\T3Handler;
use IMATHUZH\Qfq\Core\Database\DatabaseQfqSpecific;

/**
 * Return JSON encoded answer
 *
 * status: success|error
 * message: <message>
 * redirect: client|url|no
 * redirect-url: <url>
 * field-name: <field name>
 * field-message: <message>
 * form-data: [ fieldname1 => value1, fieldname2 => value2, ... ]
 * form-control: [ fieldname1 => status1, fieldname2 => status2, ... ]  status: show|hide, enabled|disabled,
 * readonly|readwrite
 *
 * Description:
 *
 * Save successful. Button 'close', 'new'. Form.forward: 'auto'. Client logic decide to redirect or not. Show message
 * if no redirect. status = 'success' message = <message> redirect = 'client'
 *
 * Save successful. Button 'close': Form.forward: 'page'. Client redirect to url.
 *  status = 'success'
 *  message = <message>
 *  redirect = 'url'
 *  redirect-url = <URL>
 *
 * Save failed: Button: any. Show message and set 'alert' on _optional_ specified form element. Bring 'pill' of
 * specified form element to front. status = 'error' message = <message> redirect = 'no' Optional: field-name = <field
 * name> field-message = <message appearing as tooltip (or similar) near the form element>
 */

// 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_AUTO;
$answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
$answer[API_MESSAGE] = '';

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

        // Get Save mode
        //TODO enured: Bitte CHAT umstellen das die Konstante SIP_MODE_SAVE anstelle de Strings 'mode' verwendet wird.
        //     Anschliessend den Wert der Konstanten 'SIP_MODE_SAVE' aendern von 'mode' zu '_modeSave'.  Siehe #18581.
        $mode = Store::getVar('mode', STORE_SIP);

        switch ($mode) {
            // Chat
            case CHAT_MODE_SAVE:
            case CHAT_MODE_TAG_DONE:
            case CHAT_MODE_TAG_ADD:
            case CHAT_MODE_TAG_DELETE:
                $data = $qfq->saveChat($mode);
                $answer[API_CHAT_UPDATE] = $data;
                break;
            // DB Update
            case SAVE_MODE_DB_UPDATE:
                $dbQfqUpdate = new DatabaseQfqSpecific();
                $dbQfqUpdate->playSelectedSqlFiles();
                break;
            // Regular save
            default:
                $data = $qfq->saveForm();
                break;
        }

        // In case of save for REPORT_SAVE or SAVE_MODE_DB_UPDATE: redirect to referer. Do nothing else.
        if (isset($data[REPORT_SAVE]) || $mode == SAVE_MODE_DB_UPDATE) {
            // Redirect to previous page
            $referer = $_SERVER['HTTP_REFERER'] ?? '';
            // Check if '?' is already in the referer URL
            $separator = (parse_url($referer, PHP_URL_QUERY) === null) ? '?' : '&';
            $preventBuildDevPanel = $separator . DEV_PANEL_PREVENT_BUILD_PARAM . '=1';

            header("Location: {$referer}{$preventBuildDevPanel}");
            return '';
        }

        $arr = $qfq->getForwardMode();
        $answer[API_REDIRECT] = $arr[API_REDIRECT];
        $redirectUrl = Support::appendTypo3ParameterToUrl($arr[API_REDIRECT_URL]);
        if (OnString::strStartsWith($redirectUrl, '/') && T3Handler::useSlugsInsteadOfPageAlias()) {
            $redirectUrl = Path::urlApp($redirectUrl);
        }
        $answer[API_REDIRECT_URL] = $redirectUrl;

        $answer[API_STATUS] = API_ANSWER_STATUS_SUCCESS;
        $answer[API_MESSAGE] = 'Saved';
        if (isset($data[API_ELEMENT_UPDATE])) {
            $answer[API_ELEMENT_UPDATE] = $data[API_ELEMENT_UPDATE];
        }

        if (isset($data[API_FORM_UPDATE])) {
            $answer[API_FORM_UPDATE] = $data[API_FORM_UPDATE];
        }

        if (isset($data[API_CHANGED_ELEMENTS])) {
            $answer[API_CHANGED_ELEMENTS] = $data[API_CHANGED_ELEMENTS];
        }

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

        $val = Store::getVar(FE_ALERT_TEXT, STORE_SYSTEM);
        if ($val !== false) {
            $answer[FE_ALERT_TEXT] = $answer[API_MESSAGE];
            $answer[FE_ALERT_LEVEL] = Store::getVar(FE_ALERT_LEVEL, STORE_SYSTEM);
            $answer[FE_ALERT_BUTTON_OK] = Store::getVar(FE_ALERT_BUTTON_OK, STORE_SYSTEM);
            $answer[FE_ALERT_BUTTON_FORCE] = Store::getVar(FE_ALERT_BUTTON_FORCE, STORE_SYSTEM);
            $answer[FE_ALERT_TIMEOUT] = Store::getVar(FE_ALERT_TIMEOUT, STORE_SYSTEM);
            $answer[FE_ALERT_FLAG_MODAL] = Store::getVar(FE_ALERT_FLAG_MODAL, STORE_SYSTEM);
        }

        $val = Store::getVar(SYSTEM_FORM_ELEMENT, STORE_SYSTEM);
        if ($val !== false) {
            $answer[API_FIELD_NAME] = $val;
        }

        $val = Store::getVar(SYSTEM_FORM_ELEMENT_MESSAGE, STORE_SYSTEM);
        if ($val !== false) {
            $answer[API_FIELD_MESSAGE] = $val;
        }

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

        $val = Store::getVar(FE_ALERT_TEXT, STORE_SYSTEM);
        if ($val !== false) {
            $answer[FE_ALERT_TEXT] = $answer[API_MESSAGE];
            $answer[FE_ALERT_LEVEL] = Store::getVar(FE_ALERT_LEVEL, STORE_SYSTEM);
            $answer[FE_ALERT_BUTTON_OK] = Store::getVar(FE_ALERT_BUTTON_OK, STORE_SYSTEM);
            $answer[FE_ALERT_BUTTON_FORCE] = Store::getVar(FE_ALERT_BUTTON_FORCE, STORE_SYSTEM);
            $answer[FE_ALERT_TIMEOUT] = Store::getVar(FE_ALERT_TIMEOUT, STORE_SYSTEM);
            $answer[FE_ALERT_FLAG_MODAL] = Store::getVar(FE_ALERT_FLAG_MODAL, STORE_SYSTEM);
        }
    }
} catch (\Throwable $e) {
    $wrapped = Support::wrapUnexpectedException($e);
    try {
        $answer[API_MESSAGE] = $wrapped->formatException();
    } catch (\Throwable $exception) {
        $answer[API_MESSAGE] = 'An unexpected error occurred.';
    }
}

header("Content-Type: application/json");
echo json_encode($answer);

