<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 4/17/17
 * Time: 5:51 PM
 *
 * Check: CODING.md > Download
 */

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\Report\Download;

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

set_error_handler("\\IMATHUZH\\Qfq\\Core\\Exception\\ErrorHandler::exception_error_handler");

$output = '';

try {
    try {
        $download = new Download();
        // Options NOT SET => don't do anything extra | prepFile => only return file info (downloadPath, fileOutputName, downloadMode) | downloadFile => Only Read file and clean Temp file
        $isModal = $_GET[DOWNLOAD_MODAL_API_PARAMETER] ?? false;
        // If all is fine: process() will output file via print() !!
        $output = $download->process(STORE_SIP, OUTPUT_MODE_DIRECT, $isModal);

    } catch (\CodeException $e) {
        $output = $e->formatMessage();
    } catch (\DbException $e) {
        $output = $e->formatMessage();
    } catch (\DownloadException $e) {
        $output = $e->formatMessage();
    }
} catch (\Throwable $e) {

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

}

echo $output;
