This page template located at app/presenters/templates/Homepage/default.latte

{block content}
    <div id="banner">
        <h1 n:block=title>{$titleTranslation}</h1>
    </div>

    <div id="content">


        <h2></h2>

        <section id="template">
            <h2>This page template located at <span>{strstr($this->getName(), app)}</span></h2>

            <pre><code class="jush">{file_get_contents($this->getName())|replacere:'#[\w+/]{60,}#':'…'}</code></pre>
        </section>

        <section id="layout">
            <h2>Layout template located at <span>{strstr($this->getParentName(), app)}</span></h2>

            <pre><code class="jush">{file_get_contents($this->getParentName())}</code></pre>
        </section>

        <section id="presenter">
            <h2>Current presenter located at <span>{strstr($presenter->getReflection()->getFileName(), app)}</span></h2>

            <pre><code class="jush-php">{file_get_contents($presenter->getReflection()->getFileName())}</code></pre>
        </section>
    </div>
{/block}


{block head}
    <style>
        html {
            overflow-y: scroll;
        }

        body {
            font: 14px/1.65 Verdana, "Geneva CE", lucida, sans-serif;
            background: #3484d2;
            color: #333;
            margin: 38px auto;
            max-width: 940px;
            min-width: 420px;
        }

        h1, h2 {
            font: normal 150%/1.3 Georgia, "New York CE", utopia, serif;
            color: #1e5eb6;
            -webkit-text-stroke: 1px rgba(0, 0, 0, 0);
        }

        img {
            border: none;
        }

        a {
            color: #006aeb;
            padding: 3px 1px;
        }

        a:hover, a:active, a:focus {
            background-color: #006aeb;
            text-decoration: none;
            color: white;
        }

        #banner {
            border-radius: 12px 12px 0 0;
            background-image: url(data:image/png;base64,…);
        }

        #banner h1 {
            color: white;
            font-size: 50px;
            line-height: 121px;
            margin: 0;
            padding-left: 4%;
            text-shadow: 1px 1px 0 rgba(0, 0, 0, .9);
        }

        @media (max-width: 600px) {
            #banner h1 {
                background: none;
            }
        }

        #content {
            background: white;
            border: 1px solid #eff4f7;
            border-radius: 0 0 12px 12px;
            padding: 10px 4%;
            overflow: hidden;
        }

        #content > h2 {
            font-size: 130%;
            color: #666;
            clear: both;
            padding: 1.2em 0;
            margin: 0;
        }

        h2 span {
            color: #87A7D5;
        }

        h2 a {
            text-decoration: none;
            background: transparent;
        }

        .boxes {
            -webkit-justify-content: space-between;
            justify-content: space-between;
            display: -webkit-flex;
            display: flex;
            margin-right: -2em;
        }

        .boxes > div {
            background: #f0f0f0;
            border: 1px solid #e6e6e6;
            border-radius: 5px;
            -webkit-flex: 1;
            flex: 1;
            margin-right: 2em;
        }

        .boxes h2 {
            text-align: right;
            margin: 1em;
        }

        .boxes img {
            float: left;
        }

        .boxes p {
            clear: both;
            margin: 1em;
        }

        .boxes p a {
            color: #006aeb;
            background: #f7f7f7;
            padding: 1px 3px;
            border-radius: 3px;
            text-decoration: none;
            box-shadow: 0 2px 5px rgba(0, 0, 0, .10);
        }

        .boxes p a:hover, .boxes p a:active, .boxes p a:focus {
            color: white;
            background-color: #006aeb;
        }

        .boxes > div:nth-child(3n - 2) h2 {
            color: #00a6e5;
        }

        .boxes > div:nth-child(3n - 2) img {
            margin: -1em -1em 0 -1em;
        }

        .boxes > div:nth-child(3n - 1) h2 a {
            color: #db8e34;
            background: transparent;
        }

        .boxes > div:nth-child(3n) h2 a {
            color: #578404;
            background: transparent;
        }

        @media (max-width: 760px) {
            .boxes {
                -webkit-flex-direction: column;
                flex-direction: column;
            }

            .boxes > div {
                margin-bottom: 1em;
                flex-basis: auto;
            }

            .boxes h2 br {
                display: none;
            }
        }

        section {
            display: none;
        }

        pre {
            font-size: 12px;
            line-height: 1.4;
            padding: 10px;
            margin: 1.3em 0;
            overflow: auto;
            max-height: 500px;
            background: #F1F5FB;
            border-radius: 5px;
            box-shadow: 0 1px 1px rgba(0, 0, 0, .1);
        }

        .jush-com, .jush-php_doc {
            color: #929292;
        }

        .jush-tag, .jush-tag_js {
            color: #6A8527;
            font-weight: bold;
        }

        .jush-att {
            color: #8CA315
        }

        .jush-att_quo {
            color: #448CCB;
            font-weight: bold;
        }

        .jush-php_var {
            color: #d59401;
            font-weight: bold;
        }

        .jush-php_apo {
            color: green;
        }

        .jush-php_new {
            font-weight: bold;
        }

        .jush-php_fun {
            color: #254DB3;
        }

        .jush-js, .jush-css {
            color: #333333;
        }

        .jush-css_val {
            color: #448CCB;
        }

        .jush-clr {
            color: #007800;
        }

        .jush a {
            color: inherit;
            background: transparent;
        }

        .jush-latte {
            color: #D59401;
            font-weight: bold
        }
    </style>
{/block}

Layout template located at app/presenters/templates/@layout.latte

{**
 * @param string   $basePath web base path
 * @param array    $flashes  flash messages
 *}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">

    <title>{ifset title}{include title|stripHtml} | {/ifset}</title>
    <link rel="stylesheet" href="{$basePath}/css/style.css">
    <meta name="viewport" content="width=device-width">
    {block head}{/block}
    {ifset $code}
        <a n:href="Homepage:registration $code,'cz'"><img src="images/czech_republic_640.png" alt="Mountain View"
                                                          style="width:40px;height:20px;"></a>
        <a n:href="Homepage:registration $code,'ru'"><img src="images/russia_640.png" alt="Mountain View"
                                                          style="width:40px;height:20px;"></a>
        <a n:href="Homepage:registration $code,'en'"><img src="images/united_kingdom_640.png" alt="Mountain View"
                                                          style="width:40px;height:20px;"></a>
    {/ifset}
</head>

<body>
<div n:foreach="$flashes as $flash" n:class="flash, $flash->type">{$flash->message}</div>

{include content}

{block scripts}
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://nette.github.io/resources/js/netteForms.min.js"></script>
    <script>
        $('[name="homeAddress"]').bind("change keyup input click", function () {
            var sting = this.value.match(/[a-zA-Z0-9- .]/g);
            this.value = '';
            if (sting !== null) {
                for (var i = 0; i < sting.length; i++) {
                    this.value += sting[i];
                }
            }
        });
        $('[name="name"],[name="surname"]').bind("change keyup input click", function () {
            var sting = this.value.match(/[a-zA-Z ]/g);
            this.value = '';
            if (sting !== null) {
                for (var i = 0; i < sting.length; i++) {
                    this.value += sting[i];
                }
            }
        });
    </script>
    <script>
        $('#frm-registrationForm-dateOfBirth').change(function () {
            var date = new Date($('#frm-registrationForm-dateOfBirth').val());
            date.setDate(date.getDate() + 15 * 365);
            if ((new Date()).getTime() < date.getTime()) {
                $('#frm-registrationForm-dateOfBirth').val('')
            }
        });
    </script>

    <script src="{$basePath}/js/main.js"></script>
{/block}
</body>
</html>

Current presenter located at app/presenters/HomepagePresenter.php

<?php

namespace App\Presenters;

use Latte\Engine;
use Mpdf\Mpdf;
use Mpdf\MpdfException;
use Mpdf\Output\Destination;
use Nette;
use Nette\Application\Responses\JsonResponse;
use Nette\Application\UI;
use Nette\Application\UI\Form;
use Nette\Utils\DateTime;
use Tracy\Debugger;


class HomepagePresenter extends BasePresenter
{
    private $code;

    private $purposeOfTheStay = [
        null => '',
        0 => 'messages.typePurposeOfTheStay.0',
        1 => 'messages.typePurposeOfTheStay.1',
        2 => 'messages.typePurposeOfTheStay.2',
        3 => 'messages.typePurposeOfTheStay.3',
        4 => 'messages.typePurposeOfTheStay.4',
        5 => 'messages.typePurposeOfTheStay.5',
        6 => 'messages.typePurposeOfTheStay.6',
        7 => 'messages.typePurposeOfTheStay.7',
        10 => 'messages.typePurposeOfTheStay.10',
        11 => 'messages.typePurposeOfTheStay.11',
        12 => 'messages.typePurposeOfTheStay.12',
        13 => 'messages.typePurposeOfTheStay.13',
        27 => 'messages.typePurposeOfTheStay.27',
        93 => 'messages.typePurposeOfTheStay.93',
        99 => 'messages.typePurposeOfTheStay.99',
    ];


    private function checkCode($apCode)
    {
        $apCode = $this->refactorCode($apCode);
        if (array_key_exists($apCode, $this->apartmentsTranslator)) {
            return true;
        }
        $text = "The apartment code: '$apCode' was not found! used name: '$apCode'";
        //$this->flashMessage($text);
        return false;
    }

    private function refactorCode($apCode)
    {
        $apCode = str_replace(' ', '_', str_replace(['/', '-', '_'], '', trim(strtolower($apCode))));
        return $apCode;
    }

    private function getApartmentName($apCode)
    {
        return $this->checkCode($apCode) ? $this->apartmentsTranslator[$apCode]['name'] : $apCode;
    }

    public function renderDefault()
    {
        $this->getHttpResponse()->setHeader('Access-Control-Allow-Origin', $this->context->parameters['rapartmentUrl']);
        $this->getHttpResponse()->setHeader('Access-Control-Allow-Credentials', 'true');
        $this->template->titleTranslation = $this->translator->translate('messages.registration');
    }

    public function actionGetGuestsInformation()
    {
        $users = [];
        $result = $this->guestListManager->getInfo($this->request->getPost('code') ?: '');
        foreach ($result as $user) {
            $us = [];
            foreach ($user as $key => $item) {
                $us[$key] = $item;
            }
            $users[] = $us;
        }
        $this->getHttpResponse()->setHeader('Access-Control-Allow-Origin', $this->context->parameters['rapartmentUrl']);
        $this->getHttpResponse()->setHeader('Access-Control-Allow-Credentials', 'true');
        $this->sendResponse(new JsonResponse(json_encode($users)));
        exit();
    }

    public function actionSetGuestInfo()
    {
        try {
            $this->registrationFormSucceeded(null, $this->request->getPost());
        } catch (\Exception $e) {
            Debugger::log($e);
        }
    }


    public function renderRegistration($code, $lang = null)
    {
        $this->translator->setLocale($lang);
        $this->code = $code;
        $this->template->setTranslator($this->translator);
        $this->template->code = $code;
        $this->template->titleTranslation = $this->translator->translate('messages.registration');
        $this->template->apartmentTranslation = $this->translator->translate('messages.apartment');
        if (!$result = $this->guestListManager->getInfo($this->code ?: $this->request->getParameter('code'))) {
            $this->flashMessage($this->translator->translate('messages.error.codeDontExist'));
            $this->redirect('Homepage:');
        }
        $this->template->usersName = [];

        foreach ($result as $user) {
            if ($user['passport']) {
                $this->template->usersName[] = $user['surname'] . ' ' . $user['name'];
            }
            $this->template->apartment = $this->getApartmentName($user['apartment']);
        }
    }

    protected function createComponentRegistrationForm()
    {
        $code = $this->code ?: $this->request->getParameter('code');
        if (!$result = $this->guestListManager->getInfo($code)) {
            $this->error($this->translator->translate('messages.error.codeDontExist'), 404);
        }

        $name = $sName = null;
        $ifFirst = 1 === count($result);
        $result = array_shift($result);
        if ($ifFirst) {
            $name = $result->name;
            $sName = $result->surname;
        }
        $countryArray = [];
        foreach ($this->database->table('country')->select('*')->order('code')->fetchAssoc('code') as $item) {
            $countryArray[$item['code']] = 'messages.countries.' . $item['code'];
        }
        $form = new UI\Form;
        $required = 'messages.error.required.';
        $form->setTranslator($this->translator);

        $form->addText('checkInDate', 'checkInDate')
            ->setType('date')
            ->setAttribute('description', $this->translator->translate('messages.description.checkInDate'))
            ->setDefaultValue((new DateTime($result->checkInDate))->format('Y-m-d'))
            ->setRequired($required . 'checkInDate')
            ->addRule($form::PATTERN, '%label example: ' . (new DateTime())->format('Y-m-d'), '[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])')
            ->setAttribute('readonly');

        $form->addText('checkOutDate', 'checkOutDate')
            ->setType('date')
            ->setAttribute('description', $this->translator->translate('messages.description.checkOutDate'))
            ->setDefaultValue((new Nette\Utils\DateTime($result->checkOutDate))->format('Y-m-d'))
            ->addRule($form::PATTERN, '%label example: ' . (new DateTime())->format('Y-m-d'), '[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])')
            ->setRequired($required . 'checkOutDate')
            ->setAttribute('readonly');

        $form->addText('name', 'name')
            ->setAttribute('description', $this->translator->translate('messages.description.name'))
            ->setDefaultValue($name)
            ->setRequired($required . 'name');

        $form->addText('surname', 'surname')
            ->setDefaultValue($sName)
            ->setAttribute('description', $this->translator->translate('messages.description.surname'))
            ->setRequired($required . 'surname');

        $form->addText('dateOfBirth', 'dateOfBirth')
            ->setType('date')
            ->setAttribute('max', (new Nette\Utils\DateTime())->modify('-15 years')->format('Y-m-d'))
            ->setAttribute('description', $this->translator->translate('messages.description.dateOfBirth'))
            ->addRule($form::PATTERN, '%label example: ' . (new DateTime())->format('Y-m-d'), '[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])')
            ->setRequired($required . 'checkInDate');

        $form->addSelect('country', 'country', $countryArray)
            ->setAttribute('description', $this->translator->translate('messages.description.country'))
            ->setRequired($required . 'country');

        $form->addText('homeAddress', 'homeAddress')
            ->setAttribute('description', $this->translator->translate('messages.description.homeAddress'))
            ->setRequired($required . 'homeAddress')
            ->addRule(Form::MIN_LENGTH, 'messages.error.validate.homeAddressMinLength', 10);

        $form->addText('passport', 'passport')
            ->setAttribute('description', $this->translator->translate('messages.description.passport'))
            ->setRequired($required . 'passport');

        $form->addInteger('visa', 'visa')
            ->setAttribute('description', $this->translator->translate('messages.description.visa'));

        $form->addText('checkInTime', 'checkInTime')
            ->setType('time')
            ->setAttribute('description', $this->translator->translate('messages.description.checkInTime'))
            ->setDefaultValue($result->checkInTime)
            ->setRequired($required . 'checkInTime');

        $form->addRadioList('typeIn', 'messages.typeIn.title',
            [
                'car' => 'messages.typeIn.car',
                'train' => 'messages.typeIn.train',
                'plane' => 'messages.typeIn.plane',
                'bus' => 'messages.typeIn.bus',
            ]
        )
            ->setAttribute('description', $this->translator->translate('messages.description.typeIn'))
            ->setRequired($required . 'radio');

        $form->addSelect('purposeOfTheStay', 'messages.typePurposeOfTheStay.name', $this->purposeOfTheStay)
            ->setAttribute('description', $this->translator->translate('messages.description.purposeOfTheStay'))
            ->setRequired($required . 'purposeOfTheStay');

        $form->addCheckbox('check', 'check')->setRequired($required . 'check');
        $form->addCheckbox('check2', 'I agree to provide my personal information for the Czech Police foreign')
            ->setRequired($required . 'check');

        $form->addHidden('checkOutTime', $result->checkOutTime);
        $form->addHidden('apartment', $result->apartment);

        $form->addHidden('sumPeoples')->setDefaultValue($result->sumPeoples);
        $form->addHidden('code')->setDefaultValue($code);
        $form->addSubmit('submit', 'submit');
        $form->onSuccess[] = [$this, 'registrationFormSucceeded'];
        $form->onValidate[] = [$this, 'registrationFormValidator'];


        return $form;
    }

    public function registrationFormValidator($form, $values)
    {
        if ((new \DateTime($this->reformatDate($values['dateOfBirth']))) >= (new \DateTime())->modify('-15 years')) {
            $form->addError($this->translator->translate('messages.error.validate.youAreYoung'));
        }
    }

    public function registrationFormSucceeded($form, $values)
    {
        unset($values['check'], $values['check2']);
        foreach (['dateOfBirth', 'checkOutDate', 'checkInDate'] as $item) {
            $values[$item] = $this->reformatDate($values[$item]);
        }
        $values['passport'] = str_replace(' ', '', $values['passport']);
        $values['visa'] = str_replace(' ', '', $values['visa']);
        $this->guestListManager->deleteFirstCode($values['code']);
        if ($this->guestListManager->getInfo($values['code'], $values['name'], $values['surname'], $values['dateOfBirth'])) {
            $this->guestListManager->updateInfo($values, $values['code']);
        } else {
            $this->guestListManager->setInfo($values);
        }
        if ($this->guestListManager->isAllSet($values['code'])) {
            try {
                $this->finishing($values['code']);
            } catch (\Exception $e) {
                //$this->emailManager->sendMailError($e);
            }
        }
        if ($this->action === 'setGuestInfo') {
            return;
        }
        $this->flashMessage($this->translator->translate('messages.succeeded.guest', ['guest' => $values['surname'] . ' ' . $values['name']]));
        $this->redirect('Homepage:registration', $values['code']);
    }

    private function getIdubFileName($code)
    {
        return $this->apartmentsTranslator[$code]['code'] . '_' . (new \dateTime())->format('ymdhm');

    }

    /**
     * @param $code
     * @throws Nette\Application\AbortException
     */
    public function actionForce($code)
    {
        $this->getHttpResponse()->setHeader('Access-Control-Allow-Origin', $this->context->parameters['rapartmentUrl']);
        $this->getHttpResponse()->setHeader('Access-Control-Allow-Credentials', 'true');
        $this->finishing($code);
        $this->sendResponse(new Nette\Application\Responses\TextResponse('Ok'));

    }

    private function getHeadForIdub($code)
    {
        return $this->apartmentsTranslator[$this->refactorCode($code)]['header'] . '|' . (new \dateTime())->format('Y.m.d H:i:s') . '||';
    }

    private function setFile($user)
    {
        $linkToDir = ROOT_DIR . '/temp/files/police/' . $this->reformatDate($user['checkInDate']);
        $linkToFile = $linkToDir . '/' . $this->getIdubFileName($user->apartment) . '.unl';
        if (!file_exists($linkToDir)) {
            mkdir($linkToDir, 0777);
        }
        if (!file_exists($linkToFile)) {
            $this->setLineToFile($linkToFile, $this->getHeadForIdub($user->apartment));
        }
        $this->setLineToFile($linkToFile,
            'U|' .
            $this->reformatDate($user['checkInDate']) . '|' .
            $this->reformatDate($user['checkOutDate']) . '|' .
            $user['surname'] . '|' .
            $user['name'] . '||' .
            $this->reformatDate($user['dateOfBirth']) . '|||' .
            $user['country'] . '|' .
            $user['homeAddress'] . '|' .
            $user['passport'] . '|' .
            $user['visa'] . '|' .
            $user['purposeOfTheStay'] . '||'
        );
    }

    /**
     * @param $date
     * @return string
     */
    private function reformatDate($date)
    {
        $_d = $date;
        if (is_array($date) && key_exists('date', $date)) {
            $date = $date['date'];
        }
        if (!($date = strtotime($date))) {
            Debugger::log($_d, 'dateError');
            return (new \DateTime())->format('d.m.Y');
        }
        try {
            return (new \DateTime())->setTimestamp($date)->format('d.m.Y');
        } catch (\Exception $e) {
            return (new \DateTime())->format('d.m.Y');
        }
    }

    private function setFileForManager($user)
    {
        $linkToDir = ROOT_DIR . '/temp/files/export/' . (new \DateTime())->format('Y');
        if (!file_exists($linkToDir)) {
            mkdir($linkToDir, 0777);
        }
        $linkToFile = $linkToDir . '/' . $this->refactorCode($this->getApartmentName($user['apartment'])) . '.csv';
        if (!file_exists($linkToFile)) {
            $this->setLineToFile($linkToFile,
                'name|code|surname|visa|sumPeoples|dateOfBirth|homeAddress|checkInDate|checkInTime|checkOutDate|checkOutTime|apartment|country|typeIn|passport|purposeOfTheStay|sum days|sum pay');
        }
        $sumDays = (new \DateTime($user['checkInDate']))->diff(new \DateTime($user['checkOutDate']))->days;
        $this->setLineToFile($linkToFile,
            $user['name'] . '|' .
            $user['code'] . '|' .
            $user['surname'] . '|' .
            $user['visa'] . '|' .
            $user['sumPeoples'] . '|' .
            $user['dateOfBirth'] . '|' .
            $user['homeAddress'] . '|' .
            $user['checkInDate'] . '|' .
            $user['checkInTime'] . '|' .
            $user['checkOutDate'] . '|' .
            $user['checkOutTime'] . '|' .
            $user['apartment'] . '|' .
            $user['country'] . '|' .
            $user['typeIn'] . '|' .
            $user['passport'] . '|' .
            $user['purposeOfTheStay'] . '|' .
            $sumDays . '|' .
            $sumDays * 0.6
        );
    }

    private function createPdf($user)
    {

    }

    public function renderSendEmails($date = null)
    {
        $this->template->titleTranslation = 'emails';
        $date = $this->reformatDate($date);
        $linkToDir = ROOT_DIR . '/temp/files/police/' . $date;
        if (!file_exists($linkToDir)) {
            $this->flashMessage("reservation on $date don't find");
            return;
        }
        $files = scandir($linkToDir);
        unset($files[0], $files[1]);
        if (count($files) === 0) {
            $this->flashMessage('dir is empty');
        }
        foreach ($files as $file) {
            $this->emailManager->sendMailPolice($linkToDir . '/' . $file);
        }
    }

    /**
     * @param $code
     * @throws Nette\Application\AbortException
     */
    private function finishing($code)
    {
        $users = $this->guestListManager->getInfo($code);
        if (empty($users)) {
            $this->redirect('Homepage:');
        }
        $needSend = true;
        $linkToDir = ROOT_DIR . '/temp/files/pdf/';
        $uName = '';
        foreach ($users as $user) {
            if ($needSend) {
                try {
                    $ch = curl_init($this->context->parameters['rapartmentUrl'] . '/Api/setGuestInformation');
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
                        'code' => $user['code'],
                        'name' => $user['surname'] . ' ' . $user['name'],
                        'address' => $user['homeAddress'],
                        'arrivalType' => $user['typeIn'],
                        'arrivalDate' => $user['checkInDate'],
                        'arrivalTime' => $user['checkInTime'],
                        'transferInformation' => $user['typeIn'],
                        'nationality' => $user['country'],
                        'age' => (new \DateTime())->diff(new \DateTime($user['dateOfBirth']))->y,
                    ], '', '&'));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_exec($ch);
                    curl_close($ch);
                    $needSend = false;
                } catch (Nette\Neon\Exception $e) {
                    $this->flashMessage($e->getMessage());
                }
            }
            $this->setFile($user);
            $this->setFileForManager($user);
            $userData = [];
            foreach ($user as $key => $value) {
                $userData[$key] = $value;
            }
            $userData['apartment'] = $this->apartmentsTranslator[$userData['apartment']]['name'];
            $userData['_control'] = $userData['_presenter'] = $this->presenter;
            $userData['ifOnOpenTime'] = $this->ifAtOpenTime($user['checkInTime'], $user['checkInDate']);
            $uName = $uName ?: $user['surname'] . ' ' . $user['name'];
            $linkToDir = ROOT_DIR . "/temp/files/pdf/" . $userData['apartment'];
            //$this->emailManager->sendMailToUser($user['email'], $user['typeIn'], $userData);
        }

        try {
            if (!is_dir($linkToDir)) {
                mkdir($linkToDir, 0777);
            }
            $linkToDir = $linkToDir . "/$uName.pdf";
            $this->cretePdf($code)->Output($linkToDir, Destination::FILE);
            $this->emailManager->sendMailToManager($this->context->parameters['emailAddress'], ['users' => $users], $linkToDir);

        } catch (\Exception $e) {
            $this->emailManager->sendMailError($e->getMessage());
            $this->emailManager->sendMailToManager($this->context->parameters['emailAddress'], ['users' => $users]);
        }


        $this->guestListManager->deleteCode($code);
        $this->flashMessage('messages.succeeded.AllPeopleAreRegistered');
        $this->redirect('Homepage:');
    }

    private function setLineToFile($file, $line)
    {
        file_put_contents($file, $line . "\r\n", FILE_APPEND);
    }

    public function renderUpLoad()
    {
        $this->template->titleTranslation = $this->translator->translate('messages.upLoad');
        $this->template->setTranslator($this->translator);
    }

    protected function createComponentUploadForm()
    {
        $form = new UI\Form;
        $form->addMultiUpload("file", "file");
        $form->addSubmit('submit', 'submit');
        $form->setTranslator($this->translator);
        $form->onValidate[] = [$this, 'validateUploadFile'];
        $form->onSuccess[] = [$this, 'saveUploadFile'];
        return $form;
    }

    public function validateUploadFile(Form $form)
    {
        $values = $form->values;
        $uploadDir = ROOT_DIR . '/temp/files';
        foreach ($values['file'] as $file) {
            $fileName = $file->name;
            if (explode(".", $fileName)[1] !== 'csv') {
                $form->addError($this->translator->translate('messages.error.validate.fileFormat'));
                return;
            }
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777);
            }
            $file->move($uploadDir . '/../' . $fileName);
        }
    }

    public function saveUploadFile(Form $form)
    {
        $values = $form->values;
        $uploadDir = ROOT_DIR . '/temp/files';
        /** @var Nette\Http\FileUpload $file */
        foreach ($values['file'] as $file) {
            $fileName = $file->name;
            $handle = fopen($uploadDir . '/../' . $fileName, "r");
            if ($handle) {
                try {
                    $header = explode(';', iconv('windows-1251', 'utf-8', fgets($handle)));
                    $indexCode = array_search('Код', $header);
                    $indexCostumer = array_search('Заказчик', $header);
                    $indexApartment = array_search('Категория', $header);
                    $indexCheckIn = array_search('Заезд', $header);
                    $indexCheckOut = array_search('Выезд', $header);
                    $indexSumPeoples = array_search('Взр/Дети', $header);
                    if (false === $indexCode) {
                        $this->flashMessage('"Код" not found!');
                        var_dump($header);
                        break;
                    }
                    if (false === $indexCostumer) {
                        $this->flashMessage('"Заказчик" not found!');
                        var_dump($header);
                        break;
                    }
                    if (false === $indexApartment) {
                        $this->flashMessage('"Категория" not found!');
                        var_dump($header);
                        break;
                    }
                    if (false === $indexCheckIn) {
                        $this->flashMessage('"Заезд" not found!');
                        var_dump($header);
                        break;
                    }
                    if (false === $indexCheckOut) {
                        $this->flashMessage('"Выезд" not found!');
                        var_dump($header);
                        break;
                    }
                    if (false === $indexSumPeoples) {
                        $this->flashMessage('"Взр/Дети" not found!');
                        var_dump($header);
                        break;
                    }
                } catch (Nette\Neon\Exception $e) {
                    $this->flashMessage($e);
                    break;
                }
                while (1 < count($buffer = explode(';', iconv('windows-1251', 'utf-8', fgets($handle))))) {
                    if ($this->guestListManager->getInfo($buffer[$indexCode])) {
                        $this->flashMessage('Code ' . $buffer[$indexCode] . ' already exists!');
                        continue;
                    }
                    if (!$this->checkCode($buffer[$indexApartment])) {
                        $this->flashMessage('Apartment with name ' . $buffer[$indexApartment] . ' don\'t exists!');
                        continue;
                    }
                    $array = [
                        'code' => $buffer[$indexCode],
                        'surname' => explode(' ', $buffer[$indexCostumer])[0],
                        'name' => key_exists(1, $surName = explode(' ', $buffer[$indexCostumer])) ? $surName[1] : '',
                        'apartment' => $this->refactorCode($buffer[$indexApartment]),
                        'checkInDate' => $this->reformatDate(explode(' ', $buffer[$indexCheckIn])[0]),
                        'checkInTime' => key_exists(1, $arrivalTime = explode(' ', $buffer[$indexCheckIn])) ? $arrivalTime[1] : '',
                        'checkOutDate' => $this->reformatDate(explode(' ', $buffer[$indexCheckOut])[0]),
                        'checkOutTime' => key_exists(1, $checkOutTime = explode(' ', $buffer[$indexCheckOut])) ? $checkOutTime[1] : '',
                        'sumPeoples' => array_sum(explode('/', $buffer[$indexSumPeoples])),
                    ];
                    if (!$this->guestListManager->getInfo($array['code'])) {
                        $this->guestListManager->setInfo($array);
                    }
                }
                fclose($handle);
            }
            $file->move($uploadDir . '/' . $fileName);
            $this->flashMessage($this->translator->translate('messages.importWasFinished'));
        }
    }

    private function ifAtOpenTime($time, $date)
    {
        $time = (int)str_replace([':', '/', ' ', '-'], '', $time);
        switch (strftime('%u', strtotime($date))) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                $timeStart = 900;
                $timeEnd = 2200;
                break;
            case 6:
            case 7:
                $timeStart = 1100;
                $timeEnd = 1800;
                break;
        }
        return $time > $timeStart && $time < $timeEnd;

    }


    /**
     * @param $code
     * @throws Nette\Application\AbortException
     * @throws \Mpdf\MpdfException
     */
    public function renderPdf($code)
    {
        $this->cretePdf($code)->Output();
        die;
    }

    /**
     * @param $code
     * @return Mpdf
     * @throws Nette\Application\AbortException
     * @throws \Mpdf\MpdfException
     */
    private function cretePdf($code)
    {
        $users = $this->guestListManager->getInfo($code);
        if (empty($users)) {
            $this->flashMessage("code: '$code' was not found!");
            $this->redirect('Homepage:');
        }
        /*vytvoření objektu*/
        $mpdf = new mPDF();
        //exit;
        $template = (new Engine)->renderToString(APP_DIR . "/presenters/templates/pdf/guests.latte", ['users' => $users, 'translate' => $this->translator, 'getApartmentAddress' => function ($name) {
            $header = $this->database->table('idubs')->select('header')->where(['id' => $name])->fetch();
            if (!$header) {
                return $name;
            }

            //Balbinova 223/5, 12000, Praha, Vinohrady
            //A|2|100103628264|USMAO|Ruterra Apartment Cimburkova 332/33|734284209|Praha|Praha|Zizkov|Cimburkova|332|33|13000
            $header = explode('|', $header->header);
            $address = $header[9] . ' ' . $header[10] . '/' . $header[11] . ' ' . $header[12] . ', ' . $header[6] . ', ' . $header[8];

            return $address;
        }]);
        /*Přidání HTML*/
        $mpdf->WriteHTML($template);
        return $mpdf;

    }

}