<?php declare(strict_types=1);

// needs globals $qrbApi, $qrbCfg

// included by index.php

// This file also provides the method reloadPage() for other code fragments (includes).

// Target for POSTs with action 'saveQrBillsConfiguration' 
// in QrBillsUseCaseSelection.php and QrBillsConfigurationSelection.php.
//
// If an error occurs then inserts a div with the error message.

if (!array_key_exists('saveQrBillsConfiguration', $_POST))
{
    return;
}

if (array_key_exists('UseCaseSelection', $_POST))
{
    // call from Use Case Selection
    $useCaseSelection = $_POST['UseCaseSelection'];
    $qrbApi->writeLog("UseCaseSelection = '{$useCaseSelection}'");
    
    if  (  ($useCaseSelection != "PdfWithPaymentSlip") 
        && ($useCaseSelection != "PdfWithoutPaymentSlip")
        && ($useCaseSelection != "MailWithoutPdf") )
        die("Unknown use case '{$useCaseSelection}'");
}


global $qrbApi;
global $qrbCfg;

// preset PDF configuration
$createPdf        = $qrbCfg->getCreatePdf();
$currency         = $qrbCfg->getCurrency();
$printAmount      = $qrbCfg->getPrintAmount();
$amount           = $qrbCfg->getAmount();

// preset payment slip configuration
$printPaymentSlip = $qrbCfg->getPrintPaymentSlip();
$addDebtor        = $qrbCfg->getAddDebtor();
$addRefToAddInfo  = $qrbCfg->getAddRefToAddInfo();

// preset mail configuration
$sendMail         = $qrbCfg->getSendMail();
$presetMail       = $qrbCfg->getPresetMail();
$sleepAfterSend   = $qrbCfg->getSleepAfterSend();

// preset multi-language configuration
$defaultLang      = $qrbCfg->getDefaultLanguage();
$multiLang        = $qrbCfg->getMultiLanguage();
$addLang          = $qrbCfg->getAdditionalLanguages();

// evaluate received values
if (array_key_exists('createPdf', $_POST))
{
    $createPdf = filter_var($_POST['createPdf'], FILTER_VALIDATE_BOOLEAN);
    $qrbApi->writeLog("new createPdf = " . ($createPdf ? "true" : "false"));
}

// some values are only valid if a PDF is created
if ($createPdf)
{
    if (array_key_exists('currency', $_POST))
    {
        $newCurrency = $_POST['currency'];
        $qrbApi->writeLog("new Currency = '{$newCurrency}'");
        
        if  (  ($newCurrency != QrbProfileConfiguration::CHF)
            && ($newCurrency != QrbProfileConfiguration::EUR) )
            die("Invalid new currency '{$newCurrency}'");

        $currency = $newCurrency;
    }

    if (array_key_exists('printAmount', $_POST))
    {
        $newPrintAmount = $_POST['printAmount'];
        $qrbApi->writeLog("new PrintAmount = '{$newPrintAmount}'");
        
        if  (  ($newPrintAmount != QrbProfileConfiguration::NO_AMOUNT) 
            && ($newPrintAmount != QrbProfileConfiguration::GLOBAL_AMOUNT)
            && ($newPrintAmount != QrbProfileConfiguration::INDIVIDUAL_AMOUNT) )
            die("Invalid new printAmount '{$newPrintAmount}'");

        $printAmount = $newPrintAmount;
    }

    if (array_key_exists('amount', $_POST))
    {
        $newAmount = $_POST['amount'];
        $qrbApi->writeLog("new Amount = '{$newAmount}'");
        
        if ($newAmount !== "")
        {
            $newFilteredAmount = filter_var($newAmount, FILTER_VALIDATE_FLOAT);
            if ($newFilteredAmount === false)
                die("Invalid new amount '{$newAmount}'");
                
            $amount = $newFilteredAmount;
        }
        else
        {
            $qrbApi->writeLog("new Amount ignored as empty");
        }
    }
}
    
if (array_key_exists('printPaymentSlip', $_POST))
{
    $printPaymentSlip = filter_var($_POST['printPaymentSlip'], FILTER_VALIDATE_BOOLEAN);
    $qrbApi->writeLog("new printPaymentSlip = " . ($printPaymentSlip ? "true" : "false"));
}

// some values are only valid if a payment slip is created
if ($printPaymentSlip)
{
    if (array_key_exists('addDebtor', $_POST))
    {
        $addDebtor = filter_var($_POST['addDebtor'], FILTER_VALIDATE_BOOLEAN);
        $qrbApi->writeLog("new addDebtor = " . ($addDebtor ? "true" : "false"));
    }
    
    if (array_key_exists('addRefToAddInfo', $_POST))
    {
        $addRefToAddInfo = filter_var($_POST['addRefToAddInfo'], FILTER_VALIDATE_BOOLEAN);
        $qrbApi->writeLog("new addRefToAddInfo = " . ($addRefToAddInfo ? "true" : "false"));
    }
}

if (array_key_exists('sendMail', $_POST))
{
    $sendMail = filter_var($_POST['sendMail'],  FILTER_VALIDATE_BOOLEAN);
    $qrbApi->writeLog("new sendMail = " . ($sendMail ? "true" : "false"));
}

// some values are only valid if a mail is sent
if ($sendMail)
{
    if (array_key_exists('presetMail', $_POST))
    {
        $presetMail = filter_var($_POST['presetMail']);
        $qrbApi->writeLog("new presetMail = '{$presetMail}'");
    }

    if (array_key_exists('sleepAfterSend', $_POST))
    {
        $newSleepAfterSend = $_POST['sleepAfterSend'];
        $qrbApi->writeLog("new sleepAfterSend = {$newSleepAfterSend}");
        
        $newFilteredSleepAfterSend = filter_var($newSleepAfterSend, FILTER_VALIDATE_INT);
        if ($newFilteredSleepAfterSend === false)
            die("Invalid new sleepAfterSend '{$newSleepAfterSend}'");
            
        $sleepAfterSend = $newFilteredSleepAfterSend * SLEEP_FACTOR;
        $qrbApi->writeLog("new sleepAfterSend after applying factor = {$sleepAfterSend}");
    }
}

if (array_key_exists('defaultLang', $_POST))
{
    $defaultLang = $_POST['defaultLang'];
    $qrbApi->writeLog("new defaultLang = '{$defaultLang}'");
}

if (array_key_exists('multiLang', $_POST))
{
    $multiLang = filter_var($_POST['multiLang'], FILTER_VALIDATE_BOOLEAN);
    $qrbApi->writeLog("new multiLang = " . ($multiLang ? "true" : "false"));
}

// some values are only valid if multi-language is enabled
if ($multiLang)
{
    $newAddLang = array();
    if (array_key_exists('addLang_de',  $_POST))    array_push($newAddLang, "de");
    if (array_key_exists('addLang_fr',  $_POST))    array_push($newAddLang, "fr");
    if (array_key_exists('addLang_it',  $_POST))    array_push($newAddLang, "it");
    if (array_key_exists('addLang_en',  $_POST))    array_push($newAddLang, "en");

    // only change additionalLanguages if at least one of the keys has been sent
    if (!empty($newAddLang))
    {
        $addLang = $newAddLang;
        $printableAddLang = "";
        foreach ($addLang as $key => $value)    $printableAddLang .= "'{$value}' ";
        $qrbApi->writeLog("new addLang = {$printableAddLang}");
    }
}
else
{
    $addLang = array();    // delete additional languages if multi-language is off
    $qrbApi->writeLog("new addLang = empty");
}

// now, set the values into qrbCfg ...
$qrbCfg->setCreatePdf($createPdf);
$qrbCfg->setCurrency($currency);
$qrbCfg->setPrintAmount($printAmount);
$qrbCfg->setAmount($amount);
$qrbCfg->setPrintPaymentSlip($printPaymentSlip);
$qrbCfg->setAddDebtor($addDebtor);
$qrbCfg->setAddRefToAddInfo($addRefToAddInfo);
$qrbCfg->setSendMail($sendMail);
$qrbCfg->setPresetMail($presetMail);
$qrbCfg->setSleepAfterSend($sleepAfterSend);
$qrbCfg->setDefaultLanguage($defaultLang);
$qrbCfg->setMultiLanguage($multiLang);
$qrbCfg->setAdditionalLanguages($addLang);

// ... and try to store the new configuration
try
{
    $qrbApi->storeProfileConfiguration($qrbCfg);
    reloadPage();
}
catch (QrbException $e)
{
    $msg = $qrbApi->xl($e->getLocalizeKey());
    print '<div class="highlight"><p>';
    print "<strong>{$msg}</strong> {$e->getAdditionalInformation()}";
    print '</p></div>';
    $qrbApi->writeLog("{$msg}: {$e}");
}
catch (\Throwable $th)
{
    $msg = $qrbApi->xl("exception.unexpectedError1") . $th->getMessage() . $qrbApi->xl("exception.unexpectedError2"); 
    print '<div class="highlight"><p>';
    print $msg;
    print '</p></div>';
    $qrbApi->writeLog("{$msg}: {$th}");
}


//////////////////////////////////////////////////////////////////////////////////////////

// Reloads web page.
// Also called by QrBillsProfileSelection.php.
function reloadPage() : void
{
    print '<script type="text/javascript">';
    print '  window.location.href = window.location.href.split("#")[0];';
    print '</script>';
}

?>
