<?php

declare(strict_types=1);

use yii;
use yii\bootstrap\ActiveForm;

use app\models\Account;
use app\models\Document;
use app\models\Import;
use app\models\Settings;

use DateTime;
use DateTimeZone;

// Инициализация
$panel ?? $panel = 'profile_panel_supplies_input_import';

?>

<link href="/css/pages/profile.css" rel="stylesheet">

<div id="page_profile" class="container mb-auto">
    <div class="row h-100 py-3">
        <nav class="col-3">
            <?= $sidebar ?? yii::$app->controller->renderPartial('/profile/sidebar') ?>
        </nav>
        <article class="col-9">
            <div class="h-100 p-4 rounded">
                <h4 class="ml-4 mb-4"><i class="fas fa-truck my-auto mr-2"></i>Управление поставками</h4>
                <div id="profile_panel_supplies" class="profile_panel">
                    <div class="profile_panel_menu mb-3">
                        <label class="btn button_white mb-0 mr-2" for="profile_panel_supplies_input_settings">Настройки</label>
                        <label class="btn button_white mb-0 mr-2" for="profile_panel_supplies_input_import">Импорт</label>
                    </div>
                    <div class="profile_panel_content">

                        <input type="radio" id="profile_panel_supplies_input_settings" name="main_panel" <?= $panel === 'profile_panel_supplies_input_settings' ? 'checked' : null ?> />
                        <div class="col">
                            <p>В разработке</p>
                        </div>

                        <input type="radio" id="profile_panel_supplies_input_import" name="main_panel" <?= $panel === 'profile_panel_supplies_input_import' ? 'checked' : null ?> />
                        <div class="col">
                            <h5>Импорт из Excel-документа</h5>
                            <div class="dropdown-divider mb-4"></div>

                            <?php if (Account::isMinimalAuthorized()) : ?>
                                <?php
                                $form = ActiveForm::begin([
                                    'id' => 'form_product_import_excel',
                                    'action' => false,
                                    'fieldConfig' => [
                                        'template' => '{label}{input}',
                                        'options' => ['class' => '']
                                    ],
                                    'options' => [
                                        'class' => 'px-3 mb-3',
                                        'onsubmit' => 'return false;'
                                    ]
                                ]);
                                ?>
                                <?= $form->field($supply, 'account', ['options' => ['class' => "mb-4 col-4"]])->input('text', ['placeholder' => yii::$app->user->identity->_key]); ?>
                                <?php ActiveForm::end(); ?>
                                <?php
                                // Инициализация счетчика инстанций импорта
                                $amount = 0;

                                // Чтение истанций импорта
                                $imports = Import::read(limit: 100, order: ['desc']);

                                // Инициализация часового пояса
                                preg_match_all('/UTC([\+\-0-9:]*)/', $account->zone ?? Settings::searchActive()['timezone_default'] ?? 'UTC+3', $timezone);
                                $timezone = $timezone[1][0];
                                ?>
                                <?php foreach ($imports as $import) : ?>
                                    <?php
                                    foreach ($import->jrnl as $jrnl) {
                                        // Перебор записей в журнале

                                        if ($jrnl['action'] === 'create') {
                                            // Найдена дата создания

                                            // Инициализация даты
                                            $create = (new DateTime())->setTimestamp($jrnl['date'])->setTimezone(new DateTimeZone($timezone))->format('H:i d.m.Y') ?? 'Неизвестно';

                                            break;
                                        }
                                    }

                                    foreach ($import->jrnl as $jrnl) {
                                        // Перебор записей в журнале

                                        if ($jrnl['action'] === 'connect_with_account') {
                                            // Найдена дата создания

                                            // Инициализация даты
                                            $account = $jrnl['data']['target'];

                                            break;
                                        }
                                    }
                                    ?>

                                    <div class="mb-3 row">
                                        <div class="col-auto"><?= ++$amount ?>.</div>
                                        <div class="col">
                                            <?= $import->name ?? 'Без названия' ?>
                                        </div>
                                        <div class="col-3 px-0 text-right">
                                            <?= $create ?? 'Неизвестно' ?>
                                        </div>
                                        <a class="pr-0 my-auto col-auto fas fa-user text-dark" href="<?= $date_connect_with_account ?? 'Неизвестно' ?>"></a>
                                        <a class="pr-0 my-auto col-auto fas fa-file-download text-dark" type="button" onclick="page_profile_supplies_download()"></a>
                                        <a class="my-auto col-auto fas fa-trash-alt text-dark" type="button" onclick="page_profile_supplies_delete()"></a>
                                    </div>

                                    <? if ($amount < count($imports)) : ?>
                                        <div class="dropdown-divider mb-3"></div>
                                    <?php endif ?>
                                <?php endforeach ?>
                            <?php else : ?>
                                <?php
                                $form = ActiveForm::begin([
                                    'id' => 'form_product_import_excel',
                                    'action' => false,
                                    'fieldConfig' => [
                                        'template' => '{label}{input}',
                                        'options' => ['class' => '']
                                    ],
                                    'options' => [
                                        'class' => 'px-3 mb-3',
                                        'onsubmit' => 'return false;'
                                    ]
                                ]);
                                ?>
                                <?php if ($import_1 = Import::searchByPosition(1)) : ?>
                                    <div class="mb-3 row">
                                        <div class="col-auto">1.</div>
                                        <div class="col">
                                            <?= $import_1[0]->name ?? 'Без названия' ?>
                                        </div>
                                        <a class="pr-0 my-auto col-auto fas fa-file-download text-dark" type="button" aria-hidden="true" onclick="page_profile_supplies_download()"></a>
                                        <a class="my-auto col-auto fas fa-trash-alt text-dark" type="button" aria-hidden="true" onclick="page_profile_supplies_delete()"></a>
                                    </div>
                                <?php else : ?>
                                    <div class="mb-3 row">
                                        <div class="col-auto">1.</div>
                                        <div class="col">
                                            <?= $form->field($supply, 'file_excel_1', ['enableLabel' => false])->fileInput(['multiple' => true, 'onChange' => 'page_profile_supplies_import_excel(this.parentElement.parentElement.parentElement.parentElement, \'profile_panel_supplies_input_import\')']) ?>
                                        </div>
                                    </div>
                                <?php endif ?>

                                <div class="dropdown-divider mb-3"></div>

                                <?php if ($import_2 = Import::searchByPosition(2)) : ?>
                                    <div class="mb-3 row">
                                        <div class="col-auto">2.</div>
                                        <div class="col">
                                            <?= $import_2[0]->name ?? 'Без названия' ?>
                                        </div>
                                        <a class="pr-0 my-auto col-auto fas fa-file-download text-dark" type="button" aria-hidden="true" onclick="page_profile_supplies_download()"></a>
                                        <a class="my-auto col-auto fas fa-trash-alt text-dark" type="button" aria-hidden="true" onclick="page_profile_supplies_delete()"></a>
                                    </div>
                                <?php else : ?>
                                    <div class="mb-3 row">
                                        <div class="col-auto">2.</div>
                                        <div class="col">
                                            <?= $form->field($supply, 'file_excel_2', ['enableLabel' => false])->fileInput(['multiple' => true, 'onChange' => 'page_profile_supplies_import_excel(this.parentElement.parentElement.parentElement.parentElement, \'profile_panel_supplies_input_import\')']) ?>
                                        </div>
                                    </div>
                                <?php endif ?>

                                <div class="dropdown-divider mb-3"></div>

                                <?php if ($import_3 = Import::searchByPosition(3)) : ?>
                                    <div class="mb-3 row">
                                        <div class="col-auto">3.</div>
                                        <div class="col">
                                            <?= $import_3[0]->name ?? 'Без названия' ?>
                                        </div>
                                        <a class="pr-0 my-auto col-auto fas fa-file-download text-dark" type="button" aria-hidden="true" onclick="page_profile_supplies_download()"></a>
                                        <a class="my-auto col-auto fas fa-trash-alt text-dark" type="button" aria-hidden="true" onclick="page_profile_supplies_delete()"></a>
                                    </div>
                                <?php else : ?>
                                    <div class="row">
                                        <div class="col-auto">3.</div>
                                        <div class="col">
                                            <?= $form->field($supply, 'file_excel_3', ['enableLabel' => false])->fileInput(['multiple' => true, 'onChange' => 'page_profile_supplies_import_excel(this.parentElement.parentElement.parentElement.parentElement, \'profile_panel_supplies_input_import\')']) ?>
                                        </div>
                                    </div>
                                <?php endif ?>

                                <?= $form->errorSummary($supply, ['header' => 'В документе были допущены ошибки:' /*, 'footer' => 'Исправьте их и попробуйте снова'*/]); ?>

                                <?php ActiveForm::end(); ?>

                            <?php endif ?>

                        </div>
                    </div>
                </div>
        </article>
    </div>
</div>

<script src="/js/profile.js" defer></script>
<?php if (
    !yii::$app->user->isGuest
    && (yii::$app->user->identity->type === 'administrator'
        || yii::$app->user->identity->type === 'moderator')
) : ?>
    <script src="/js/profile_panel.js" defer></script>
<?php endif ?>
