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

namespace IMATHUZH\Qfq\Api;

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

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

/**
 * delete: success
 *   SIP_MODE_ANSWER: MODE_HTML
 *     Send header 'location' to targetUrl
 *
 *   SUP_MODE_ANSWER: MODE_JSON
 *     Send AJAX answer with Status 'success'
 *
 * delete: failed
 *   SIP_MODE_ANSWER: MODE_HTML
 *     No forward, print error message.
 *
 *   SUP_MODE_ANSWER: MODE_JSON
 *     Send AJAX answer with Status 'error' and 'error message' as JSON encoded
 *
 *
 * JSON Format:
 *
 * status: success|error
 * message: <message>
 * redirect: client|url|no
 * redirect-url: <url>
 * field-name:<field name>
 * field-message: <message>
 *
 * Description:
 *
 * Delete successful.
 *  status = 'success'
 *  message = <message>
 *  redirect = 'client'
 *
 * Delete successful.
 *  status = 'success'
 *  message = <message>
 *  redirect = 'url'
 *  redirect-url = <URL>
 *
 * Delete failed: Show message.
 *  status = 'error'
 *  message = <message>
 *  redirect = 'no'
 */

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

$result[MSG_HEADER] = '';
$result[MSG_CONTENT] = '';

$modeAnswer = false;
$flagSuccess = false;

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

        $answer = $qfq->delete();

        // in case everything is fine, an empty string is returned. Else an Array.
        $flagSuccess = ($answer === '');

        $targetUrl = str_replace('--amp--', '&', Store::getVar(SIP_TARGET_URL, STORE_SIP));
        $modeAnswer = Store::getVar(SIP_MODE_ANSWER, STORE_SIP);

        switch ($modeAnswer) {
            case MODE_JSON:
                $answer = array();
                if ($flagSuccess) {
                    $answer[API_MESSAGE] = 'Deleted';
                    $answer[API_REDIRECT] = API_ANSWER_REDIRECT_AUTO;
                    $answer[API_STATUS] = API_ANSWER_STATUS_SUCCESS;
                } else {
                    $answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
                }

                break;

            case MODE_HTML:
                if ($targetUrl === false || $targetUrl === '') {
                    throw new \CodeException('Missing target URL', ERROR_MISSING_VALUE);
                }

                if ($flagSuccess) {
                    $result[MSG_HEADER] = "Location: $targetUrl";
                }
                break;

            default:
                throw new \CodeException('Unknown mode: ' . $modeAnswer, ERROR_UNKNOWN_MODE);
                break;
        }

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

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

// In case $modeAnswer is still missing: try to get it again - maybe the SIP store has been initialized before the exception has been thrown.
    if ($modeAnswer === false) {
        $modeAnswer = Store::getVar(SIP_MODE_ANSWER, STORE_SIP);
    }

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


if ($modeAnswer === MODE_JSON) {
    // JSON
    $result[MSG_HEADER] = "Content-Type: application/json";
    $result[MSG_CONTENT] = json_encode($answer);
} else {
    // HTML
    if (!$flagSuccess) {
        $result[MSG_CONTENT] = "<p>" . $answer[API_MESSAGE] . "</p>";
        if (isset($answer[API_FIELD_NAME])) {
            $result[MSG_CONTENT] .= "<p>" . $answer[API_FIELD_NAME] . " : " . $answer[API_FIELD_MESSAGE] . "</p>";
        }
    }
}

// Send header, if given.
if ($result[MSG_HEADER] !== '') {
    header($result[MSG_HEADER]);
}

echo $result[MSG_CONTENT];