<?php declare(strict_types=1);

require_once __DIR__ . '/src/common/QrbException.php';

// needs globals $qrbApi, $qrbCfg

// included by index.php

// Target for file upload POSTs with action 'submit' in QrBillsUploadForm.php.
//
// Shows the result in a separate DIV.

// keys for submitting the input files, see also function checkUploadedData()
const PDF_DATA_KEY     = "PdfData";
const PDF_TMPL_KEY     = "PdfTemplate";
const PDF_TMPL_DE_KEY  = "PdfTemplateDe";
const PDF_TMPL_FR_KEY  = "PdfTemplateFr";
const PDF_TMPL_IT_KEY  = "PdfTemplateIt";
const PDF_TMPL_EN_KEY  = "PdfTemplateEn";
const CRED_INFO_KEY    = "CreditorInformation";
const ADD_INFO_KEY     = "AdditionalInformation";
const MAIL_DATA_KEY    = "MailData";
const MAIL_BODY_KEY    = "MailBody";
const MAIL_BODY_DE_KEY = "MailBodyDe";
const MAIL_BODY_FR_KEY = "MailBodyFr";
const MAIL_BODY_IT_KEY = "MailBodyIt";
const MAIL_BODY_EN_KEY = "MailBodyEn";
const RCPT_INFO_KEY    = "Recipients";

if (isset($_POST['submit']))
{
?>

<div class="msg">
    <p>

<?php 
    // Sets the error handler to throw an ErrorException.
    set_error_handler(
        function($errno, $errstr, $errfile, $errline)
        {
            throw new ErrorException($errstr, $errno, 0, $errfile, $errline);     
        }
    );

    if ( checkAndMove() )    // prints errors
    {
        print $qrbApi->xl('upload.success');
    }
    else
    {
        print "<br />";
        print "<strong>";
        print $qrbApi->xl('upload.failed');
        print "</strong>";
    }
?>

    </p>
</div>

<?php
} 

// Checks the uploaded file and if valid moves it to target destination.
// Needs global variables $qrbApi and $qrbXl.
function checkAndMove() : bool
{
    global $qrbApi;
    global $qrbXl;
    $qrbApi->writeLog("Upload started");

    try
    {
        $qrbApi->writeLog("Start checking uploaded data");
        $result = checkFile(findFileEntry());
        $qrbApi->writeLog("End checking uploaded data");

        // everything is ok, try to move uploaded file to target destination
        $qrbApi->storeInputData($result["tmpFileName"], 
                                $result["srcFileName"], 
                                $result["dataType"], 
                                $result["language"]);
        return true;
    }
    catch (QrbException $e)
    {
        $msg = $qrbApi->xl($e->getLocalizeKey());
        print "<strong>{$msg}</strong> {$e->getAdditionalInformation()}";
        $qrbApi->writeLog("{$msg}: {$e}");
        return false;
    }
    catch (\Throwable $th)
    {
        $msg = $qrbApi->xl("exception.unexpectedError1") . $th->getMessage() . $qrbApi->xl("exception.unexpectedError2"); 
        print $msg;
        $qrbApi->writeLog("{$msg}: {$th}");
        return false;
    }
    finally
    {
        $qrbApi->writeLog("Upload finished");
    }
}

// Finds the entry for the uploaded file.
// Returns an array with:
// "key":      key, one of the XXX_KEY constants
// "dataType": QrbDataType
// "language": language, one of "de", "fr", "it", "en" or "" (no or default language)
// Needs global variable $_FILES.
function findFileEntry() : array
{
    // known files 
    $list = array(
        //    name in form (key)         target data type                         language     
        array("key" => PDF_DATA_KEY,     "dataType" => QrbDataType::PDF_DATA,     "language" => ""),
        array("key" => PDF_TMPL_KEY,     "dataType" => QrbDataType::PDF_TEMPLATE, "language" => ""),
        array("key" => PDF_TMPL_DE_KEY,  "dataType" => QrbDataType::PDF_TEMPLATE, "language" => "de"),
        array("key" => PDF_TMPL_FR_KEY,  "dataType" => QrbDataType::PDF_TEMPLATE, "language" => "fr"),
        array("key" => PDF_TMPL_IT_KEY,  "dataType" => QrbDataType::PDF_TEMPLATE, "language" => "it"),
        array("key" => PDF_TMPL_EN_KEY,  "dataType" => QrbDataType::PDF_TEMPLATE, "language" => "en"),
        array("key" => CRED_INFO_KEY,    "dataType" => QrbDataType::CRED_INFO,    "language" => ""),
        array("key" => ADD_INFO_KEY,     "dataType" => QrbDataType::ADD_INFO,     "language" => ""),
        array("key" => MAIL_DATA_KEY,    "dataType" => QrbDataType::MAIL_DATA,    "language" => ""),
        array("key" => MAIL_BODY_KEY,    "dataType" => QrbDataType::MAIL_BODY,    "language" => ""),
        array("key" => MAIL_BODY_DE_KEY, "dataType" => QrbDataType::MAIL_BODY,    "language" => "de"),
        array("key" => MAIL_BODY_FR_KEY, "dataType" => QrbDataType::MAIL_BODY,    "language" => "fr"),
        array("key" => MAIL_BODY_IT_KEY, "dataType" => QrbDataType::MAIL_BODY,    "language" => "it"),
        array("key" => MAIL_BODY_EN_KEY, "dataType" => QrbDataType::MAIL_BODY,    "language" => "en"),
        array("key" => RCPT_INFO_KEY,    "dataType" => QrbDataType::RECIPIENTS,   "language" => "")
    );

    // search key in list
    for ($row = 0; $row < count($list); $row++)
    {
        if (array_key_exists($list[$row]["key"], $_FILES))
        {
            return $list[$row];
        }
    }

    // not found    
    throw new QrbException("QrBillsUpload - findFileEntry() - Invalid upload file.",
                           "exception.upload.invalidUploadFile",
                           "unknown");
}


// Checks the uploaded file defined by the given listEntry, returning an array with:
// [tmpFileName]: tmpFileName
// [srcFileName]: srcFileName
// [dataType]:    QrbDataType
// [language]:    language, one of "de", "fr", "it", "en" or "" (no or default language)
// Needs global variables $_FILES, $qrbApi and $qrbCfg.
function checkFile(array $listEntry) : array
{
    global $qrbApi;
    global $qrbCfg;

    $key      = $listEntry["key"];
    $dataType = $listEntry["dataType"];
    $language = $listEntry["language"];

    // Check file size
    if ($_FILES[$key]["size"] > 5000000)
        throw new QrbException("QrBillsUpload - checkFile() - File is too large (> 5'000'000 bytes).",
                               "exception.upload.fileTooLarge",
                               $dataType);

    // validate
    $srcFileName = $_FILES[$key]["name"];
    $ext = strtolower(pathinfo($srcFileName, PATHINFO_EXTENSION));
    $tmpFileName = $_FILES[$key]["tmp_name"];
    $qrbApi->writeLog("Validating file '{$srcFileName}' uploaded to '{$tmpFileName}' for data type '{$dataType->value}' ...");
    $qrbApi->validateInputData($dataType, $tmpFileName, $ext, $qrbCfg);

    return array("tmpFileName" => $tmpFileName, 
                 "srcFileName" => $srcFileName, 
                 "dataType"    => $dataType, 
                 "language"    => $language);
}

?>
