<?php declare(strict_types=1);

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

// needs globals $qrbApi, $qrbXl

// included by index.php

// Form and POST handler for 'deleteInputData'.
//
?>
            <form action="#upload-deleteAll" method="post">
              <div class="highlight">
                <div class="row g-1">
                    <h3 id="upload-deleteAll">
<?php
print $qrbApi->xl('upload.deleteAll.title'); 
?>
                    </h3>
                    <p>
<?php
print $qrbApi->xl('upload.deleteAll.hint'); 
?>
                    </p>
                    <button type="submit" name="deleteInputData" class="btn btn-danger">
<?php
print $qrbApi->xl('upload.deleteAll.submit'); 
?>
                    </button>
                </div>
              </div>

<?php
if (array_key_exists('deleteInputData', $_POST)) { ?>
              <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 (deleteInputData())              // prints errors
    {
        print $qrbApi->xl('upload.deleteAll.success');
    }
    else
    {
        print "<br />";
        print "<strong>";
        print $qrbApi->xl('upload.deleteAll.failed');
        print "</strong>";
    }
?>
                </p>
              </div>
<?php
} 
?>
            </form>

<?php
// Deletes input data of current profile.
// Returns true if delete done (or there was nothing to delete), false if error.
function deleteInputData() : bool
{
    global $qrbApi;
    global $qrbXl;
    $qrbApi->writeLog("delete started");
    
    try
    {
        return $qrbApi->deleteInputData();
    }
    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}");
        return false;
    }
    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}");
        return false;
    }
    finally
    {
        $qrbApi->writeLog("delete finished");
    }
}

?>
