<?php

namespace app\controllers;

use app\models\Profile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use Yii;
use yii\web\HttpException;

use dektrium\user\controllers\SettingsController as BaseSettingsController;
use yii\web\UploadedFile;

class SettingsController extends BaseSettingsController
{
    public function init()
    {
        if (@!Yii::$app->user->identity->confirmed_at && (@Yii::$app->user->identity->role == 1)) {
            return $this->redirect('/user/login');
        }
        Yii::$app->session->set('user.flags', Yii::$app->user->identity->id);
        $this->layout = '@app/views/layouts/backend/user';
        parent::init();
    }

    public function behaviors()
    {
        return array_merge(parent::behaviors(),
            [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'disconnect' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['account', 'confirm', 'networks', 'disconnect', 'profile', 'profile-settings'],
                        'roles' => ['@'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['bills-template', 'download-template'],
                        'roles' => ['admin'],
                    ],
                ],
            ],
        ]) ;

        // return [
        //     'verbs' => [
        //         'class' => VerbFilter::className(),
        //         'actions' => [
        //             'disconnect' => ['post'],
        //         ],
        //     ],
        //     'access' => [
        //         'class' => AccessControl::className(),
        //         'rules' => [
        //             [
        //                 'allow' => true,
        //                 'actions' => ['account', 'confirm', 'networks', 'disconnect', 'profile', 'profile-settings'],
        //                 'roles' => ['@'],
        //             ],
        //             [
        //                 'allow' => true,
        //                 'actions' => ['bills-template', 'download-template'],
        //                 'roles' => ['admin'],
        //             ],
        //         ],
        //     ],
        // ];
    }

    public function actionProfile()
    {
        $model = Yii::$app->user->identity->profile;

        $this->performAjaxValidation($model);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->getSession()->setFlash('success', Yii::t('user', 'Your profile has been updated'));

            return $this->refresh();
        }

        return $this->render('profile', [
            'model' => $model,
        ]);
    }

    public function actionProfileSettings()
    {
        $model = \app\models\Profile::findOne(['user_id' => Yii::$app->user->id]);

        if (!$model) {
            throw new \yii\web\NotFoundHttpException('Профиль не найден');
        }

        $this->performAjaxValidation($model);

        if ($model->load(Yii::$app->request->post())) {

            Yii::debug($model->attributes, 'profile.save'); // логируем то, что пришло

            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Профиль обновлён');
                return $this->refresh();
            } else {
                Yii::error($model->errors, 'profile.errors');
                Yii::$app->session->setFlash('danger', 'Ошибка при сохранении');
            }
        }

        return $this->render('profile-settings', [
            'model' => $model,
        ]);
    }

    public function actionBillsTemplate()
    {
        if (false != ($file = UploadedFile::getInstanceByName('billTemplate'))) {
            if ($file->extension !== 'docx') {
                Yii::$app->session->setFlash('danger', Yii::t('app', 'Можна завантажити тільки docx'));
            } else {
                $path = dirname(__DIR__) . '/web/bill-template.docx';
                if ($file->saveAs($path)) {
                    Yii::$app->session->setFlash('success', Yii::t('app', 'Шаблон успішно завантажено'));
                    return $this->refresh();
                }
                else{
                    Yii::$app->session->setFlash('warning', Yii::t('app', 'Не вдалося завантажити файл шаблону'));
                }
            }
        }
        return $this->render('bills-template');
    }

    public function actionDownloadTemplate() {

        $filename = templater()->process([
            'billID' => '1',
            'auctionID' => '123123123',
            'date' => date('d-m-Y'),
            'inn' => '09876543210',
            'zkpo' => '000111222',
            'uAddress' => 'Ukraine, Kiev',
            'bank' => 'Ukraine, Kiev, Privat Bank',
            'payAccount' => '01234567890',
            'phone' => '+38-050-777-1255',
            'fax' => '044-586-56-87',
            'firmaFull' => 'Тестове ТОВ',
            'billType' => 'Гарантійний внесок',
            'amountString' => num2str(100.34),
            'amountVat' => 100.34,
            'amount' => 100.34,
            'vat' => 'без ПДВ',
        ]);
        return Yii::$app->response->sendFile($filename);
    }

}