<?php

$config = [
    'id' => 'skillparts',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'defaultRoute' => 'main',
    'aliases' => [
        '@vendor'       => dirname(__DIR__) . '/../../../vendor',
        '@bower'        => '@vendor/bower-asset',
        '@npm'          => '@vendor/npm-asset'
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '',
            'baseUrl' => ''
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass'     => 'app\models\Account',
            'loginUrl'          => ['/authentication'],
            // 'enableAutoLogin'     => true,
            'enableSession'     => true
        ],
        // 'authManager' => [
        //     'class' => 'mirzaev\yii2\arangodb\rbac\DbManager',
        // ],
        'session' => [
            'class' => 'mirzaev\yii2\arangodb\sessions\ArangoDbSession',
            'document' => 'session',
            'cookieParams' => [
                // 'lifetime' => 3600 * 24 * 30 * 12
                'lifetime' => 3600 * 24 * 3
            ],
            'writeCallback' => function($session): array {
                // Инициализация
                $data = [];

                yii::$app->request->userIP and $data['ip'] = yii::$app->request->userIP;
                Yii::$app->user->id and $data['account'] = Yii::$app->user->id;

                return $data ?? [];
            },
            'timeout' => 3600 * 24 * 3,
            'useStrictMode' => false,
            'useCookies' => true
        ],
        'errorHandler' => [
            'errorAction' => 'error',
        ],
        'mail_info' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.yandex.com',
                'username' => 'info@skillparts.ru',
                'password' => 'SkillParts_1337',
                'port' => '465',
                'encryption' => 'ssl',

            ],
        ],
        'mail_system' => [
            'class' => 'yii\swiftmailer\Mailer',
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.yandex.com',
                'username' => 'system@skillparts.ru',
                'password' => 'System01001010Null',
                'port' => '465',
                'encryption' => 'ssl',
            ],
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'arangodb' => require __DIR__ . '/db.php',
        'urlManager' => [
            'enablePrettyUrl'   => true,
            'showScriptName'    => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'main'
                ],
                'product/<catn:[^/]+>' => 'product/index',
                '<section:(product|cart)>/<catn:[^/]+>/<action:(read|write|edit|delete)>/<target:(title|catn|dscr|dmns|wght|image|cover|comm)>' => '<section>/<action>-<target>',
                'profile/geolocation/<action:(init|write)>' => 'profile/geolocation-<action>',
                'orders' => 'order/index',
                'orders/<type:[^/]+>' => 'order/index',
                'orders/<catn:[^/]+>/<action:(accept)>' => 'order/<action>',
                'orders/supply/<catn:[^/]+>/<action:(read|write|edit|delete)>' => 'order/supply-<action>',
                'orders/supply/<catn:[^/]+>/<action:(read|write|edit|delete)>/<target:(stts|cost|time|comm)>' => 'order/supply-<action>-<target>',
                'invoices/<order:[^/]+>' => 'invoice/index',
                'invoices/<order:[^/]+>/<action:(download)>' => 'invoice/<action>',
                'verify/send' => 'verify/send',
                'verify/<vrfy:[^/]+>' => 'verify/index'
            ],
        ],

    ],
    'modules' => [
        'exchange' => [
            'class' => 'carono\exchange1c\ExchangeModule',
            'exchangeDocuments' => true,
            'validateModelOnSave' => true,
            'groupClass' => 'app\models\SupplyGroup',
            'productClass' => 'app\models\Supply',
            'offerClass' => 'app\models\SupplyEdgeProduct',
            'partnerClass' => 'app\models\Account',
            'documentClass' => 'app\models\Order',
            'auth' => function ($mail, $pswd) {
                // Необходимо уничтожить AccountForm
                // return (new \app\models\AccountForm())->authentication($mail, $pswd);

                if ($user = \app\models\Account::findByMail($mail)) {
                    if ($user->validatePassword($pswd)) {
                        return $user;
                    }
                }
                return false;
            }
        ]
    ],
    'params' => require __DIR__ . '/params.php',
    'on beforeAction' => function ($event) {
        if (yii::$app->user->isGuest) {
            // Гость
        } else {
            // Пользователь

            // Подтверждение почты
            if (yii::$app->user->identity->vrfy !== true) {
                // Почта не подтверждена

                if (!(str_starts_with(yii::$app->request->getPathInfo(), 'verify')
                    || match (yii::$app->request->getPathInfo()) {
                        'policy', 'notification', 'identification' => true,
                        default => false
                    })) {
                    // Фильтрация страниц

                    if (yii::$app->request->isPost) {
                        // POST-запрос

                        yii::$app->response->format = Response::FORMAT_JSON;

                        yii::$app->response->statusCode = 401;

                        return [
                            'main' => yii::$app->controller->renderPartial('/account/verify'),
                            'redirect' => '/registration',
                            '_csrf' => yii::$app->request->getCsrfToken()
                        ];
                    } else {
                        // Подразумевается как GET-запрос

                        // Переадресация на страницу указывающую на необходимость подтвердить почту
                        yii::$app->response->redirect('/verify')->send();
                    }
                }
            }

            // Согласие с офертой
            if (
                !(isset(yii::$app->session['offer_buyer_accepted'])
                    && yii::$app->session['offer_buyer_accepted'] === true)
                && (!isset(yii::$app->user->identity->acpt['buyer'])
                    || yii::$app->user->identity->acpt['buyer'] === false)
            ) {
                // Нет подтверждения офферты пользователя

                if (!(str_starts_with(yii::$app->request->getPathInfo(), 'verify')
                    || str_starts_with(yii::$app->request->getPathInfo(), 'offer')
                    || match (yii::$app->request->getPathInfo()) {
                        'notification', 'identification' => true,
                        default => false
                    })) {
                    // Фильтрация страниц

                    if (yii::$app->request->isPost) {
                        // POST-запрос

                        yii::$app->response->format = Response::FORMAT_JSON;

                        yii::$app->response->statusCode = 401;

                        return [
                            'main' => yii::$app->controller->renderPartial('/offer/index'),
                            'redirect' => '/registration',
                            '_csrf' => yii::$app->request->getCsrfToken()
                        ];
                    } else {
                        // Подразумевается как GET-запрос

                        // Переадресация на оферту
                        yii::$app->response->redirect('/offer')->send();
                    }
                }
            } else if (
                (isset(yii::$app->user->identity->agnt)
                    && yii::$app->user->identity->agnt === true)
                && !(isset(yii::$app->session['offer_supplier_accepted'])
                    && yii::$app->session['offer_supplier_accepted'] === true)
                && (!isset(yii::$app->user->identity->acpt['supplier'])
                    || yii::$app->user->identity->acpt['supplier'] === false)
            ) {
                // Нет подтверждения офферты поставщика

                if (!(str_starts_with(yii::$app->request->getPathInfo(), 'verify')
                    || str_starts_with(yii::$app->request->getPathInfo(), 'offer')
                    || match (yii::$app->request->getPathInfo()) {
                        'notification', 'identification' => true,
                        default => false
                    })) {
                    // Фильтрация страниц

                    if (yii::$app->request->isPost) {
                        // POST-запрос

                        yii::$app->response->format = Response::FORMAT_JSON;

                        yii::$app->response->statusCode = 401;

                        return [
                            'main' => $this->renderPartial('/offer/supplier'),
                            'redirect' => '/registration',
                            '_csrf' => yii::$app->request->getCsrfToken()
                        ];
                    } else {
                        // Подразумевается как GET-запрос

                        // Переадресация на оферту
                        yii::$app->response->redirect('/offer/suppliers')->send();
                    }
                }
            }
        }
    }
];

if (YII_ENV_DEV) {
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'panels' => [
            'ArangoDB' => [
                'class' => 'mirzaev\yii2\arangodb\panels\arangodb\ArangoDbPanel'
            ]
        ]
    ];
}

return $config;
