<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 4/25/16
 * Time: 8:02 PM
 */

namespace IMATHUZH\Qfq\Api;

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

use IMATHUZH\Qfq\Core\Exception\GenericException;
use IMATHUZH\Qfq\Core\File;
use IMATHUZH\Qfq\Core\Helper\Support;

/**
 * Process File Upload - immediately when the the user selects a file.
 * Return JSON encoded answer
 *
 * status: success|error
 * message: <message>
 *
 * Description:
 *
 * Upload successful & File accepted by server.
 *  status = 'success'
 *  message = <message>
 *
 * Upload failed:
 *  status = 'error'
 *  message = <message>
 */

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

$fileUpload = null;
$answer = array();
$answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
$answer[API_MESSAGE] = '';

try {
    try {
        $fileUpload = new File();

        $fileUpload->process();

        if ($fileUpload->imageUploadFilePath) {
            // TinyMce: Use a location key to specify the path to the saved image resource.
            // { location : '/your/uploaded/image/file'}
            $answer = array('location' => $fileUpload->imageUploadFilePath);
        } else {
            $answer[API_MESSAGE] = 'upload: success';
//    $answer[API_REDIRECT] = API_ANSWER_REDIRECT_NO;
            $answer[API_STATUS] = API_ANSWER_STATUS_SUCCESS;
            if ($fileUpload->sipTmp !== null) {
                $answer['sipTmp'] = $fileUpload->sipTmp;
            }
            if ($fileUpload->fileIndex !== null) {
                $answer['fileIndex'] = $fileUpload->fileIndex;
            }
            if ($fileUpload->uniqueFileId !== null) {
                $answer = array('uniqueFileId' => $fileUpload->uniqueFileId, 'groupId' => $fileUpload->groupId);
            }
        }
    } catch (\UserFormException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
    } catch (\CodeException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
    }

    if ($fileUpload->imageUploadFilePath === null) {
        header("Content-Type: application/json");
    }
} catch (\Throwable $e) {
    $wrapped = Support::wrapUnexpectedException($e);
    try {
        $answer[API_MESSAGE] = $wrapped->formatException();
    } catch (\Throwable $exception) {
        $answer[API_MESSAGE] = 'An unexpected error occurred.';
    }
}

echo json_encode($answer);


