<?php

namespace app\modules\performance\controllers;

use Yii;
use app\modules\performance\models\FormularioResposta;
use app\modules\performance\models\FormularioRespostaSearch;
use app\modules\performance\models\FormularioPerguntaResposta;
use app\modules\performance\models\FormularioPergunta;
use app\modules\performance\models\Formulario;
use app\modules\performance\models\Coleta;
use app\modules\performance\models\Projeto;
use app\modules\performance\models\Vertical;
use app\modules\performance\models\Contexto;
use app\modules\performance\models\Arvore;
use app\modules\performance\models\ArvoreRespostaSearch;
use app\modules\performance\models\ArvoreResposta;
use app\modules\performance\models\ArvorePergunta;
use app\modules\performance\models\ArvoreAlternativa;
use app\modules\performance\models\ArvoreRespostaPerguntaAlternativa;
use app\models\GenericSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use app\components\Utils;

/**
 * FormularioRespostaController implements the CRUD actions for FormularioResposta model.
 */
class FormularioRespostaController extends Controller {

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

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

        \app\models\Base::loga("Acessou a lista de Formulários", $_GET, $_POST, 56);

        $searchModel = new FormularioRespostaSearch();

        $searchModel->status = FormularioResposta::ATIVO;

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

        $searchModelArvore = new ArvoreRespostaSearch();

        $searchModelArvore->status = ArvoreResposta::ATIVO;

        $dataProviderArvore = $searchModelArvore->search(Yii::$app->request->queryParams);

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

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

        \app\models\Base::loga("Acessou a visualização de Formulário", $_GET, $_POST, 57);

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

        $myForms = GenericSearch::filterMyFormularios()
                ->query
                ->select('id')
                ->column();

        if (!in_array($model->formulario_id, $myForms)) {
            throw new HttpException(500, "Formulário não liberado para seu usuário");
        }

        $municipio = 'N/D';
        $latitude = 0;
        $longitude = 0;

        if ($model->coleta_id) {

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

            $contextoTemParametro = \app\modules\performance\models\ContextoTemParametro::find()
                    ->where([
                        'contexto_id' => $model->coleta->contexto_id,
                        'parametro' => 'Município'
                    ])
                    ->one();
            if ($contextoTemParametro) {
                $municipio = $contextoTemParametro->informacao;
            }

            $latitude = $model->coleta->contexto->latitude;
            $longitude = $model->coleta->contexto->longitude;
        }

        if ($model->formulario->tipo == \app\modules\performance\models\Formulario::FORMULARIO_TIPO_APLICACAO) {
            return $this->render('_view_tipo_aplicacao', [
                        'model' => $model,
                        'municipio' => $municipio,
                        'latitude' => $latitude,
                        'longitude' => $longitude,
            ]);
        } elseif ($model->formulario->tipo == \app\modules\performance\models\Formulario::FORMULARIO_TIPO_COLETA_WEB) {

            $estrutura = Coleta::estrutura($model->coleta, false);
            return $this->render('_view_tipo_coleta_web', [
                        'model' => $model,
                        'estrutura' => $estrutura,
            ]);
        } else {
            return $this->render('_view_tipo_generico', [
                        'model' => $model,
            ]);
        }
    }

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

        \app\models\Base::loga("Acessou a criação de Resposta de Formulário", $_GET, $_POST, 58);

        $myForms = GenericSearch::filterMyFormularios()
                ->query
                ->select('id')
                ->column();

        if (!in_array($formulario_id, $myForms)) {
            throw new HttpException(500, "Formulário não liberado para seu usuário");
        }

        $model = new FormularioResposta();
        $model->formulario_id = $formulario_id;

        $formularioPerguntaResposta = new FormularioPerguntaResposta();

        $contexto = new \app\modules\performance\models\Contexto();

        $coleta = new \app\modules\performance\models\Coleta();

        $formulario = \app\modules\performance\models\Formulario::findOne($formulario_id);

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

            $resultado = null;

            if ($formulario->tipo == \app\modules\performance\models\Formulario::FORMULARIO_TIPO_APLICACAO) {

                $resultado = $model->salvaTipoAplicacao(Yii::$app->request->post(), $contexto, $coleta);
            }

            if ($formulario->tipo == \app\modules\performance\models\Formulario::FORMULARIO_TIPO_GENERICO) {

                $resultado = $model->salvaTipoGenerico(Yii::$app->request->post());
            }

            if ($formulario->tipo == \app\modules\performance\models\Formulario::FORMULARIO_TIPO_COLETA_WEB) {


                $resultado = $model->salvaTipoColetaWeb(Yii::$app->request->post());
            }

            if ($formulario->codigo_pos_preenchimento && $resultado) {

                eval("\$pos = $formulario->codigo_pos_preenchimento");

                if ($pos !== true) {
                    $model->status = FormularioResposta::INATIVO;
                    $resultado = false;
                }
            }

            if ($resultado) {
                return $this->redirect(['view', 'id' => $resultado]);
            }
        }

        if ($formulario->tipo == \app\modules\performance\models\Formulario::FORMULARIO_TIPO_APLICACAO) {

            $indicadores = null;
            if ($formulario->vertical_id) {
                $indicadores = \app\modules\performance\models\VerticalIndicador::find()
                        ->joinWith(['estrutura'])
                        ->where([
                            'vertical_estrutura.vertical_id' => (int) $formulario->vertical->id,
                            'vertical_estrutura.status' => \app\modules\performance\models\VerticalEstrutura::ATIVO,
                            'vertical_indicador.status' => \app\modules\performance\models\VerticalIndicador::ATIVO
                        ])
                        ->all();
            }

            $municipios = \yii\helpers\ArrayHelper::map(
                            \app\models\Municipio::find()
                                    ->joinWith(['estado'])
                                    ->where([
                                        'municipio.status' => \app\models\Municipio::ATIVO,
                                        'estado.id' => \app\models\Estado::SANTA_CATARINA,
                                    ])
                                    ->orderBy('municipio.nome ASC')
                                    ->all(),
                            'id', 'nome');

            $contexto = new \app\modules\performance\models\Contexto();

            $filhosContextoBase = null;
            $filhos = [];

            if ($formulario->node_base) {
                $contextoBase = \app\modules\performance\models\Contexto::findOne($formulario->node_base);

                $filhosContextoBase = $contextoBase->children()->all();

                $filhos[] = $formulario->node_base;
                foreach ($filhosContextoBase as $filhoContextoBase) {
                    if ($filhoContextoBase->active == \app\modules\performance\models\Contexto::ATIVO) {
                        $filhos[] = $filhoContextoBase->id;
                    }
                }
            }

            $treeContexto = \app\modules\performance\models\Contexto::find()
                    ->andWhere(['in', 'id', $filhos])
                    ->addOrderBy('root, lft');

            foreach ($treeContexto->all() as $t) {
                if ($t->rgt - $t->lft > 1) {
                    $t->disabled = 1;
                    $t->save();
                }
            }

            return $this->render('_form_aplicacao', [
                        'model' => $model,
                        'formularioPerguntaResposta' => $formularioPerguntaResposta,
                        'indicadores' => $indicadores,
                        'formulario' => $formulario,
                        'contexto' => $contexto,
                        'municipios' => $municipios,
                        'treeContexto' => $treeContexto,
                        'coleta' => $coleta,
            ]);
        } elseif ($formulario->tipo == \app\modules\performance\models\Formulario::FORMULARIO_TIPO_COLETA_WEB) {

            $indicadores = null;

            $contexto = new \app\modules\performance\models\Contexto();

            $filhosContextoBase = null;
            $filhos = [];

            if ($formulario->node_base) {
                $contextoBase = \app\modules\performance\models\Contexto::findOne($formulario->node_base);

                $filhosContextoBase = $contextoBase->children()->all();

                $filhos[] = $formulario->node_base;
                foreach ($filhosContextoBase as $filhoContextoBase) {
                    if ($filhoContextoBase->active == \app\modules\performance\models\Contexto::ATIVO) {
                        $filhos[] = $filhoContextoBase->id;
                    }
                }
            }

            $treeContexto = \app\modules\performance\models\Contexto::find()
                    ->andWhere(['in', 'id', $filhos])
                    ->addOrderBy('root, lft');

            foreach ($treeContexto->all() as $t) {
                if ($t->rgt - $t->lft > 1) {
                    $t->disabled = 1;
                    $t->save();
                }
            }

            $municipios = \yii\helpers\ArrayHelper::map(
                            \app\models\Municipio::find()
                                    ->joinWith(['estado'])
                                    ->where([
                                        'municipio.status' => \app\models\Municipio::ATIVO,
                                        'estado.id' => \app\models\Estado::SANTA_CATARINA,
                                    ])
                                    ->orderBy('municipio.nome ASC')
                                    ->all(),
                            'id', 'nome');

            return $this->render('_form_coleta_web', [
                        'model' => $model,
                        'formulario' => $formulario,
                        'contexto' => $contexto,
                        'treeContexto' => $treeContexto,
                        'coleta' => $coleta,
                        'municipios' => $municipios,
            ]);
        } else {

            $perguntas = FormularioPergunta::find()
                    ->where([
                        'formulario_id' => $model->formulario_id,
                        'status' => FormularioPergunta::ATIVO
                    ])
                    ->orderby('ordem ASC, id ASC')
                    ->all();

            return $this->render('_form_generico', [
                        'model' => $model,
                        'perguntas' => $perguntas,
                        'formularioPerguntaResposta' => $formularioPerguntaResposta,
            ]);
        }
    }

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

        return false;

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

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

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

    /**
     * Deletes an existing FormularioResposta 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 Formulário", $_GET, $_POST, 59);

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

        $myForms = GenericSearch::filterMyFormularios()
                ->query
                ->select('id')
                ->column();

        if (!in_array($model->formulario_id, $myForms)) {
            throw new HttpException(500, "Formulário não liberado para seu usuário");
        }

        $connection = \Yii::$app->db;

        $transaction = $connection->beginTransaction();
        try {

            $model->status = Formulario::INATIVO;

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

            if ($model->coleta_id) {
                $coleta = Coleta::findOne($model->coleta_id);

                if ($coleta) {


                    $qteColetas = Coleta::find()
                            ->where([
                                'contexto_id' => $coleta->contexto_id,
                                'status' => Coleta::ATIVO,
                            ])
                            ->count();

                    if ($qteColetas == 1) {
                        $contexto = Contexto::findOne($coleta->contexto->id);
                        if ($contexto) {
                            $contexto->active = Contexto::INATIVO;
                            if (!$contexto->save()) {
                                throw new HttpException(500, "Erro ao excluir o contexto, motivo: " . json_encode($contexto->getErrors()));
                            }
                        }
                    }

                    $coleta->status = Coleta::INATIVO;

                    if (!$coleta->save()) {
                        throw new HttpException(500, "Erro ao excluir a coleta gerada pelo formulário, motivo: " . json_encode($coleta->geetErrors()));
                    }
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollback();
        }


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

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

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

    public function actionBuscaFormulario() {

        \app\models\Base::loga("Acessou a busca de Formulário", $_GET, $_POST, 60);

        $formularioResposta = new FormularioResposta();

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

            $exp = explode("-", $formularioResposta->tipoFormularioArvore);

            if (isset($exp[0]) && $exp[0] == 'F') {
                $this->redirect(['create', 'formulario_id' => $exp[1]]);
            }

            if (isset($exp[0]) && $exp[0] == 'A') {
                $this->redirect(['create-arvore', 'arvore_id' => $exp[1]]);
            }
        }

        $myForms = GenericSearch::filterMyFormularios()
                ->query
                ->select('id')
                ->column();

        $formularios = Formulario::find()
                ->where(['status' => Formulario::ATIVO])
                ->andWhere(['in', 'id', $myForms])
                ->orderBy('nome ASC')
                ->all();

        $formulariosArvores = [];
        foreach ($formularios as $formulario) {
            $formulariosArvores[] = ['id' => 'F-' . $formulario->id, 'name' => $formulario->nome, 'tipo' => 'Formulários'];
        }

        $arvores = Arvore::find()
                ->where(['status' => Arvore::ATIVO])
                ->orderBy('nome ASC')
                ->all();

        foreach ($arvores as $arvore) {
            $formulariosArvores[] = ['id' => 'A-' . $arvore->id, 'name' => $arvore->nome, 'tipo' => 'Árvore'];
        }

        $formulariosArvores = ArrayHelper::map($formulariosArvores, 'id', 'name', 'tipo');


        return $this->renderAjax('_busca-formulario', [
                    'formularioResposta' => $formularioResposta,
                    'formularios' => $formularios,
                    'formulariosArvores' => $formulariosArvores,
        ]);
    }

    public function actionBuscaEstruturaApp() {

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

            if (!isset($_POST["projeto"]) || !isset($_POST["vertical"]) || !isset($_POST["contexto"])) {
                throw new HttpException(500, "Falta campo obrigatório");
            }

            $projeto = Projeto::find()->where(['id' => (int) $_POST['projeto'], 'status' => Projeto::ATIVO])->one();

            if (!$projeto) {
                throw new HttpException(500, "Projeto não encontrado");
            }

            $vertical = Vertical::find()->where(['id' => (int) $_POST['vertical'], 'status' => Projeto::ATIVO])->one();

            if (!$vertical) {
                throw new HttpException(500, "Vertical não encontrada");
            }

            $vertical = Vertical::find()->where(['id' => (int) $_POST["vertical"], 'status' => Vertical::ATIVO])->one();

            if (!$vertical) {
                throw new HttpException(500, "Vertical do projeto não encontrada");
            }

            $estrutura = Vertical::estruturaFormApp($vertical, $_POST["contexto"]);

            return $estrutura;
        }
    }

    public function actionListaRespostas($id, $formulario, $pergunta) {

        $formularioPergunta = FormularioPergunta::find()
                ->where([
                    'pergunta' => $pergunta,
                    'formulario_id' => $formulario,
                    'status' => FormularioPergunta::ATIVO,
                ])
                ->one();

        if (!$formularioPergunta) {
            return json_encode(['data' => [], 'informacao' => []]);
        }

        $formularioRespostas = FormularioPerguntaResposta::find()
                ->select(['coleta.data_coleta as extra', 'resposta'])
                ->join('INNER JOIN', 'formulario_resposta', 'formulario_pergunta_resposta.formulario_resposta_id=formulario_resposta.id')
                ->join('INNER JOIN', 'coleta', 'formulario_resposta.coleta_id=coleta.id')
                ->where([
                    'formulario_pergunta_resposta.formulario_pergunta_id' => $formularioPergunta->id,
                    'coleta.contexto_id' => $id,
                    'formulario_pergunta_resposta.status' => FormularioPerguntaResposta::ATIVO
                ])
                ->all();

        $datas = [];
        $respostas = [];

        foreach ($formularioRespostas as $formularioResposta) {

            $datas[] = date('d/m/Y', strtotime($formularioResposta['extra']));

            $respostas[] = round($formularioResposta['resposta'], 2);
        }

        return json_encode(['data' => $datas, 'informacao' => $respostas]);
    }

    public function actionCreateArvore($arvore_id) {

        \app\models\Base::loga("Acessou a criação de Resposta de Árvore", $_GET, $_POST, 58);

        $model = new ArvoreResposta();
        $model->ca_arvore_id = $arvore_id;
        $model->status = ArvoreResposta::ATIVO;

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


            $model->respondido_por = \Yii::$app->user->identity->id ?? null;

            $model->respondido_em = date('Y-m-d H:i:s');

            $estrutura = [];

            $primeiraPergunta = ArvorePergunta::find()
                    ->where([
                        'ca_arvore_id' => $arvore_id,
                        'status' => ArvorePergunta::ATIVO,
                    ])
                    ->orderBy('id ASC')
                    ->one();

            $estrutura[] = [
                "id" => 'P' . $primeiraPergunta->id,
                "parent" => '#',
                "text" => $primeiraPergunta->pergunta,
                "icon" => 'fab fa-product-hunt',
                "data" => [
                    "pergunta" => 'P' . $primeiraPergunta->id,
                ],
            ];

            foreach ($primeiraPergunta
                    ->getArvoreAlternativas()
                    ->where(['status' => ArvoreAlternativa::ATIVO])
                    ->orderBy('ordem ASC, id ASC')
                    ->all() as $alternativa) {

                $estrutura[] = [
                    "id" => 'A' . $alternativa->id,
                    "parent" => 'P' . $alternativa->ca_arvore_pergunta_id,
                    "text" => $alternativa->texto,
                    "icon" => 'far fa-circle',
                    "data" => [
                        "pergunta" => 'P' . $primeiraPergunta->id,
                    ]
                ];
            }

            $outrasPerguntas = ArvorePergunta::find()
                    ->where([
                        'ca_arvore_id' => $arvore_id,
                        'status' => ArvorePergunta::ATIVO,
                    ])
                    ->andWhere(['!=', 'id', $primeiraPergunta->id])
                    ->orderBy('id ASC')
                    ->all();

            foreach ($outrasPerguntas as $outrasPergunta) {

                $estrutura[] = [
                    "id" => 'P' . $outrasPergunta->id,
                    "parent" => 'A' . $outrasPergunta->ca_arvore_alternativa_id,
                    "text" => $outrasPergunta->pergunta,
                    "icon" => 'fab fa-product-hunt',
                    "data" => [
                        "pergunta" => 'P' . $outrasPergunta->id,
                    ]
                ];

                foreach ($outrasPergunta
                        ->getArvoreAlternativas()
                        ->where(['status' => ArvoreAlternativa::ATIVO])
                        ->orderBy('ordem ASC, id ASC')
                        ->all() as $alternativa) {
                    $estrutura[] = [
                        "id" => 'A' . $alternativa->id,
                        "parent" => 'P' . $alternativa->ca_arvore_pergunta_id,
                        "text" => $alternativa->texto,
                        "icon" => 'far fa-circle',
                        "data" => [
                            "pergunta" => 'P' . $outrasPergunta->id,
                        ]
                    ];
                }
            }

            $model->arvore_estrutura = json_encode($estrutura);

            if ($model->save()) {
                return $this->redirect([
                            'arvore-resposta-pergunta',
                            'resposta' => $model->id,
                ]);
            }

//            if ($model->arvore->codigo_fim_resposta && $resultado) {
//
//                eval("\$pos = $model->arvore->codigo_fim_resposta");
//
//                if ($pos !== true) {
//                    $model->status = ArvoreResposta::INATIVO;
//                    $resultado = false;
//                }
//            }
        }

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

    public function actionArvoreRespostaPergunta($resposta) {

        $arvoreResposta = ArvoreResposta::findOne($resposta);

        if (!$arvoreResposta) {
            throw new HttpException(404, "Resposta não encontrada");
        }

        $model = new ArvoreRespostaPerguntaAlternativa();

        $model->ca_arvore_resposta_id = $arvoreResposta->id;

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

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


        $ultimaArvoreRespostaPerguntaAlternativa = ArvoreRespostaPerguntaAlternativa::find()
                ->where([
                    'ca_arvore_resposta_id' => $arvoreResposta->id,
                ])
                ->orderBy('id DESC')
                ->one();

        if ($ultimaArvoreRespostaPerguntaAlternativa) {
            $primeira = false;
            $pergunta = ArvorePergunta::find()
                    ->where([
                        'ca_arvore_alternativa_id' => $ultimaArvoreRespostaPerguntaAlternativa->ca_arvore_alternativa_id,
                        'status' => ArvorePergunta::ATIVO,
                    ])
                    ->one();
        } else {
            $primeira = true;
            $pergunta = ArvorePergunta::find()
                    ->where([
                        'ca_arvore_id' => $arvoreResposta->ca_arvore_id,
                        'status' => ArvorePergunta::ATIVO,
                    ])
                    ->one();
        }

        if (!$pergunta) {
            Yii::$app->session->setFlash('success', "Encerrado!");

            if ($arvoreResposta->arvore->codigo_fim_resposta) {

                $arvoreT = $arvoreResposta->arvore;
                eval("\$pos = $arvoreT->codigo_fim_resposta");
            }

            return $this->redirect(['arvore-view', 'resposta' => $arvoreResposta->id]);
        } else {

            $alternativas = $pergunta
                    ->getArvoreAlternativas()
                    ->andWhere(['status' => ArvoreAlternativa::ATIVO])
                    ->orderBy('ordem ASC, id ASC')
                    ->all();

            $qtdeAlternativas = count($alternativas);

            if ($qtdeAlternativas == 1) {
                $col = 12;
            } elseif ($qtdeAlternativas == 2) {
                $col = 6;
            } elseif ($qtdeAlternativas == 3) {
                $col = 4;
            } elseif ($qtdeAlternativas == 4) {
                $col = 3;
            } elseif ($qtdeAlternativas == 5) {
                $col = 3;
            } else {
                $col = 12;
            }

            return $this->render('_form_arvore_pergunta', [
                        'model' => $model,
                        'resposta' => $arvoreResposta,
                        'pergunta' => $pergunta,
                        'alternativas' => $alternativas,
                        'col' => $col,
                        'primeira' => $primeira,
            ]);
        }
    }

    public function actionArvoreCancelaPergunta($resposta) {

        $ultimaArvoreRespostaPerguntaAlternativa = ArvoreRespostaPerguntaAlternativa::find()
                ->where([
                    'ca_arvore_resposta_id' => $resposta,
                ])
                ->orderBy('id DESC')
                ->one();

        if ($ultimaArvoreRespostaPerguntaAlternativa) {

            if ($ultimaArvoreRespostaPerguntaAlternativa->delete()) {
                return $this->redirect(['arvore-resposta-pergunta', 'resposta' => $resposta]);
            } else {
                throw new HttpException(500, "Erro ao excluir a resposta, motivo: " . json_encode($ultimaArvoreRespostaPerguntaAlternativa->getErrors()));
            }
        } else {
            throw new HttpException(500, "Erro: resposta não encontrada.");
        }
    }

    public function actionArvoreView($resposta) {

        $arvoreResposta = ArvoreResposta::find()
                ->where([
                    'id' => $resposta,
                    'status' => ArvoreResposta::ATIVO,
                ])
                ->one();

        if (!$arvoreResposta) {
            throw new HttpException(404, 'Resposta não encontrada');
        }

        return $this->render('arvore-view', ['arvoreResposta' => $arvoreResposta]);
    }

}
