<?php

namespace app\controllers;

use Yii;
use app\models\RegistrationForm;
use yii\filters\AccessControl;
use app\models\Messages;
use dektrium\user\controllers\RegistrationController as BaseRegistrationController;
use app\models\Files;
use yii\web\UploadedFile;

class RegistrationController extends BaseRegistrationController
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    ['allow' => true, 'actions' => ['register', 'connect'], 'roles' => ['?']],
                    ['allow' => true, 'actions' => ['confirm', 'resend'], 'roles' => ['@']],
                ],
            ],
        ];
    }

    public function actionRegister()
    {
        $model = Yii::createObject(RegistrationForm::class);

        $this->performAjaxValidation($model);

        $files = new Files();        

        if ( $model->load( Yii::$app->request->post() ) && false != ( $file = UploadedFile::getInstances( $files, 'file' ) ) ) {
            Yii::debug('Form data: ' . print_r(Yii::$app->request->post(), true), __METHOD__);
            if ($user = $model->register()) {
                // Создаем директорию для пользователя
                @mkdir(Yii::$app->params['uploadPath'] . $user->id, 0777, true);

                // Устанавливаем роль
                $authManager = Yii::$app->authManager;
                $role = $model->role == 1 ? 'org' : 'member';
                $userRole = $authManager->getRole($role);
                if ($userRole) {
                    $authManager->assign($userRole, $user->id);
                } else {
                    Yii::error("Role '$role' not found", __METHOD__);
                }

                $files->uploads = '../uploads/' . $user->id . '/';
                $files->user_id = $user->id;

                $fileName = $files->uploadFile();
                if ($fileName) {
                    $files->saveFile([
                        'name' => $fileName,
                        'path' => $files->uploads,
                        'user_id' => $user->id,
                        'auction_id'=>'null',
                        'lot_id'=>false,                        
                        'type' => 'register',
                    ]);
                }

                // $files = new Files();

                // $file = UploadedFile::getInstance($files, 'file');
                // if(isset($file)){
                //     $file->name = $files->transliteration($file->name);
                //     $path = Yii::$app->params['uploadPath'] . $file->name;
                //     $file->saveAs($path);

                //     $files->saveFile([
                //         'name'=>$file->name,
                //         'path'=>Yii::$app->params['uploadPath'],
                //         'user_id'=>$user->id,
                //         'auction_id'=>'null',
                //         'lot_id'=>'NULL',
                //         'type'  =>  'register'
                //     ]);
                // }                

                // Создаем сообщение
                Yii::createObject(Messages::class)->CreateMessage([
                    'user_id' => 23,
                    'notes' => Yii::t('app', 'User Registered ID: {name}', ['name' => $model->at_org]),
                ]);

                // Выход и редирект
                Yii::$app->user->logout();
                Yii::$app->session->setFlash('info', Yii::t('app', 'You must relogin for apply changes'));
                return $this->redirect('/user/login');
            } else {
                Yii::error('Registration failed', __METHOD__);
            }
        }

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

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
            ],
        ];
    }
}