<?php

namespace app\controllers;

use Yii;
use app\models\AnaliseRegulatoria;
use app\models\AnaliseRegulatoriaSearch;
use app\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use yii\filters\VerbFilter;

/**
 * AnaliseRegulatoriaController implements the CRUD actions for AnaliseRegulatoria model.
 */
class AnaliseRegulatoriaController extends BaseController {

    /**
     * {@inheritdoc}
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all AnaliseRegulatoria models.
     * @return mixed
     */
    public function actionIndex() {

        \app\models\Base::loga("Acessou a lista de Análises Regulatórias", $_GET, $_POST, 2);

        $searchModel = new AnaliseRegulatoriaSearch();

        if (!$searchModel->status) {
            $searchModel->status = AnaliseRegulatoria::ATIVO;
        }

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if (!\app\components\Logged::isCeon()) {

            $meusClientes = \app\models\GenericSearch::filterMyClientes()
                    ->query
                    ->select('id')
                    ->andwhere(['=', 'status', \app\modules\performance\models\Cliente::ATIVO])
                    ->column();

            $clientes = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\Cliente::find()
                                    ->where(['status' => \app\modules\performance\models\Cliente::ATIVO])
                                    ->andWhere(['in', 'id', $meusClientes])
                                    ->all(), 'id', 'nome');
        } else {
            $clientes = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\Cliente::find()
                                    ->where(['status' => \app\modules\performance\models\Cliente::ATIVO])
                                    ->all(), 'id', 'nome');
        }

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

    /**
     * Displays a single AnaliseRegulatoria model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id) {

        \app\models\Base::loga("Visualizou Análise Regulatória", $_GET, $_POST, 2);

        $model = $this->findModel($id);

        if (!\app\components\Logged::isCeon()) {

            $meusClientes = \app\models\GenericSearch::filterMyClientes()
                    ->query
                    ->select('id')
                    ->andwhere(['=', 'status', \app\modules\performance\models\Cliente::ATIVO])
                    ->column();

            if (!in_array($model->cliente_id, $meusClientes)) {
                throw new HttpException(500, "Análise regulatória não pertence a seu escritório");
            }
        }
        return $this->render('view', [
                    'model' => $model,
        ]);
    }

    /**
     * Creates a new AnaliseRegulatoria model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new AnaliseRegulatoria();

        if (!\app\components\Logged::isCeon()) {

            $meusClientes = \app\models\GenericSearch::filterMyClientes()
                    ->query
                    ->select('id')
                    ->andwhere(['=', 'status', \app\modules\performance\models\Cliente::ATIVO])
                    ->column();

            $clientes = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\Cliente::find()
                                    ->where(['status' => \app\modules\performance\models\Cliente::ATIVO])
                                    ->andWhere(['in', 'id', $meusClientes])
                                    ->all(), 'id', 'nome');
        } else {
            $clientes = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\Cliente::find()
                                    ->where(['status' => \app\modules\performance\models\Cliente::ATIVO])
                                    ->all(), 'id', 'nome');
        }

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

            if (!\app\components\Logged::isCeon()) {

                if (!in_array($model->cliente_id, $meusClientes)) {
                    throw new HttpException(500, "Análise regulatória não pertence a seu escritório");
                }
            }

            \app\models\Base::loga("Cadastrou Análise Regulatória", $_GET, $_POST, 2);

            if (!$model->save()) {
                throw new HttpException(500, "Erro ao cadastrar a análise regulatória, motivo: " . json_encode($model->gerErrors()));
            }

            return $this->redirect(['index']);
        }

        \app\models\Base::loga("Acessou a criação de Análise Regulatória", $_GET, $_POST, 2);

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

    /**
     * Updates an existing AnaliseRegulatoria model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if (!\app\components\Logged::isCeon()) {

            $meusClientes = \app\models\GenericSearch::filterMyClientes()
                    ->query
                    ->select('id')
                    ->andwhere(['=', 'status', \app\modules\performance\models\Cliente::ATIVO])
                    ->column();

            if (!in_array($model->cliente_id, $meusClientes)) {
                throw new HttpException(500, "Análise regulatória não pertence a seu escritório");
            }

            $clientes = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\Cliente::find()
                                    ->where(['status' => \app\modules\performance\models\Cliente::ATIVO])
                                    ->andWhere(['in', 'id', $meusClientes])
                                    ->all(), 'id', 'nome');
        } else {
            $clientes = \yii\helpers\ArrayHelper::map(\app\modules\performance\models\Cliente::find()
                                    ->where(['status' => \app\modules\performance\models\Cliente::ATIVO])
                                    ->all(), 'id', 'nome');
        }
        if ($model->load(Yii::$app->request->post())) {

            \app\models\Base::loga("Atualizou Análise Regulatória", $_GET, $_POST, 2);

            if (!\app\components\Logged::isCeon()) {

                if (!in_array($model->cliente_id, $meusClientes)) {
                    throw new HttpException(500, "Análise regulatória não pertence a seu escritório");
                }
            }

            \app\models\Base::loga("Cadastrou Análise Regulatória", $_GET, $_POST, 2);

            if (!$model->save()) {
                throw new HttpException(500, "Erro ao cadastrar a análise regulatória, motivo: " . json_encode($model->gerErrors()));
            }

            return $this->redirect(['index']);
        }

        \app\models\Base::loga("Acessou a atualização de Análise Regulatória", $_GET, $_POST, 2);

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

    /**
     * Deletes an existing AnaliseRegulatoria model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id) {

        \app\models\Base::loga("Excluiu Análise Regulatória", $_GET, $_POST, 2);

        $model = $this->findModel($id);

        if (!\app\components\Logged::isCeon()) {

            $meusClientes = \app\models\GenericSearch::filterMyClientes()
                    ->query
                    ->select('id')
                    ->andwhere(['=', 'status', \app\modules\performance\models\Cliente::ATIVO])
                    ->column();

            if (!in_array($model->cliente_id, $meusClientes)) {
                throw new HttpException(500, "Análise regulatória não pertence a seu escritório");
            }
        }

        $model->status = AnaliseRegulatoria::INATIVO;

        $model->save();


        return $this->redirect(['index']);
    }

    /**
     * Finds the AnaliseRegulatoria model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AnaliseRegulatoria the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = AnaliseRegulatoria::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionContexto($contexto, $aplicacao) {

        $this->layout = '//empty';

        $contextoModel = \app\modules\performance\models\Contexto::find()
                ->where([
                    'id' => $contexto,
                    'active' => \app\modules\performance\models\Contexto::ATIVO,
                ])
                ->one();

        if (!$contextoModel) {
            return '<br /><div class="alert alert-danger">Erro! Cliente não encontrado!</div>';
        }

        if ($contextoModel->tipoLicenca != 'Licenciado') {
            return '<br /><div class="alert alert-danger">Cliente não Licenciado';
        }


        if (!$contextoModel->acessoTemporarioLiberado) {
            throw new \yii\web\HttpException(500, "Cliente não autorizado para seu usuário, solicite acesso temporário ao gestor do Escritório");
        }

        $meusContextos = \app\models\GenericSearch::filterMyContextosVisualizacao()
                ->query
                ->select('contexto.id')
                ->andWhere('rgt-lft=1')
                ->andwhere(['=', 'contexto.id', $contextoModel->id])
                ->column();

        if (!$meusContextos) {
            throw new HttpException(500, "Erro! Cliente não permitido para seu usuário");
        }

        $aplicacao = \app\modules\performance\models\Aplicacao::findOne($aplicacao);

        $model = new \app\models\ContextoTemAnaliseRegulatoria();

        $model->contexto_id = $contextoModel->id;

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

            \app\models\ContextoTemAnaliseRegulatoria::deleteAll(['contexto_id' => $contextoModel->id]);

            if ($model->itens) {
                foreach ($model->itens as $key => $item) {

                    $analiseRegualatoria = AnaliseRegulatoria::findOne($item);

                    if (!$analiseRegualatoria) {
                        throw new HttpException(500, "Análise regulatória não encontrad");
                    }
                    if (!in_array($analiseRegualatoria->cliente_id, $meusClientes)) {
                        throw new HttpException(500, "Análise regulatória não pertence a seu escritório");
                    }

                    $contextoTemAnaliseRegulatoria = new \app\models\ContextoTemAnaliseRegulatoria();
                    $contextoTemAnaliseRegulatoria->contexto_id = $contextoModel->id;
                    $contextoTemAnaliseRegulatoria->analise_regulatoria_id = $item;
                    $contextoTemAnaliseRegulatoria->observacao = $_POST['ContextoTemAnaliseRegulatoria']['observacao'][$key];

                    if (!$contextoTemAnaliseRegulatoria->save()) {
                        throw new HttpException(500, "Erro ao salvar, motivo: " . json_encode($contextoTemAnaliseRegulatoria->getErrors()));
                    }
                }
            }

            \app\models\Base::loga("Cadastrou/Atualizou Análise Regulatória de Cliente", $_GET, $_POST, 2);

            return $this->redirect(['/performance/contexto/view', 'id' => $contextoModel->id, 'aplicacao_id' => $aplicacao->id])->send();
        }
               
        $itens = \yii\helpers\ArrayHelper::map(
                        AnaliseRegulatoria::find()
                                ->where([
                                    'status' => AnaliseRegulatoria::ATIVO,
                                ])
                                ->andWhere(['OR',
                                    ['=', 'cliente_id', $contextoModel->cliente_id,],
                                    ['is', 'cliente_id', new \yii\db\Expression('null')]
                                ])
                                ->all(), 'id', 'item');

        $marcados = \app\models\ContextoTemAnaliseRegulatoria::find()
                ->select('analise_regulatoria_id')
                ->where(['contexto_id' => $contextoModel->id])
                ->column();

        \app\models\Base::loga("Acessou a Análise Regulatporia de Cliente", $_GET, $_POST, 2);

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

}
