<?php
    namespace frontend\controllers;
    
    use common\models\User;
    use frontend\models\CreativeRole;
    use frontend\models\IntellectualProperty;
    use frontend\models\Report;
    use frontend\models\UserData;
    use frontend\models\UserPassport;
    use yii\filters\AccessControl;
    use yii\filters\VerbFilter;
    use yii\helpers\VarDumper;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    
    /**
     * Cabinet controller
     */
    class CabinetController extends Controller
    {
        
        public $layout = 'cabinet';
        
        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                'verbs'  => [
                    'class'   => VerbFilter::className(),
                    'actions' => [
                        'personal' => [ 'post' ],
                        'passport' => [ 'post' ],
                    ],
                ],
                'access' => [
                    'class' => AccessControl::className(),
                    'rules' => [
                        [
                            'allow' => true,
                            'roles' => [ '@' ],
                        ],
                    ],
                ],
            ];
        }
        
        /**
         * Displays index page.
         *
         * @return mixed
         */
        public function actionIndex()
        {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if (!$userData = $user->userData) {
                $userData = new UserData();
            }
            if (!$userPassport = $user->userPassport) {
                $userPassport = new UserPassport();
            }
            
            $tableQuery = IntellectualProperty::find();
            if (!$user->isAdmin()) {
                $tableQuery->joinWith('creativeRoles')
                           ->where([ 'intellectual_property.user_id' => $user->id ])
                           ->orWhere([ 'creative_role.user_id' => $user->id ]);
            }
            $table = $tableQuery->all();
            
            return $this->render(
                'index',
                [
                    'userData'     => $userData,
                    'userPassport' => $userPassport,
                    'table'        => $table,
                ]
            );
        }
        
        public function actionSales($id = null)
        {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            $newRecord = false;
            if ($id) {
                $propertyQuery = IntellectualProperty::find();
                if (!$user->isAdmin()) {
                    $propertyQuery->joinWith('creativeRoles')
                                  ->where([ 'intellectual_property.user_id' => $user->id ])
                                  ->orWhere([ 'creative_role.user_id' => $user->id ]);
                }
                $propertyQuery->andWhere([ 'intellectual_property.id' => $id ]);
                $property = $propertyQuery->one();
                if (empty( $property )) {
                    throw new NotFoundHttpException();
                }
            } else {
                $property = new IntellectualProperty(
                    [
                        'user_id' => \Yii::$app->user->id,
                    ]
                );
                $newRecord = true;
            }
            if ($property->load(\Yii::$app->request->post()) && $property->save()) {
                if ($newRecord) {
                    return $this->redirect(
                        [
                            'cabinet/sales',
                            'id' => $property->id,
                        ]
                    );
                } else {
                    $response = \Yii::$app->response;
                    $response->format = $response::FORMAT_JSON;
                    return [
                        'success' => true,
                        'message' => 'Данные успешно сохранены',
                    ];
                }
            }
            
            $table = CreativeRole::find()
                                 ->where(
                                     [
                                         'intellectual_property_id' => $id,
                                     ]
                                 )
                                 ->all();
            
            return $this->render(
                'sales',
                [
                    'property' => $property,
                    'table'    => $table,
                ]
            );
        }
        
        public function actionList()
        {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            $tableQuery = IntellectualProperty::find();
            if (!$user->isAdmin()) {
                $tableQuery->where(
                    [
                        'user_id' => \Yii::$app->user->id,
                    ]
                );
            }
            $table = $tableQuery->all();
            return $this->render(
                'list',
                [
                    'table' => $table,
                ]
            );
        }
        
        public function actionArrivals()
        {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if ($user->isAdmin()) {
                $reports = Report::find()
                                 ->with('intellectualProperty')
                                 ->all();
            } else {
                $reports = Report::find()
                                 ->joinWith('intellectualProperty.creativeRoles')
                                 ->where([ 'creative_role.user_id' => $user->id ])
                                 ->all();
            }
            return $this->render(
                'arrivals',
                [
                    'reports' => $reports,
                ]
            );
        }
        
        public function actionNotifications()
        {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if ($user->isAdmin()) {
                $table = Report::find()
                               ->with('intellectualProperty')
                               ->all();
            } else {
                $table = Report::find()
                               ->joinWith('intellectualProperty.creativeRoles')
                               ->where([ 'creative_role.user_id' => $user->id ])
                               ->all();
            }
            return $this->render(
                'notifications',
                [
                    'table' => $table,
                ]
            );
        }
        
        public function actionUsers()
        {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if ($user->isAdmin()) {
                $reports = Report::find()
                                 ->with('intellectualProperty')
                                 ->all();
            } else {
                $reports = Report::find()
                                 ->innerJoinWith('intellectualProperty.creativeRole')
                                 ->all();
            }
            
            return $this->render(
                'users',
                [
                    'reports' => $reports,
                ]
            );
        }
        
        public function actionUsersAdd()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            /**
             * @var User $user
             */
            $report = new Report();
            if ($report->load($request->post()) && $report->save()) {
                return [
                    'success' => true,
                    'message' => 'Данные успешно сохранены',
                ];
            } else {
                return [
                    'error'   => true,
                    'message' => 'Ошибка сохранения данных',
                ];
            }
        }
        
        public function actionPersonal()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if (!$userData = $user->userData) {
                $userData = new UserData();
                $userData->user_id = $user->id;
            }
            if ($userData->load($request->post()) && $userData->save()) {
                return [
                    'success' => true,
                    'message' => 'Данные успешно сохранены',
                ];
            } else {
                return [
                    'error'   => true,
                    'message' => 'Ошибка сохранения данных',
                ];
            }
        }
        
        public function actionPassport()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if (!$userPassport = $user->userPassport) {
                $userPassport = new UserPassport();
                $userPassport->user_id = $user->id;
            }
            if ($userPassport->load($request->post()) && $userPassport->save()) {
                return [
                    'success' => true,
                    'message' => 'Данные успешно сохранены',
                ];
            } else {
                return [
                    'error'   => true,
                    'message' => 'Ошибка сохранения данных',
                ];
            }
        }
        
        public function actionAddIntProp()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            
            $intProperty = new IntellectualProperty();
            
            $intProperty->user_id = \Yii::$app->user->identity->id;
            
            if ($intProperty->load($request->post()) && $intProperty->save()) {
                return [
                    'success' => true,
                    'message' => 'Данные успешно сохранены',
                ];
            } else {
                return [
                    'error'   => true,
                    'message' => 'Ошибка сохранения данных',
                ];
            }
        }
        
        public function actionDeleteIntProperty()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            
            if (!empty( $request->post('id') )) {
                $role = IntellectualProperty::findOne($request->post('id'));
                if ($role->delete()) {
                    return [
                        'success' => true,
                        'message' => 'Данные успешно удалены',
                    ];
                } else {
                    return [
                        'error'   => true,
                        'message' => 'Ошибка удаления данных',
                    ];
                }
            } else {
                return [
                    'error'   => true,
                    'message' => 'Элемент не найден',
                ];
            }
        }
        
        public function actionAddRole()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            
            $role = new CreativeRole();
            
            if ($role->load($request->post()) && $role->save()) {
                return [
                    'success' => true,
                    'message' => 'Данные успешно сохранены',
                ];
            } else {
                return [
                    'error'   => true,
                    'message' => 'Ошибка сохранения данных',
                ];
            }
        }
        
        public function actionUpdateRole()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            
            $role = CreativeRole::findOne($request->get('id'));
            
            if ($role->load($request->post()) && $role->save()) {
                return [
                    'success' => true,
                    'message' => 'Данные успешно сохранены',
                ];
            } else {
                return [
                    'error'   => true,
                    'message' => 'Ошибка сохранения данных',
                ];
            }
        }
        
        public function actionGetRoleForm()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            
            $model = CreativeRole::findOne($request->post('id'));
            
            return [
                'answer' => $this->renderPartial('_update_form', [ 'model' => $model ]),
            ];
        }
        
        public function actionDeleteRole()
        {
            $request = \Yii::$app->request;
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            
            if (!empty( $request->post('id') )) {
                $role = CreativeRole::findOne($request->post('id'));
                if ($role->delete()) {
                    return [
                        'success' => true,
                        'message' => 'Данные успешно удалены',
                    ];
                } else {
                    return [
                        'error'   => true,
                        'message' => 'Ошибка удаления данных',
                    ];
                }
            } else {
                return [
                    'error'   => true,
                    'message' => 'Роль не найдена',
                ];
            }
        }
        
        public function findProperty($id)
        {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            $modelQuery = IntellectualProperty::find();
            if (!$user->isAdmin()) {
                $modelQuery->where(
                    [
                        'id'      => $id,
                        'user_id' => \Yii::$app->user->id,
                    ]
                );
            }
            $model = $modelQuery->one();
            if (empty( $model )) {
                throw new NotFoundHttpException();
            }
            return $model;
        }
    }
