<?php
require_once 'agronet/controllers/MailController.php';
require_once 'sistema/controllers/UsuarioController.php';
require_once APPLICATION_PATH. "/../library/dompdf/autoload.inc.php";

Use Dompdf\Dompdf;
use Dompdf\Options;

class CorretorController extends Agro_Controller_Action
{
    private $camposValidarFormularioExterno = [
      'ds_nome_corretor'                    => ['mensagem' => 'Nome/Razão Social não informado.'],
      'ds_nome_fantasia'                    => ['mensagem' => 'Nome Fantasia não informado.'],
      'cpf_cnpj'                            => ['mensagem' => 'CPF/CNPJ não informado.'],
      'nr_susep'                            => ['mensagem' => 'Nº SUSEP não informado.'],
      'ds_contato_seguro_agricola'          => ['mensagem' => 'Contato Seguro Agrícola não informado.'],
      'ds_email'                            => ['mensagem' => 'E-mail Principal não informado.'],
      'ds_telefone_contato_seguro_agricola' => ['mensagem' => 'Telefone Seguro Agrícola não informado.'],
      'ds_nome_responsavel'                 => ['mensagem' => 'Corretor Responsável não informado.'],
      'ds_email_responsavel'                => ['mensagem' => 'E-mail do Responsável não informado.'],
      'ds_telefone_responsavel'             => ['mensagem' => 'Telefone do Responsável não informado.'],
      'ds_endereco_cep'                     => ['mensagem' => 'CEP não informado.'],
      'id_estado'                           => ['mensagem' => 'Estado não informado.'],
      'id_municipio'                        => ['mensagem' => 'Município não informado.'],
      'ds_endereco_bairro'                  => ['mensagem' => 'Bairro não informado.'],
      'ds_endereco_rua'                     => ['mensagem' => 'Endereço não informado.'],
      'ds_endereco_nro'                     => ['mensagem' => 'Número do Endereço não informado.'],
      'cpf_responsavel'                     => ['mensagem' => 'CPF do Responsável Técnico não informado'],
      'cpf_contato_seguro_agricola'         => ['mensagem' => 'CPF do Contato Seguro Agrícola não informado'],
    ];

    private $errosFormularioExterno = [];

    public function dadosenderecoAction()
    {
        $this->isAjax();

        $retorno = ['endereco' => null];
        $modelCorretoresEnderecos = new Sistema_Model_CorretoresEnderecos();
        $rows = $modelCorretoresEnderecos->getEnderecosFromCorretor($this->getRequest()->getParam('id_corretor'))->toArray();

        if (!empty($rows)) {
            $retorno['endereco'] = $rows[0];
        }

        $this->getResponse()->setBody(Zend_Json::encode($retorno));
    }

    public function formAction()
    {
        $this->view->erro = false;
        $parametros = $this->getRequest()->getParams();
        $hash = $parametros['hash'];
        $mensagem = "Link inválido ou expirado. Entre em contato com o atendimento.";

        if (empty($hash)) {
            $this->view->erro = true;
            $this->view->mensagem = $mensagem;

            return;
        }

        $modelCorretores = new Sistema_Model_Corretores();
        $this->view->hash = $hash;
        $row = $modelCorretores->getDadosCorretorByHash($hash);

        if (empty($row)) {
            $this->view->erro = true;
            $this->view->mensagem = $mensagem;

            return;
        }

        $dados = $row->toArray();
        $diasEntreDatas = abs(Agro_Util::contarDiasEntreDatas($dados['dt_url_cadastro'], date('Y-m-d')));

        if ($diasEntreDatas > 7) {
            $this->view->erro = true;
            $this->view->mensagem = $mensagem;

            return;
        }

        $this->view->form = $this->getForm();
        $this->view->form->populate($dados);
    }

    public function gerarsenhaAction()
    {
        $this->isAjax();
        $this->getResponse()->setBody(Zend_Json::encode(['senha' => (new Agro_Senha())->gerarNovaSenha()]));
    }

    public function getForm()
    {
        $this->view->formEndereco = new Default_Form_CorretorEndereco();

        return new Default_Form_Corretor();
    }

    public function getModel()
    {
        return new Sistema_Model_Corretores();
    }

    public function getmunicipiosAction()
    {
        $this->isAjax();

        $modelMunicipios = new Sistema_Model_Municipios();
        $rs = false;

        if ($this->getRequest()->getParam('id_estado')) {
            $arEstados = explode(',', $this->getRequest()->getParam('id_estado'));
            if (count($arEstados) > 1) {
                $rs = $modelMunicipios->getCombo($arEstados);
            } else {
                $rs = $modelMunicipios->getCombo($this->getRequest()->getParam('id_estado'));
            }
        } else {
            if ($this->getRequest()->getParam('ds_sigla')) {
                $rs = $modelMunicipios->getComboSigla($this->getRequest()->getParam('ds_sigla'));
            }
        }

        if ($rs) {
            $this->getResponse()->setBody(Zend_Json::encode($rs));
        }
    }

    public function init()
    {
        $this->getHelper('layout')->setLayout('popup');
    }

    public function salvarAction()
    {
        $this->isAjax();
        $retorno = ['erro' => false, 'mensagem' => 'Dados salvos com sucesso.', 'erros' => []];

        $parametros = $this->getRequest()->getParams();
        $this->validarCampos($parametros);

        if (!empty($this->errosFormularioExterno)) {
            if (isset($this->errosFormularioExterno['ds_senha']) && is_array($this->errosFormularioExterno['ds_senha'])) {
                $errosSenha = [];

                foreach ($this->errosFormularioExterno['ds_senha'] as $tipoErro => $erro) {
                    $errosSenha[] = $erro['mensagem'];
                }

                $this->errosFormularioExterno['ds_senha'] = $errosSenha;
            }

            $retorno['erro'] = true;
            $retorno['mensagem'] = 'Erro ao salvar os dados.';
            $retorno['erros'] = $this->errosFormularioExterno;
        } else {
            $modelStatus = new Sistema_Model_Status();

            if (!empty($parametros['id'])) {
                $idStatusAnalise = $modelStatus->getIdStatus(
                  Sistema_Model_Status::CORRETOR_EM_ANALISE, Sistema_Model_Tipostatus::CORRETOR
                );

                $idStatusConcluido = $modelStatus->getIdStatus(
                  Sistema_Model_Status::CORRETOR_CONCLUIDO_FINALIZADO, Sistema_Model_Tipostatus::CORRETOR
                );

                $rowCorretor = $this->getModel()->getRow($parametros['id'])->toArray();

                if (!in_array($rowCorretor['id_status'], [$idStatusAnalise, $idStatusConcluido])) {
                    $parametros['id_status'] = $modelStatus->getIdStatus(
                      Sistema_Model_Status::CORRETOR_EM_ANDAMENTO, Sistema_Model_Tipostatus::CORRETOR
                    );
                }
            }

            $parametros['fl_ativo'] = true;

            $this->salvarEndereco($parametros);
            $this->getModel()->save($parametros);
        }

        $this->getResponse()->setBody(Zend_Json::encode($retorno));
    }

    public function salvarEndereco(array $dados)
    {
        $dados['corretor'] = $dados['id'];
        $dados['id'] = $dados['id_endereco'];
        $dados['id_usuario_criacao'] = $dados['id_usuario'];

        $adapter = Agro_Db_Table_Abstract::getDefaultAdapter();
        $adapter->beginTransaction();

        try {
            $modelCorretoresEnderecos = new Sistema_Model_CorretoresEnderecos();
            $modelCorretoresEnderecos->save($dados);

            $adapter->commit();
        } catch (Exception $erro) {
            $adapter->rollback();
        }
    }

    private function validarCampos(array $dados)
    {
        foreach ($dados as $campo => $valor) {
            if (isset($this->camposValidarFormularioExterno[$campo]) && empty($valor)) {
                $this->errosFormularioExterno[$campo] = $this->camposValidarFormularioExterno[$campo]['mensagem'];
            }
        }

        $this->validarSenhas($dados['ds_senha'], $dados['ds_senha2']);
    }

    private function validarSenhas(string $senha1, string $senha2): bool
    {
        if (empty($senha1) || empty($senha2)) {
            $this->errosFormularioExterno['ds_senha'] = 'Senha e/ou confirmação da senha não informada.';

            return false;
        }

        if ($senha1 !== $senha2) {
            $this->errosFormularioExterno['ds_senha'] = 'As senhas devem ser iguais.';

            return false;
        }

        $agroSenha = new Agro_Senha();
        $senhaValida = $agroSenha->validarSenha($senha1, $senha2);
        $this->isAjax();

        if (!$senhaValida) {
            $this->errosFormularioExterno['ds_senha'] = $agroSenha->getErrosSenha();
        }

        return $senhaValida;
    }

    public function salvararquivoAction()
    {
        $this->isAjax();

        $post = $this->getRequest()->getParams();

        // Obtém o arquivo do upload
        $file = $_FILES['arquivo'];
        $db = Agro_Db_Table_Abstract::getDefaultAdapter();
        $db->beginTransaction();

        try {
            $idCorretor = !Agro_Util::filterVariable($post['id_corretor'])
                ? 0
                : (int)$post['id_corretor'];
            $idTipoArquivo = !Agro_Util::filterVariable($post['id_tipo_arquivo'])
                ? 0
                : (int)$post['id_tipo_arquivo'];
            $idUsuarioCriacao = !Agro_Util::filterVariable($post['id_usuario_criacao'])
                ? 0
                : (int)$post['id_usuario_criacao'];
            
            // Gera o nome do novo arquivo
            $tipoArquivoCorretor = new Sistema_Model_TipoArquivoCorretor();
            $tipo = $tipoArquivoCorretor->fetchRow($tipoArquivoCorretor->getAdapter()->quoteInto(
                'id = ?',
                $idTipoArquivo
            ))->toArray();

            $corretorArquivo = new Sistema_Model_CorretoresArquivos();
            $id = $corretorArquivo->nextSequenceId();

            if (!is_int($idCorretor)) {
                throw new Exception('Erro ao salvar arquivo.');
            }

            $extensao = strtolower(end(explode('.', $file['name'])));

            if (Agro_File::isInvalidExtension($extensao)) {
                throw new TypeError('Extensão de arquivo inválida.');
            }
            
            $nomeArquivo = "{$idCorretor}-{$id}-{$tipo['ds_chave_tipo_arquivo']}.$extensao";

            $target = APPLICATION_PATH . '/upload_files/corretores/' . $nomeArquivo;

            if (copy($file['tmp_name'], $target)) {
                // Salva registro na tabela corretores_arquivos
                $data = array();
                $data['id'] = $id;
                $data['id_corretor'] = $idCorretor;
                $data['id_tipo_arquivo'] = $idTipoArquivo;
                $data['ds_nome_arquivo'] = $nomeArquivo;
                $data['id_usuario_criacao'] = $idUsuarioCriacao;

                $corretorArquivo->save($data);

                $dadosCorretor = [
                  'id' => $idCorretor,
                  'fl_ativo' => true,
                ];

                $modelCorretores = new Sistema_Model_Corretores();
                $modelCorretores->salvarCorretor($dadosCorretor);

                $db->commit();

                $this->getResponse()->setBody('');
            }
        } catch (Throwable $e) {
            $db->rollback();
            $this->view->showMessage(MSG_ERROR . "<br />" . $e->getMessage(), 'error');
        }
    }

    public function listararquivosAction()
    {
        $this->isAjax();
        $parametros = $this->getRequest()->getParams();
        $retorno = ['arquivos' => []];

        $corretorArquivo = new Sistema_Model_CorretoresArquivos();
        $arquivos = $corretorArquivo->getCorretorArquivos($parametros['id']);

        foreach ($arquivos as $indice => $arquivo) {
            $retorno['arquivos'][$indice] = [
              'id'              => $arquivo['id'],
              'ds_tipo_arquivo' => $arquivo['ds_tipo_arquivo'],
              'data_cadastro'   => Agro_Util::formatDate($arquivo['dt_criacao']),
              'ds_nome_arquivo' => $arquivo['ds_nome_arquivo'],
            ];
        }

        $this->getResponse()->setBody(Zend_Json::encode($retorno));
    }

    public function deletararquivoAction()
    {
        $this->isAjax();

        $model = new Sistema_Model_CorretoresArquivos();
        $Row = $model->getRow($this->getRequest()->getParam('id'));

        if ($model->delete($this->getRequest()->getParam('id'))) {
            $sanitizedPath = APPLICATION_PATH . '/upload_files/corretores/' . $Row->ds_nome_arquivo;
            
            if (file_exists($sanitizedPath)) {
                @unlink($sanitizedPath);
            }

            $return['message'] = 'Documento excluído com sucesso!';
            $return['id'] = $this->getRequest()->getParam('id_corretor');

            $this->getResponse()->setBody(Zend_Json::encode($return));
        } else {
            $return['message'] = 'Erro ao excluir documento!';
        }
    }

    public function enviarcadastroAction()
    {
        $this->isAjax();
        $retorno = ['erro' => false, 'mensagem' => 'Procedimento concluído com sucesso.'];
        $parametros = $this->getRequest()->getParams();

        $adapter = Agro_Db_Table_Abstract::getDefaultAdapter();
        $adapter->beginTransaction();

        try {
            $modelStatus = new Sistema_Model_Status();

            $this->getModel()->salvarCorretor(
              [
                'id' => $parametros['id_corretor'],
                'id_status' => $modelStatus->getIdStatus(
                  Sistema_Model_Status::CORRETOR_EM_ANALISE, Sistema_Model_Tipostatus::CORRETOR
                ),
                'dt_url_cadastro' => null,
                'ds_url_cadastro' => '',
              ]
            );

            $this->view->setScriptPath(APPLICATION_PATH . '/modules/sistema/views/scripts/');
            $this->view->ds_nome_corretor = $parametros['ds_nome_corretor'];
            $assunto = "Cadastro de Corretor - AgroNet® 2.0";
            $conteudo = $this->view->render('corretor/emailcadastrofinalizado.phtml');
            $this->view->setScriptPath(APPLICATION_PATH . '/modules/default/views/scripts/');

            $mailController = new Agronet_MailController($this->getRequest(), $this->getResponse());
            $mailController->inicioTextoPadrao(false);
            $mailController->enviarEmail('atendimento@agrobrasilseguros.com.br', $assunto, $conteudo);

            $adapter->commit();

            $this->isAjax();
        } catch (Exception $erro) {
            $adapter->rollback();
            $retorno = ['erro' => true, 'mensagem' => 'Erro ao enviar o cadastro.'];
        }

        $this->getResponse()->setBody(Zend_Json::encode($retorno));
    }

    public function declaracaocorretorAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $parametros = $this->getRequest()->getParams();

        $idCorretor = !Agro_Util::filterVariable($parametros['id_corretor'])
            ? 0
            : (int)$parametros['id_corretor'];

        $modelCorretores = new Sistema_Model_Corretores();
        $this->view->dados = $modelCorretores->find($idCorretor)->current()->toArray();

        $this->view->setScriptPath(APPLICATION_PATH . '/modules/sistema/views/scripts/');
        $html = $this->view->render('corretor/pdfdeclaracao.phtml');

        $dompdf = new Dompdf(array('isRemoteEnabled' => true));
        $html = preg_replace('/>\s+</', '><', $html);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $output = $dompdf->output();
        $nomeArquivo = "declaracao_corretor_{$idCorretor}.pdf";
        $arquivo = APPLICATION_PATH . "/upload_files/corretores/declaracao_corretor_{$idCorretor}.pdf";

        file_put_contents($arquivo, $output);

        if (file_exists($arquivo)) {
            $data = file_get_contents($arquivo);
            $size = filesize($arquivo);

            $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
            $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo, true);
            $this->getResponse()->setHeader('Content-Length', $size, true);
            $this->getResponse()->setHeader('Pragma', 'no-cache', true);
            $this->getResponse()->setBody($data);
            $this->getResponse()->sendResponse();
        }
    }
}
