<?php

namespace app\modules\performance\controllers;

use Yii;
use app\modules\performance\models\Timeline;
use app\modules\performance\models\TimelineSearch;
use app\modules\performance\models\Contexto;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\helpers\ArrayHelper;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use yii\helpers\Url;
use app\modules\performance\models\TimelineTipo;
use app\modules\performance\models\ClienteTemTimelineTipo;
use app\modules\performance\models\Cliente;
use app\component\Utils;
use yii\web\HttpException;
use app\modules\performance\models\TipoPermissao;
use app\controllers\BaseController;
use app\models\GenericSearch;

/**
 * TimelineController implements the CRUD actions for Timeline model.
 */
class AtendimentoController extends BaseController
{

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

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

        \app\models\Base::loga("Acessou a visualização dos Atendimentos", $_GET, $_POST, 21);

        $searchModel = new TimelineSearch();

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

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

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

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

        return false;
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

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

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

        \app\models\Base::loga("Acessou a criação de Atendimento", $_GET, $_POST, 22);

        $model = new Timeline();

        $model->tipo = Timeline::TIPO_CONTEXTO;

        $model->cadastrado_por = \Yii::$app->user->identity->id;

        $model->cadastrado_nome = \Yii::$app->user->identity->name;

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

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

            $contexto = Contexto::find()
                ->where(['id' => $model->vinculo, 'active' => Contexto::ATIVO])
                ->one();

            if (!array_key_exists($contexto->id, $contextos)) {
                throw new HttpException(500, 'Contexto não pertence a seus clientes');
            }

            $dataNormal = explode("/", $model->data);

            $dia = '';
            if (isset($dataNormal[0])) {
                $dia = $dataNormal[0];
            }
            $mes = '';
            if (isset($dataNormal[1])) {
                $mes = $dataNormal[1];
            }
            $ano = '';
            if (isset($dataNormal[2])) {
                $ano = $dataNormal[2];
            }

            $model->data_cadastro = $ano . '-' . $mes . '-' . $dia . ' ' . $model->hora . ':00';

            if ($model->save()) {
                return $this->redirect(['index']);
            }
        }

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

    /**
     * Updates an existing Timeline 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)
    {

        \app\models\Base::loga("Acessou a atualização de Atendimento", $_GET, $_POST, 23);

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

        $model->tipo = Timeline::TIPO_CONTEXTO;

        $model->cadastrado_por = \Yii::$app->user->identity->id;

        $model->cadastrado_nome = \Yii::$app->user->identity->name;

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

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

            $contexto = Contexto::find()
                ->where(['id' => $model->vinculo, 'active' => Contexto::ATIVO])
                ->one();

            if (!array_key_exists($contexto->id, $contextos)) {
                throw new HttpException(500, 'Contexto não pertence a seus clientes');
            }

            $dataNormal = explode("/", $model->data);

            $dia = '';
            if (isset($dataNormal[0])) {
                $dia = $dataNormal[0];
            }
            $mes = '';
            if (isset($dataNormal[1])) {
                $mes = $dataNormal[1];
            }
            $ano = '';
            if (isset($dataNormal[2])) {
                $ano = $dataNormal[2];
            }

            $model->data_cadastro = $ano . '-' . $mes . '-' . $dia . ' ' . $model->hora . ':00';

            if ($model->save()) {
                return $this->redirect(['index']);
            }
        }

        $explodeData = explode(" ", $model->data_cadastro);

        $model->hora = substr($explodeData[1], 0, 5);

        $dataNormal = explode("-", $explodeData[0]);

        $dia = '';
        if (isset($dataNormal[2])) {
            $dia = $dataNormal[2];
        }
        $mes = '';
        if (isset($dataNormal[1])) {
            $mes = $dataNormal[1];
        }
        $ano = '';
        if (isset($dataNormal[0])) {
            $ano = $dataNormal[0];
        }

        $model->data = $dia . '/' . $mes . '/' . $ano;

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

    /**
     * Deletes an existing Timeline 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("Acessou a exclusão de Atendimento", $_GET, $_POST, 24);

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

        $model->data = date('d/m/Y', strtotime($model->data_cadastro));

        $model->hora = date('H:i', strtotime($model->data_cadastro));

        $contexto = Contexto::find()
            ->where(['id' => $model->vinculo, 'active' => Contexto::ATIVO])
            ->one();

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($contexto->id, $meusContextos)) {
            throw new HttpException(500, 'Contexto não pertence a seus clientes');
        }

        $model->status = Timeline::INATIVO;

        if (!$model->save()) {

            $msgErro = '<ul>';
            foreach ($model->getErrors() as $key => $value) {
                $msgErro .= '<li>' . $key . ': ' . json_encode($value) . '</li>';
            }
            $msgErro .= '</ul>';
            throw new HttpException(500, "Erro ao excluir o atendimento, motivo: " . $msgErro);
        }

        return true;
    }

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

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

    public function actionListaTimelinePossiveis()
    {

        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            if ($parents != null) {
                $contextoId = $parents[0];

                $clienteId = null;

                $contexto = Contexto::find()->where(['id' => $contextoId,])->one();

                if ($contexto) {
                    $clienteId = $contexto->cliente_id;
                }

                $timelineTipos = TimelineTipo::find()
                    ->joinWith('clienteTemTimelineTipos')
                    ->where([
                        'timeline_tipo.status' => TimelineTipo::ATIVO,
                        //       'cliente_tem_timeline_tipo.status' => ClienteTemTimelineTipo::ATIVO,
                    ])
                    //    ->andWhere(['=', 'cliente_tem_timeline_tipo.cliente_id', $clienteId])
                    ->all();

                //$list = Contexto::find()->where('(rgt-lft)=1')->andWhere(['=', 'active', Contexto::ATIVO])->andWhere(['=', 'cliente_id', $clienteId])->asArray()->all();

                $selected = null;
                if ($clienteId != null && count($timelineTipos) > 0) {
                    $selected = '';
                    foreach ($timelineTipos as $timelineTipo) {
                        $out[] = ['id' => $timelineTipo->id, 'name' => $timelineTipo->titulo];
                    }

                    if (isset($_POST['depdrop_all_params']['new'])) {
                        if ($_POST['depdrop_all_params']['new'] == 'sim') {
                            //$selected = '*';
                        } else {
                            //$projeto = Projeto::findOne($_POST['depdrop_all_params']['projeto']);
                            $projeto = null;
                            if ($projeto) {
                                $selected = [];
                                $c = explode(',', $projeto->contextos);
                                foreach ($c as $ey => $value) {
                                    $selected[] = $value;
                                }
                            }
                        }
                    }
                    // Shows how you can preselect a value
                    echo Json::encode(['output' => $out, 'selected' => $selected]);
                    return;
                }
                echo Json::encode(['output' => $out, 'selected' => '']);
                return;
            }
        }
        echo Json::encode(['output' => '', 'selected' => '']);
    }

    /**
     * Creates a new Timeline model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateAjax($id, $aplicacao_id)
    {

        \app\models\Base::loga("Acessou a criação de Atendimento via Contexto", $_GET, $_POST, 25);

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

        $model = new Timeline();

        $contexto = Contexto::find()
            ->where(['id' => $id, 'active' => Contexto::ATIVO])
            ->one();

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

        if (!array_key_exists($contexto->id, $contextos)) {
            throw new HttpException(500, 'Contexto não pertence a seus clientes');
        }

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

        if (!$aplicacao) {
            return '<div class="alert alert-danger">Erro! Aplicação não encontrada!</div>';
        }

        $model->vinculo = $id;

        $model->tipo = Timeline::TIPO_CONTEXTO;

        $model->cadastrado_por = \Yii::$app->user->identity->id;

        $model->cadastrado_nome = \Yii::$app->user->identity->name;

        $tipos = [];

        if ($contexto) {

            $tipos = ArrayHelper::map(TimelineTipo::find()
                ->joinWith('clienteTemTimelineTipos')
                ->where([
                    'timeline_tipo.status' => TimelineTipo::ATIVO,
                    'cliente_tem_timeline_tipo.status' => ClienteTemTimelineTipo::ATIVO,
                ])
                ->andWhere(['=', 'cliente_tem_timeline_tipo.cliente_id', $contexto->cliente_id])
                ->all(), 'id', 'titulo');
        } else {
            throw new HttpException(500, 'Contexto não encontrado');
        }

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


            if (!array_key_exists($contexto->id, $contextos)) {
                throw new HttpException(500, 'Contexto não pertence a seus clientes');
            }

            $dataNormal = explode("/", $model->data);

            $dia = '';
            if (isset($dataNormal[0])) {
                $dia = $dataNormal[0];
            }
            $mes = '';
            if (isset($dataNormal[1])) {
                $mes = $dataNormal[1];
            }
            $ano = '';
            if (isset($dataNormal[2])) {
                $ano = $dataNormal[2];
            }

            $model->data_cadastro = $ano . '-' . $mes . '-' . $dia . ' ' . $model->hora . ':00';

            //            if (!array_key_exists($model->timeline_tipo_id, $tipos)) {
            //                throw new HttpException(500, 'Tipo de atendimento não permitido para esse contexto');
            //            }

            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Atendimento cadastrado com sucesso!');
            } else {
                Yii::$app->session->setFlash('danger', 'Erro ao cadastrar o atendimento! Motivo: ' . json_encode($model->getErrors()));
            }

            return $this->redirect(['/performance/contexto/view', 'id' => $id, 'aplicacao_id' => $aplicacao_id]);
        }

        $permiteEditar = true;

        $tarefasAtrasadas = \app\modules\performance\models\Tarefa::find()
            ->join('LEFT JOIN', 'pa_acao_proposta', 'pa_acao_proposta.id=pa_tarefa.pa_acao_proposta_id')
            ->join('LEFT JOIN', 'pa_plano_acao', 'pa_plano_acao.id=pa_acao_proposta.pa_plano_acao_id')
            ->where([
                'pa_plano_acao.contexto_id' => $contexto->id,
                'pa_acao_proposta.status' => \app\modules\performance\models\PlanoAcao::ATIVO,
                'pa_plano_acao.status' => \app\modules\performance\models\AcaoProposta::ATIVO,
            ])
            ->andWhere(['<', 'pa_tarefa.termino_previsto', date('Y-m-d')])
            ->andWhere(['!=', 'pa_tarefa.situacao', \app\modules\performance\models\Tarefa::SITUACAO_ENCERRADA])
            ->orderBy('pa_plano_acao_id ASC, pa_tarefa.termino_previsto ASC, pa_tarefa.id ASC')
            ->all();

        $totalNotificacoes = count($tarefasAtrasadas);

        $ultimasAtualizacoes = \app\models\Log::find()
            ->where([
                'contexto_id' => $contexto->id,
            ])
            ->andWhere(['!=', 'mensagem', 'Acessou a visualização de Contexto'])
            ->orderBy('id DESC')
            ->limit(10)
            ->all();

        return $this->render('create', [
            'model' => $model,
            'contextos' => $contextos,
            'breadcrumb' => ['label' => $contexto->name, 'url' => Url::previous()],
            'contexto' => $contexto,
            'aplicacao' => $aplicacao,
            'permiteEditar' => $permiteEditar,
            'totalNotificacoes' => $totalNotificacoes,
            'ultimasAtualizacoes' => $ultimasAtualizacoes,
        ]);
    }

    public function actionUpdateAjax($id, $aplicacao_id)
    {

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

        \app\models\Base::loga("Acessou a atualização de Atendimento via Contexto", $_GET, $_POST, 26);

        $model = Timeline::find()->where(['id' => $id, 'status' => Timeline::ATIVO])->one();

        $model->tipo = Timeline::TIPO_CONTEXTO;

        $model->cadastrado_por = \Yii::$app->user->identity->id;

        $model->cadastrado_nome = \Yii::$app->user->identity->name;

        $contexto = Contexto::find()
            ->where(['id' => $model->vinculo, 'active' => Contexto::ATIVO])
            ->one();

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

        if (!array_key_exists($contexto->id, $contextos)) {
            throw new HttpException(500, 'Contexto não pertence a seus clientes');
        }

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

        if (!$aplicacao) {
            return '<div class="alert alert-danger">Erro! Aplicação não encontrada!</div>';
        }

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

            $contexto = Contexto::find()
                ->where(['id' => $model->vinculo, 'active' => Contexto::ATIVO])
                ->one();


            if (!array_key_exists($contexto->id, $contextos)) {
                throw new HttpException(500, 'Contexto não pertence a seus clientes');
            }

            $dataNormal = explode("/", $model->data);

            $dia = '';
            if (isset($dataNormal[0])) {
                $dia = $dataNormal[0];
            }
            $mes = '';
            if (isset($dataNormal[1])) {
                $mes = $dataNormal[1];
            }
            $ano = '';
            if (isset($dataNormal[2])) {
                $ano = $dataNormal[2];
            }

            $model->data_cadastro = $ano . '-' . $mes . '-' . $dia . ' ' . $model->hora . ':00';

            if ($model->save()) {
                Yii::$app->session->setFlash('success', 'Atendimento cadastrado com sucesso!');
            } else {
                Yii::$app->session->setFlash('danger', 'Erro ao cadastrar o atendimento! Motivo: ' . json_encode($model->getErrors()));
            }

            return $this->redirect(['/performance/contexto/view', 'id' => $model->vinculo, 'aplicacao_id' => $aplicacao_id]);
        }

        $explodeData = explode(" ", $model->data_cadastro);

        $model->hora = substr($explodeData[1], 0, 5);

        $dataNormal = explode("-", $explodeData[0]);

        $dia = '';
        if (isset($dataNormal[2])) {
            $dia = $dataNormal[2];
        }
        $mes = '';
        if (isset($dataNormal[1])) {
            $mes = $dataNormal[1];
        }
        $ano = '';
        if (isset($dataNormal[0])) {
            $ano = $dataNormal[0];
        }

        $model->data = $dia . '/' . $mes . '/' . $ano;

        $permiteEditar = true;

        $tarefasAtrasadas = \app\modules\performance\models\Tarefa::find()
            ->join('LEFT JOIN', 'pa_acao_proposta', 'pa_acao_proposta.id=pa_tarefa.pa_acao_proposta_id')
            ->join('LEFT JOIN', 'pa_plano_acao', 'pa_plano_acao.id=pa_acao_proposta.pa_plano_acao_id')
            ->where([
                'pa_plano_acao.contexto_id' => $contexto->id,
                'pa_acao_proposta.status' => \app\modules\performance\models\PlanoAcao::ATIVO,
                'pa_plano_acao.status' => \app\modules\performance\models\AcaoProposta::ATIVO,
            ])
            ->andWhere(['<', 'pa_tarefa.termino_previsto', date('Y-m-d')])
            ->andWhere(['!=', 'pa_tarefa.situacao', \app\modules\performance\models\Tarefa::SITUACAO_ENCERRADA])
            ->orderBy('pa_plano_acao_id ASC, pa_tarefa.termino_previsto ASC, pa_tarefa.id ASC')
            ->all();

        $totalNotificacoes = count($tarefasAtrasadas);

        $ultimasAtualizacoes = \app\models\Log::find()
            ->where([
                'contexto_id' => $contexto->id,
            ])
            ->andWhere(['!=', 'mensagem', 'Acessou a visualização de Contexto'])
            ->orderBy('id DESC')
            ->limit(10)
            ->all();

        return $this->render('update', [
            'model' => $model,
            'contextos' => $contextos,
            'breadcrumb' => ['label' => $contexto->name, 'url' => Url::previous()],
            'contexto' => $contexto,
            'aplicacao' => $aplicacao,
            'permiteEditar' => $permiteEditar,
            'totalNotificacoes' => $totalNotificacoes,
            'ultimasAtualizacoes' => $ultimasAtualizacoes,
        ]);
    }

    public function actionDeleteAjax($id, $aplicacao_id)
    {

        \app\models\Base::loga("Acessou a exclusão de Atendimento via Contexto", $_GET, $_POST, 27);

        $model = Timeline::find()->where(['id' => $id, 'status' => Timeline::ATIVO])->one();

        if (!$model) {
            throw new HttpException(500, 'Atendimento não encontrado');
        }

        $contexto = Contexto::find()->where(['id' => $model->vinculo])->one();

        if (!$contexto) {
            throw new HttpException(500, 'Atendimento não encontrado');
        }

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($contexto->id, $meusContextos)) {
            throw new HttpException(500, 'Contexto não pertence a seus clientes');
        }

        $model->status = Timeline::INATIVO;

        $model->data = date('d/m/Y', strtotime($model->data_cadastro));

        $model->hora = date('H:i', strtotime($model->data_cadastro));

        if (!$model->save()) {
            throw new HttpException(500, "Erro ao excluir o item do timeline, motivo: " . json_encode($model->getErrors()));
        }

        return $this->redirect(['/performance/contexto/view', 'id' => $model->vinculo, 'aplicacao_id' => $aplicacao_id]);
    }

    public function actionCreateApuracao($apuracao_id)
    {

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

        $model = new Timeline();

        $model->tipo = Timeline::TIPO_APURACAO;

        $model->vinculo = $apuracao_id;

        $model->cadastrado_por = \Yii::$app->user->identity->id;

        $model->cadastrado_nome = \Yii::$app->user->identity->name;


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

            $dataNormal = explode("/", $model->data);

            $dia = '';
            if (isset($dataNormal[0])) {
                $dia = $dataNormal[0];
            }
            $mes = '';
            if (isset($dataNormal[1])) {
                $mes = $dataNormal[1];
            }
            $ano = '';
            if (isset($dataNormal[2])) {
                $ano = $dataNormal[2];
            }

            $model->data_cadastro = $ano . '-' . $mes . '-' . $dia . ' ' . $model->hora . ':00';

            if ($model->save()) {
                return $this->redirect(['/apuracao/update', 'id' => $apuracao_id]);
            }
        }

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

    public function actionUpdateApuracao($id)
    {

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

        \app\models\Base::loga("Acessou a atualização de Atendimento", $_GET, $_POST, 23);

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

        $model->cadastrado_por = \Yii::$app->user->identity->id;

        $model->cadastrado_nome = \Yii::$app->user->identity->name;

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->all();

        $contextos = ArrayHelper::map($meusContextos, 'id', 'clienteNomeName');

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

            $contexto = Contexto::find()
                ->where(['id' => $model->vinculo, 'active' => Contexto::ATIVO])
                ->one();

//            if (!array_key_exists($contexto->id, $contextos)) {
 ///               throw new HttpException(500, 'Contexto não pertence a seus clientes');
    //        }

            $dataNormal = explode("/", $model->data);

            $dia = '';
            if (isset($dataNormal[0])) {
                $dia = $dataNormal[0];
            }
            $mes = '';
            if (isset($dataNormal[1])) {
                $mes = $dataNormal[1];
            }
            $ano = '';
            if (isset($dataNormal[2])) {
                $ano = $dataNormal[2];
            }

            $model->data_cadastro = $ano . '-' . $mes . '-' . $dia . ' ' . $model->hora . ':00';

            if ($model->save()) {
                return $this->redirect(['/apuracao/update', 'id' => $model->vinculo]);
            }
        }

        $explodeData = explode(" ", $model->data_cadastro);

        $model->hora = substr($explodeData[1], 0, 5);

        $dataNormal = explode("-", $explodeData[0]);

        $dia = '';
        if (isset($dataNormal[2])) {
            $dia = $dataNormal[2];
        }
        $mes = '';
        if (isset($dataNormal[1])) {
            $mes = $dataNormal[1];
        }
        $ano = '';
        if (isset($dataNormal[0])) {
            $ano = $dataNormal[0];
        }

        $model->data = $dia . '/' . $mes . '/' . $ano;

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

    public function actionDeleteApuracao($id)
    {

        \app\models\Base::loga("Acessou a exclusão de Atendimento", $_GET, $_POST, 24);

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

        $model->data = date('d/m/Y', strtotime($model->data_cadastro));

        $model->hora = date('H:i', strtotime($model->data_cadastro));

        $contexto = Contexto::find()
            ->where(['id' => $model->vinculo, 'active' => Contexto::ATIVO])
            ->one();

        $meusContextos = GenericSearch::filterMyContextosAnaliseTecnica()
            ->query
            ->select('id')
            ->andWhere('rgt-lft=1')
            ->andwhere(['=', 'active', Contexto::ATIVO])
            ->column();

        if (!in_array($contexto->id, $meusContextos)) {
            throw new HttpException(500, 'Contexto não pertence a seus clientes');
        }

        $model->status = Timeline::INATIVO;

        if (!$model->save()) {

            $msgErro = '<ul>';
            foreach ($model->getErrors() as $key => $value) {
                $msgErro .= '<li>' . $key . ': ' . json_encode($value) . '</li>';
            }
            $msgErro .= '</ul>';
            throw new HttpException(500, "Erro ao excluir o atendimento, motivo: " . $msgErro);
        }

        return $this->redirect(['/apuracao/update', 'id' => $model->vinculo]);
       
    }
}
