<?php

declare(strict_types=1);

use yii;
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;

use app\models\Notification;
use app\models\Account;
use app\models\Document;
use app\models\Product;
use app\models\Settings;
use app\models\Supply;

use DateTime;
use DateTimeZone;

// Инициализация
$panel ?? $panel = 'profile_panel_input_accounts';
$panel_accounts ?? $panel_accounts = 'profile_panel_input_accounts_control';

// Инициализация часового пояса
preg_match_all('/UTC([\+\-0-9:]*)/', $account->zone ?? Settings::searchActive()['timezone_default'] ?? 'UTC+3', $timezone);
$timezone = $timezone[1][0];
?>

<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="p-4 rounded">
                <div id="profile_panel_panel" class="profile_panel">
                    <div class="profile_panel_menu mb-3">
                        <label class="btn button_white mb-0 mr-2" for="profile_panel_input_notifications" onclick="return page_profile_panel_choose('profile_panel_input_notifications');">Уведомления</label>
                        <label class="btn button_white mb-0 mr-2" for="profile_panel_input_accounts" onclick="return page_profile_panel_choose('profile_panel_input_accounts');">Аккаунты</label>
                        <label class="btn button_white mb-0 mr-2" for="profile_panel_input_products" onclick="return page_profile_panel_choose('profile_panel_input_products');">Товары</label>
                        <label class="btn button_white mb-0 mr-2" for="profile_panel_input_supplies" onclick="return page_profile_panel_choose('profile_panel_supplies_read');">Поставки</label>
                        <label class="btn button_white mb-0 mr-2" for="profile_panel_input_settings" onclick="return page_profile_panel_choose('profile_panel_input_settings');">Настройки</label>
                    </div>
                    <div class="profile_panel_content">
                        <input type="radio" id="profile_panel_input_notifications" name="main_panel" <?= $panel === 'profile_panel_input_notifications' ? 'checked' : null ?> />
                        <div class="col">
                            <h5>Отправка уведомления</h5>
                            <div class="dropdown-divider mb-3"></div>
                            <?php
                            $form = ActiveForm::begin([
                                'id' => 'form_profile_panel_notifications',
                                'action' => false,
                                'fieldConfig' => [
                                    'template' => '{label}{input}'
                                ],
                                'options' => [
                                    'onsubmit' => 'return false;'
                                ]
                            ]);

                            // Значения по умолчанию
                            $model_notifications ?? $model_notifications = new Notification;
                            $model_notifications->account ?? $model_notifications->account = null;
                            $model_notifications->text ?? $model_notifications->text = '';
                            ?>

                            <?= $form->errorSummary($model_notifications) ?>

                            <div class="row">
                                <?= $form->field($model_notifications, 'account', ['options' => ['class' => "mb-1 col-9"]])->input('text', ['placeholder' => yii::$app->user->identity->_key]); ?>
                                <?= $form->field($model_notifications, 'type', ['options' => ['class' => "col pl-0"]])->dropDownList($model_notifications->typs); ?>
                            </div>
                            <small class="d-block mb-1"><b>Множественная отправка:</b> @all или перечислить через запятую</small>
                            <small class="d-block mb-3"><b>Тестирование:</b> @test или оставить поле пустым</small>

                            <?= $form->field($model_notifications, 'text', ['options' => ['class' => "mb-1"]])->textarea(["maxlength" => '300']); ?>

                            <p class="mb-3 text-right">
                                <span id="notification-text-current">0</span>
                                <span> / </span>
                                <span id="notification-text-maximum">300</span>
                            </p>

                            <?= Html::submitButton('Отправить', ['name' => 'submitNotification', 'onclick' => 'page_profile_panel_notification_create(this.parentElement);', 'id' => 'notification-button-send', 'class' => 'flex-grow-1 mr-2 btn button_white button_clean']) ?>
                            <?= Html::submitButton('Отправить как HTML', ['name' => 'submitNotification', 'onclick' => 'page_profile_panel_notification_create(this.parentElement, 1);', 'id' => 'notification-button-send-html', 'class' => 'flex-grow-1 mr-2 btn button_white button_clean']) ?>

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

                        <input type="radio" id="profile_panel_input_accounts" name="main_panel" <?= $panel === 'profile_panel_input_accounts' ? 'checked' : null ?> />
                        <div class="profile_panel_input_accounts_menu mb-4">
                            <label class="mb-0 mr-2 px-2 py-1 btn button_white_small" for="profile_panel_input_accounts_control" onclick="return page_profile_panel_choose('profile_panel_input_accounts_control');">Пользователи</label>
                            <label class="mb-0 mr-2 px-2 py-1 btn button_white_small" for="profile_panel_input_accounts_suppliers" onclick="return page_profile_panel_choose('profile_panel_input_accounts_suppliers');">Поставщики</label>
                        </div>
                        <input type="radio" id="profile_panel_input_accounts_control" name="main_panel_accounts" <?= $panel_accounts === 'profile_panel_input_accounts_control' ? 'checked' : null ?> />
                        <div class="col">
                            <h5>Список пользователей</h5>
                            <div class="dropdown-divider mb-4"></div>
                            <div id="profile_panel_input_accounts_list" class="px-3"></div>
                        </div>

                        <input type="radio" id="profile_panel_input_accounts_suppliers" name="main_panel_accounts" <?= $panel_accounts === 'profile_panel_input_accounts_suppliers' ? 'checked' : null ?> />
                        <div class="col">
                            <h5>Заявки на регистрацию поставщиков</h5>
                            <div class="dropdown-divider mb-4"></div>
                            <div id="profile_panel_input_suppliers_requests"></div>
                        </div>

                        <input type="radio" id="profile_panel_input_products" name="main_panel" <?= $panel === 'profile_panel_input_products' ? 'checked' : null ?> />
                        <div class="col">
                            <h5>Список товаров</h5>
                            <div class="orders_panel_menu ml-auto text-right">
                                <a class="btn btn-sm button_white button_clean font-weight-bold mb-0 mr-2" type="button" onclick="return profile_panel_products_read('@last', 'all', '@last', '@last', 1, true);">Все</a>
                                <a class="btn btn-sm button_white button_clean font-weight-bold mb-0 mr-2" type="button" onclick="return profile_panel_products_read('@last', 'active', '@last', '@last', 1, true);">Активные</a>
                                <a class="btn btn-sm button_white button_clean font-weight-bold mb-0" type="button" onclick="return profile_panel_products_read('@last', 'inactive', '@last', '@last', 1, true);">Неактивные</a>
                            </div>
                            <div class="dropdown-divider mb-4"></div>
                            <div id="profile_panel_input_products_wrap"></div>
                        </div>

                        <input type="radio" id="profile_panel_input_supplies" name="main_panel" <?= $panel === 'profile_panel_input_supplies' ? 'checked' : null ?> />
                        <div class="col">
                            <h5>Список поставок</h5>
                            <div class="dropdown-divider mb-4"></div>
                            <div id="profile_panel_input_supplies_wrap"></div>
                        </div>

                        <input type="radio" id="profile_panel_input_settings" name="main_panel" <?= $panel === 'profile_panel_input_settings' ? 'checked' : null ?> />
                        <div class="col">
                            <?php
                            $form = ActiveForm::begin([
                                'id' => 'form_profile_panel_settings_addition_global',
                                'action' => false,
                                'fieldConfig' => [
                                    'template' => '{label}{input}',
                                ],
                                'options' => [
                                    'onsubmit' => 'return false;',
                                    'class' => 'mb-4'
                                ]
                            ]);
                            ?>

                            <?= $form->errorSummary($model_settings, ['header' => 'Получены ошибки:']) ?>

                            <?= $form->field($model_settings, 'addition_global', ['options' => ['class' => "mb-1"]])->textInput(['value' => $model_settings['addition_global'], 'onChange' => 'page_profile_panel_settings(this.parentElement.parentElement, \'profile_panel_input_settings\')']); ?>
                            <small class="d-block mb-1">Коэффициент умножаемый на цену каждого товара (доставка считается отдельно)</small>

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

                            <?php
                            $form = ActiveForm::begin([
                                'id' => 'form_profile_panel_settings_delivery_addition_global',
                                'action' => false,
                                'fieldConfig' => [
                                    'template' => '{label}{input}',
                                ],
                                'options' => [
                                    'onsubmit' => 'return false;',
                                    'class' => 'mb-4'
                                ]
                            ]);
                            ?>

                            <?= $form->field($model_settings, 'delivery_addition_global', ['options' => ['class' => "mb-1"]])->textInput(['value' => $model_settings['delivery_addition_global'], 'onChange' => 'page_profile_panel_settings(this.parentElement.parentElement, \'profile_panel_input_settings\')']); ?>
                            <small class="d-block mb-1">Время которое нужно добавить к доставке (дни)</small>

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

                            <?php
                            $form = ActiveForm::begin([
                                'id' => 'form_profile_panel_settings_search_period',
                                'action' => false,
                                'fieldConfig' => [
                                    'template' => '{label}{input}',
                                ],
                                'options' => [
                                    'onsubmit' => 'return false;',
                                    'class' => 'mb-4'
                                ]
                            ]);
                            ?>

                            <?= $form->errorSummary($model_settings, ['header' => 'Получены ошибки:']) ?>

                            <?= $form->field($model_settings, 'search_period', ['options' => ['class' => "mb-1"]])->textInput(['value' => $model_settings['search_period'], 'onChange' => 'page_profile_panel_settings(this.parentElement.parentElement, \'profile_panel_input_settings\')']); ?>
                            <small class="d-block mb-1">Время которое надо ждать для повторного поиска в секундах</small>

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

                            <?php
                            $form = ActiveForm::begin([
                                'id' => 'form_profile_panel_settings_search_connect_keep',
                                'action' => false,
                                'fieldConfig' => [
                                    'template' => '{label}{input}',
                                ],
                                'options' => [
                                    'onsubmit' => 'return false;'
                                ]
                            ]);

                            $list = ['false' => 'Нет', 'true' => 'Да'];

                            if (isset($model_settings->search_connect_keep)) {
                                // Найден ранее записанный параметр

                                if (isset($list[$model_settings->search_connect_keep])) {
                                    // Совпадение параметра с параметрами списка найдено

                                    // Буфер для сохранения параметра
                                    $buffer = $list[$model_settings->search_connect_keep];

                                    // Удаление параметра
                                    unset($list[$model_settings->search_connect_keep]);

                                    // Сохранение параметра в начале массива
                                    $list = array_merge([$model_settings->search_connect_keep => $buffer], $list);
                                } else {
                                    // Совпадение параметра с параметрами списка не найдено

                                    // Сохранение параметра из данных аккаунта в начале массива
                                    $list = array_merge([$model_settings->search_connect_keep => $model_settings->search_connect_keep], $list);
                                }
                            }
                            ?>

                            <?= $form->field($model_settings, 'search_connect_keep', ['options' => ['class' => "mb-1"]])->dropDownList($list, ['onChange' => 'page_profile_panel_settings(this.parentElement.parentElement, \'profile_panel_input_settings\')']); ?>
                            <small class="d-block mb-1">Удерживать открытое соединение до истечения срока блокировки поиска?</small>
                            <small class="d-block mb-1">При малой задержке позволяет снизить время загрузки страницы, но при большой будет казаться, что сайт завис</small>

                            <?php ActiveForm::end(); ?>
                        </div>
                    </div>
                </div>
            </div>
        </article>
    </div>
</div>

<script src="/js/profile.js" defer></script>
<script src="/js/product.js" defer></script>
<script src="/js/product_panel.js" defer></script>
<script src="/js/profile_panel.js" defer></script>
<script src="/js/textarea.js" defer></script>
<script>
    document.addEventListener('profile.loaded', function(e) {
        // Загружена программа для работы с профилем
    });

    document.addEventListener('profile_panel.loaded', function(e) {
        // Загружена программа для работы с панелью управления

        // Инициализация активной вкладки
        page_profile_panel_choose('<?= $panel ?? '' ?>');
    });

    document.addEventListener('textarea.loaded', function(e) {
        // Загружена программа для работы с блоками текста

        // Инициализация панели для ввода текста (тест уведомлений для администратора)
        initTextarea(
            '#notification-text',
            '#notification-text-current',
            '#notification-text-maximum',
            function() {
                let send = document.getElementById('notification-button-send');
                let send_html = document.getElementById('notification-button-send-html');

                send.removeAttribute('onchange');
                send_html.removeAttribute('onchange');

                send.disabled = true;
                send_html.disabled = true;
            },
            function() {
                let send = document.getElementById('notification-button-send');
                let send_html = document.getElementById('notification-button-send-html');

                send.setAttribute('onchange', 'page_profile_panel_notification_create(this.parentElement);');
                send_html.setAttribute('onchange', 'page_profile_panel_notification_create(this.parentElement, 1);');

                send.disabled = false;
                send_html.disabled = false;
            });
    });
</script>
