<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\mongodb\Query;
use app\models\Form;
use app\models\Group;
use app\models\GroupSearch;
use app\components\Utilities;
use yii\web\NotFoundHttpException;

class GroupsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['Admin']
                    ],
                ],
                'denyCallback' => function(){
                    if(Yii::$app->user->isGuest){
                        return Yii::$app->response->redirect(['/users/login']);
                    }
                    return Yii::$app->response->redirect(Yii::$app->homeUrl);
                }
            ]
        ];
    }

    public function actionIndex(){
        $searchModel = new GroupSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionView($id){
        $model = $this->findModel($id);
        $users = (new Query())
            ->from('users')
            ->where([
                'groups' => $id
            ])
            ->all();
        
        return $this->render('view', [
            'model' => $model,
            'users' => $users
        ]);
    }

    public function actionCreate(){
        $model = new Group();

        if($model->load(Yii::$app->request->post())){
            $data = Yii::$app->request->post();
            $model->forms = $this->handleFormsPermissions($data, $model);
            if($model->save()){
                return $this->redirect(['view', 'id' => (string)$model->_id]);
            }
        }
        
        return $this->render('create', [
            'model' => $model,
            'forms' => $this->getFormsIDsAndNames()
        ]);
    }

    public function actionUpdate($id){
        $model = $this->findModel($id);

        if($model->load(Yii::$app->request->post())){
            $data = Yii::$app->request->post();
            $model->forms = $this->handleFormsPermissions($data, $model);
            if($model->save()){
                return $this->redirect(['view', 'id' => (string)$model->_id]);
            }
        }

        $checked_permissions = $model->forms;
        // The attribute 'forms' is a multi-level array according to MongoDB document
        $forms_IDs = [];
        foreach($model->forms as $key => $value){
            $forms_IDs[] = $key;
        }
        $model->forms = $forms_IDs;
        
        return $this->render('update', [
            'model' => $model,
            'forms' => $this->getFormsIDsAndNames(),
            'checked_permissions' => $checked_permissions
        ]);
    }

    public function actionDelete($id){
        $collection = Yii::$app->mongodb->getCollection('groups');
        $collection->remove(['_id' => Utilities::getIdAsObject($id)]);
        return $this->redirect(['index']);
    }

    protected function findModel($id){
        if(($model = Group::findOne($id)) != null){
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }

    public function getFormsIDsAndNames(){
        $forms = Form::find()->all();
        $forms_data = [];
        if($forms){
            foreach($forms as $form){
                $forms_data[] = [
                    'id' => (string)$form->_id,
                    'name' => $form->name . ($form->type == 'global' ? ' (Global)' : '')
                ];
            }
        }
        return $forms_data;
    }

    public function handleFormsPermissions($data, $model){
        $data_keys = array_keys($data);
        $forms_and_permissions = [];
        foreach($model->forms as $form){
            $forms_and_permissions[$form] = [
                'submit'         => in_array($form . '_submit', $data_keys)         ? true : false,
                'read'           => in_array($form . '_read', $data_keys)           ? true : false,
                'update'         => in_array($form . '_update', $data_keys)         ? true : false,
                'create-view'    => in_array($form . '_create-view', $data_keys)    ? true : false,
                'complete-data'  => in_array($form . '_complete-data', $data_keys)  ? true : false,
            ];
        }
        return $forms_and_permissions;
    }
}