<?php declare(strict_types=1);

require_once __DIR__ . '/src/QrbApi.php';

// Target for POST with action "dryRun", "testRun" or "process" in QrBillsProcess.js.
//
// This code will respond with HTTP code 200 (ok), if the function was executed (and a status file was written).
// Answers with HTTP code 400 (bad request) if the received request was not for 'dryRun', 'testRun' or 'processRun'.
// Answers with HTTP code 403 (forbidden) if the current profile is locked.
// Answers with HTTP code 500 (server error) if some unforeseen exception occurred.
// Answers with HTTP code 503 (service unavailable) if the process has thrown a known execption.

const HTTP_CODE_BAD_REQUEST         = 400;
const HTTP_CODE_FORBIDDEN           = 403;
const HTTP_CODE_SERVER_ERROR        = 500;
const HTTP_CODE_SERVICE_UNAVAILABLE = 503;

if (array_key_exists('dryRun', $_POST))
{
    $qrbApi = new QrbApi(Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));

    execute($qrbApi, function() use ($qrbApi)
    {
        $qrbApi->dryRun();
    });
}
else
if (array_key_exists('testRun', $_POST))
{
    $testEmailAddress = "";    // preset testEmailAddress, it must not be NULL
    if (array_key_exists('testEmailAddress', $_POST))
        $testEmailAddress = htmlspecialchars_decode($_POST["testEmailAddress"]);
        
    $qrbApi = new QrbApi(Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));
    
    execute($qrbApi, function() use ($qrbApi, $testEmailAddress)
    {
        $qrbApi->testRun($testEmailAddress);    // will test for valid mail address
    });
}
else
if (array_key_exists('processRun', $_POST))
{
    $qrbApi = new QrbApi(Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));
    
    execute($qrbApi, function() use ($qrbApi)
    {
        $qrbApi->processRun();
    });
}
else
{
    http_response_code(HTTP_CODE_BAD_REQUEST);
    exit;
}

// Executes the given function.
// Catches QrbException to send a 503 (HTTP_CODE_SERVICE_UNAVAILABLE) response.
// Catches Throwable to send a 500 (HTTP_CODE_SERVER_ERROR) response.
//
// qrbApi:         used to write to the log
// functionToCall: function to call
function execute(QrbApi $qrbApi, Closure $functionToCall) : void
{
    try
    {
        $functionToCall();
    }
    catch (QrbLockedException $e)
    {
        $msg = $qrbApi->xl($e->getLocalizeKey());
        $qrbApi->writeLog("{$msg}: {$e}");
        http_response_code(HTTP_CODE_FORBIDDEN);
        exit;
    }
    catch (QrbException $e)
    {
        $msg = $qrbApi->xl($e->getLocalizeKey());
        $qrbApi->writeLog("{$msg}: {$e}");
        http_response_code(HTTP_CODE_SERVICE_UNAVAILABLE);
        exit;
    }
    catch (\Throwable $th)
    {
        $msg = $qrbApi->xl("exception.unexpectedError1") . $th->getMessage() . $qrbApi->xl("exception.unexpectedError2"); 
        $qrbApi->writeLog("{$msg}: {$th}");
        http_response_code(HTTP_CODE_SERVER_ERROR);
        exit;
    }
}

?>
