<?php
require_once 'UsuarioController.php';
require_once 'agronet/controllers/MailController.php';

class Sistema_CorretorController extends Agro_Controller_Action {
	public $_backAfterSave = false;

	public function init() {
		$this->view->title = 'Sistema » Cadastro » Corretores';
	}

	public function setBack() {
		$this->view->back = '/sistema/corretor';

        if (Zend_Auth::getInstance()->getIdentity()->tp_usuario === Sistema_Model_Usuarios::TIPO_USUARIO_CORRETOR) {
            $this->view->back = '';
        }
	}

	public function formAction() {
	    $parametros = $this->getRequest()->getParams();

	    if (isset($parametros['salvar']) && empty($parametros['id'])) {
	        if (empty($parametros['ds_nome_fantasia'])) {
                $parametros['ds_nome_fantasia'] = $parametros['ds_nome_corretor'];
            }

            $modelStatus = new Sistema_Model_Status();
            $parametros['id_status'] = $modelStatus->getIdStatus(
              Sistema_Model_Status::CORRETOR_CADASTRO_INICIAL, Sistema_Model_Tipostatus::CORRETOR
            );

            $agroSenha = new Agro_Senha();

            if (empty($parametros['ds_senha'])) {
                $parametros['ds_senha'] = $parametros['ds_senha2'] = $agroSenha->gerarNovaSenha();
            }

            $parametros['dt_url_cadastro'] = Agro_Util::formatDate(date('Y-m-d'), Zend_Date::W3C);
            $parametros['ds_url_cadastro'] = $agroSenha->gerarHash();
            $parametros['fl_ativo'] = false;

            $this->getRequest()->setParams($parametros);
        }

        if (!empty(trim($this->getRequest()->getParam('ds_senha')))) {
            $this->getRequest()->setParam('validarSenha', true);
        }

		parent::formAction();
        $this->setBack();
		$params = $this->getRequest()->getParams();

		$this->view->relatorios = array();
		if (isset($params['id']) && !empty($params['id'])) {
			$acoesModel = new Sistema_Model_Acoes();
			$corretorModel = new Sistema_Model_Corretores();
			$corretor = $corretorModel->getRow($params['id']);
			$this->view->relatorios = $acoesModel->getRelatoriosByUser($corretor->id_usuario)->toArray();
			$this->view->relatoriosUsuario = $acoesModel->getRelatoriosUsuarioSenhaByUser($corretor->id_usuario)->toArray();
		}
	}

	public function getForm() {
		$Model = $this->getModel();

		$this->view->formTelefone = new Sistema_Form_Telefone();
		$this->view->formEndereco = new Sistema_Form_CorretorEndereco();
		$this->view->formInformacoesBancarias = new Sistema_Form_InformacoesBancarias();

		return new Sistema_Form_Corretor();
	}

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

	public function viewAction() {
		$Model = $this->getModel();

		$this->view->title .= ' » Visualização';
		$this->view->data = $this->getRow();

		$this->view->telefones = $Model->getTelefones($this->view->data['id_usuario']);
		$this->view->prepostos = $Model->getPrepostos($this->view->data['id']);
		$this->view->informacoes_bancarias = $Model->getInformacoesBancarias($this->view->data['id']);
		$this->view->enderecos = $Model->getEnderecos($this->view->data['id']);

		parent::viewAction();
	}


	public function getFilter() {
		$where = array();

		if ($this->getRequest()->getParam('ds_nome_fantasia')) {
			$where[] = array(
				'field' => 'c.ds_nome_fantasia',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_fantasia').'%'
			);
		}

		if ($this->getRequest()->getParam('ds_razao_social')) {
			$where[] = array(
				'field' => 'c.ds_nome_corretor',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_razao_social').'%'
			);
		}

		if ($this->getRequest()->getParam('ds_nome_abreviado')) {
			$where[] = array(
				'field' => 'c.ds_nome_abreviado',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_abreviado').'%'
			);
		}

		if ($this->getRequest()->getParam('id_estado')) {
			$where[] = array(
				'field' => 'id_estado',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_estado')
			);
		}

		if ($this->getRequest()->getParam('id_municipio')) {
			$where[] = array(
				'field' => 'id_municipio',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_municipio')
			);
		}

		if ($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array(
				'field' => 'c.fl_ativo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}

		if ($this->getRequest()->getParam('id_comercial')) {
			$where[] = array(
				'field' => 'c.id_comercial',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_comercial')
			);
		}

		if ($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array (
				'field' => 'c.fl_ativo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}

        if ($this->getRequest()->getParam('cpf_cnpj')) {
            $where[] = array (
                'field' => 'c.cpf_cnpj',
                'operator' => '=',
                'value' => $this->getRequest()->getParam('cpf_cnpj')
            );
        }

        if ($this->getRequest()->getParam('id_status_cadastro')) {
            $where[] = array (
                'field' => 'cor.id_status',
                'operator' => '=',
                'value' => $this->getRequest()->getParam('id_status_cadastro')
            );
        }

		return $where;
	}

	public function getprepostosAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$id = $this->getRequest()->getParam('id_usuario');

		$Corretores = new Sistema_Model_Corretores();
		$row = $Corretores->fetchRow("id_usuario = $id");

		$Prepostos = new Sistema_Model_Prepostos();
		$combo = $Prepostos->getCombo($row['id']);

		$opt = array();
		if (is_array($combo)) {
			foreach ($combo as $key => $text) {
				$opt[] = array('id'=>$key,'label'=>$text);
			}
		}

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

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

		$Prepostos = new Sistema_Model_Prepostos();
		$combo = $Prepostos->getComboUsuario($this->getRequest()->getParam('id'));

		$opt = array();
		if (is_array($combo)) {
			foreach ($combo as $key => $text) {
				$opt[] = array('id'=>$key,'label'=>$text);
			}
		}

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

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

		$Prepostos = new Sistema_Model_Prepostos();
		$Corretores = new Sistema_Model_Corretores();

		$Corretor = $Corretores->fetchRow("id_usuario={$this->getRequest()->getParam('id')}");

		$combo = $Prepostos->fetchPairs("id_usuario", "ds_nome_preposto", false, false, 1, "id_corretor=$Corretor->id");

		$opt = array();
		if (is_array($combo)) {
			foreach ($combo as $key => $text) {
				$opt[] = array('id'=>$key,'label'=>$text);
			}
		}

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

	}

	public function enderecosAction() {
		$CorretoresEnderecos = new Sistema_Model_CorretoresEnderecos();
		$Corretor = new Sistema_Model_Corretores();
		$row = $Corretor->getViewId($this->getRequest()->getParam('id'));
		$this->view->title = "Gerência de Corretores » {$row['ds_nome_corretor']} » Endereços";
		$this->view->back = '/sistema/corretor';
		$this->view->form = new Sistema_Form_CorretorEndereco();

		if ($this->getRequest()->isPost() && count($this->getRequest()->getPost())) {
			$this->saveEnderecos($this->getRequest()->getPost());
		}

		$where[] = array(
			'field' => 'id_corretor',
			'operator' => '=',
			'value' => $this->getRequest()->getParam('id')
		);

		$this->view->paginator = $CorretoresEnderecos->fetchAllPaginator($where, $this->getPageCache());
	}

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

		$Corretores = new Sistema_Model_Corretores();
		$Usuarios = new Sistema_Model_Usuarios();
		$Prepostos = new Sistema_Model_Prepostos();

		$Corretor = $Corretores->find($this->getRequest()->getParam('id'))->current();
		$Usuario = $Usuarios->find($Corretor->id_usuario)->current();

		$Corretor->fl_ativo = ($Corretor->fl_ativo ? 0 : 1);
		$Usuario->fl_ativo = $Corretor->fl_ativo;

		if($Corretor->fl_ativo == 0){
		    $Prepostos->desativaPrepostos($this->getRequest()->getParam('id'));
		}

		$img = ($Usuario->fl_ativo ? 'active.png' : 'inactive.png');

		if ($Usuario->save() && $Corretor->save()) {
			$result['ativo'] = $Corretor->fl_ativo;

			// adiciona o cara nos grupos de capacidade qndo é ativado.
			$CapacidadeUsuario = new Produto_Model_ValidacoesCapacidadeUsuarios();
			$CapacidadeUsuario->addCorretorPreposto($Corretor->id_usuario);

			$this->getResponse()->setBody(Zend_Json::encode($result));
		} else {
			$this->view->message(MSG_ERROR, 'error');
		}
	}

	public function afterSave($id) {
	    $parametros = $this->getRequest()->getParams();
        
        $modelStatus = new Sistema_Model_Status();
		$model = $this->getModel();
        $Row = $model->find($id)->current()->toArray();

        $idStatusCadastroInicial = $modelStatus->getIdStatus(
            Sistema_Model_Status::CORRETOR_CADASTRO_INICIAL, Sistema_Model_Tipostatus::CORRETOR
        );

        if ($Row['id_status'] === $idStatusCadastroInicial) {

            if (!array_key_exists('ds_url_cadastro', $parametros)) {
                $parametros['ds_url_cadastro'] = $Row['ds_url_cadastro'];
            }

            $this->enviarEmailParaCorretor(
              Sistema_Model_Status::CORRETOR_CADASTRO_INICIAL,
              $parametros
            );
        }

        if (!empty($parametros['ds_endereco_cep'])) {
            $this->salvarEndereco($parametros);
        }

        if ($parametros['periodo_cadastro_anual']) {
            $modelCorretoresPeriodoCadastroAnual = new Sistema_Model_CorretoresPeriodoCadastroAnual();
            $modelCorretoresPeriodoCadastroAnual->save(
              ['id_corretor' => $parametros['id'], 'fl_cadastro_inalterado' => $parametros['fl_cadastro_inalterado']]
            );

            
            $idStatusAtualizacaoCadastro = $modelStatus->getIdStatus(
              Sistema_Model_Status::CORRETOR_ATUALIZACAO_CADASTRO, Sistema_Model_Tipostatus::CORRETOR
            );

            if ($Row['id_status'] === $idStatusAtualizacaoCadastro) {
                $parametros['id_status'] = $modelStatus->getIdStatus(
                  Sistema_Model_Status::CORRETOR_EM_ANDAMENTO, Sistema_Model_Tipostatus::CORRETOR
                );

                $model->salvarCorretor($parametros);

                $this->enviarEmailParaCorretor(
                  Sistema_Model_Status::CORRETOR_EM_ANDAMENTO,
                  $parametros
                );
            }

            $this->view->form->getElement('fl_cadastro_inalterado')->setValue(
                (bool)$parametros['fl_cadastro_inalterado']
            );
        }

        $modelPrepostos = new Sistema_Model_Prepostos();
        $modelPrepostos->atualizarIdComercialCorretor($id, $Row['id_comercial']);

        $this->view->form->populate($Row);
	}

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

        if ($this->getRequest()->getParam('id_usuario')) {
            $ProdutoHabilitacoes = new Produto_Model_Habilitacoes();
            $ProdutoHabilitacoes->desabilitaByCorretor($this->getRequest()->getParam('id_usuario'));
        }

        $result = array();
        $this->getResponse()->setBody(Zend_Json::encode($result));
    }

    public function beforeSave() {
        $params = $this->getRequest()->getPost();

        $modelUsuarios = new Sistema_Model_Usuarios();
        $rowUsuario = $modelUsuarios->getUsuarioByNomeUsuario($params['ds_nome_usuario']);

        if (
          !empty($rowUsuario)
          && $rowUsuario['ds_nome_usuario'] === $params['ds_nome_usuario']
          && $rowUsuario['id'] != $params['id_usuario']
        ) {
            throw new \Exception('Nome de usuário já cadastrado.', 403);
        }

        $this->validarUsuario($params);
    }

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

        ini_set('memory_limit', '4096M');
        ini_set('max_execution_time', 360);

        $modelAtendimento = new Relatorio_Model_Atendimento();
        $Rs = $this->getModel()->fetchAll($this->getModel()->getData($this->getFilter()));
        $arr = [];
        $aux = 0;
        $numeroMaximoComerciais = 0;

        foreach ($Rs as $Row) {
            $arr[$aux]['id'] = $Row['id'];
            $arr[$aux]['ds_nome_fantasia'] = $Row['ds_nome_fantasia'];
            $arr[$aux]['ds_nome_abreviado'] = $Row['ds_nome_abreviado'];
            $arr[$aux]['id_usuario'] = $Row['id_usuario'];
            $arr[$aux]['ds_nome_usuario'] = $Row['ds_nome_usuario'];
            $arr[$aux]['ds_nome_municipio'] = $Row['ds_nome_municipio'];
            $arr[$aux]['ds_sigla'] = $Row['ds_sigla'];
            $arr[$aux]['ds_nome_responsavel'] = $Row['ds_nome_responsavel'];
            $arr[$aux]['telefones_lista'] = $Row['telefones_lista'];
            $arr[$aux]['ds_email'] = $Row['ds_email'];
            $arr[$aux]['ativo'] = $Row['ativo'];

            $Rs_corr = $modelAtendimento->getComerciais($Row['id']);

            $i = 0;
            foreach ($Rs_corr as $row2) {
                $arr[$aux]['corr_' . $i] = $row2['ds_nome_funcionario'];
                $i++;
            }

            $aux++;
            $numeroMaximoComerciais = $i > $numeroMaximoComerciais ? $i : $numeroMaximoComerciais;
        }

        $titles = $this->getModel()->_columnExcel;

        $contadorComercial = 1;
        for ($i = 0; $i < $numeroMaximoComerciais; $i++) {
            $titles["corr_{$i}"] = "Comercial {$contadorComercial}";
            $contadorComercial++;
        }

        if ($this->getModel()->_columnExcel) {
            $Csv = new Agro_Plugin_Rs2Csv();
            $Csv->setTitles($titles);
            $Csv->setRecordSet($arr);
            $Csv->setType("application/octet-stream");
            $Csv->setFileName("pesquisa.csv");
            $Csv->setDisposition("attachment");
            $Csv->setSeparator(";");
            $Csv->getCsv();
        } else {
            $Csv = new Agro_Plugin_Rs2Csv();
            $Csv->setTitles($this->getModel()->_columnExcel);
            $Csv->setRecordSet(array('Excel não configurado'));
            $Csv->setType("application/octet-stream");
            $Csv->setFileName("notfound.csv");
            $Csv->setDisposition("attachment");
            $Csv->setSeparator(";");
            $Csv->getCsv();
        }
    }

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

        $retorno = [];

        $modelStatus = new Sistema_Model_Status();
        $retorno['status'] = $modelStatus->getComboStatusArquivos(Sistema_Model_Tipostatus::CORRETOR);

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

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

        $retorno = ['erro' => false, 'mensagem' => 'Status salvo com sucesso.'];

        Agro_Db_Table_Abstract::getDefaultAdapter()->beginTransaction();

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

            if ($parametros['status_chave'] === Sistema_Model_Status::CORRETOR_CADASTRO_INICIAL) {
                $parametros['dt_url_cadastro'] = Agro_Util::formatDate(date('Y-m-d'), Zend_Date::W3C);
                $parametros['ds_url_cadastro'] = (new Agro_Senha())->gerarHash();

                $this->isAjax();
            }

            if ($parametros['status_chave'] === Sistema_Model_Status::CORRETOR_CONCLUIDO_FINALIZADO) {
                $parametros['dt_url_cadastro'] = null;
                $parametros['ds_url_cadastro'] = '';
            }

            $row = $this->getModel()->salvarCorretor($parametros);

            $this->enviarEmailParaCorretor(
              $parametros['status_chave'],
              $row->toArray()
            );

            $this->isAjax();

            Agro_Db_Table_Abstract::getDefaultAdapter()->commit();
        } catch (Exception $erro) {
            $retorno = ['erro' => true, 'mensagem' => 'Erro ao atualizar o status.'];
            Agro_Db_Table_Abstract::getDefaultAdapter()->rollback();
        }

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

    private function enviarEmailParaCorretor(string $dsChave, array $dados)
    {
        switch ($dsChave) {
            case Sistema_Model_Status::CORRETOR_CADASTRO_INICIAL:
                $this->view->link = "http://agronet.agrobrasilseguros.com.br/default/corretor/form/hash/{$dados['ds_url_cadastro']}";
                $conteudo = $this->view->render('corretor/emailinicial.phtml');
                $assunto = "Cadastro de Corretor - AgroNet® 2.0";
                $inicioTextoPadrao = true;
                $enviarEmail = true;
                break;
            case Sistema_Model_Status::CORRETOR_AGUARDANDO_PENDENCIA:
                $this->view->observacao = $dados['ds_observacao_status'];
                $conteudo = $this->view->render('corretor/emailpendencia.phtml');
                $assunto = "Pendência no Cadastro de Corretor - AgroNet® 2.0";
                $inicioTextoPadrao = true;
                $enviarEmail = true;
                break;
            case Sistema_Model_Status::CORRETOR_EM_ANDAMENTO:
            case Sistema_Model_Status::CORRETOR_EM_ANALISE:
                $this->view->ds_nome_corretor = $dados['ds_nome_corretor'];
                $dados['ds_email'] = "atendimento@agrobrasilseguros.com.br";
                $conteudo = $this->view->render('corretor/emailcadastroanual.phtml');
                $assunto = "Cadastro Anual de Corretor - AgroNet® 2.0";
                $inicioTextoPadrao = false;
                $enviarEmail = true;
                break;
            case Sistema_Model_Status::CORRETOR_CONCLUIDO_FINALIZADO:
                $conteudo = $this->view->render('corretor/emailcadastroliberado.phtml');
                $assunto = "Cadastro Anual de Corretor - AgroNet® 2.0";
                $inicioTextoPadrao = true;
                $enviarEmail = false;

                if ($dados['fl_treinado'] === true) {
                    $enviarEmail = true;
                }
                break;
            default:
                $conteudo = '';
                $assunto = '';
                $inicioTextoPadrao = true;
                $enviarEmail = false;
                break;
        }

        if ($enviarEmail) {
            $mailController = new Agronet_MailController($this->getRequest(), $this->getResponse());
            $mailController->inicioTextoPadrao($inicioTextoPadrao);
            $mailController->enviarEmail($dados['ds_email'], $assunto, $conteudo, "Corretor");
        }
    }

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

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

    public function indexAction()
    {
        if ($this->validarUsuarioLogado()) {
            parent::indexAction();
        }
    }

    private function validarUsuarioLogado()
    {
        $user = Zend_Auth::getInstance()->getIdentity();

        if ($user->tp_usuario === Sistema_Model_Usuarios::TIPO_USUARIO_CORRETOR) {
            $modelCorretor = new Sistema_Model_Corretores();
            $rowCorretor = $modelCorretor->findByUser($user->id);

            if (!empty($rowCorretor)) {
                $this->_redirect("/sistema/corretor/form/id/{$rowCorretor['id']}");
            }

            return false;
        }

        if ($user->tp_usuario === Sistema_Model_Usuarios::TIPO_USUARIO_PREPOSTO) {
            Zend_Layout::getMvcInstance()->getView()->title = 'Erro de Permissão';
            Zend_Layout::getMvcInstance()->getView()->error = 'Você não tem permissão para acessar esta tela. Contate o administrador.';

            $this->view->setScriptPath(APPLICATION_PATH . '/modules/default/views/scripts/');

            $this->getRequest()->setModuleName('default');
            $this->getRequest()->setControllerName('error');
            $this->getRequest()->setActionName('privileges');

            return false;
        }

        return true;
    }

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

        $dadosCorretor = null;
        $rowCorretor = $this->getModel()->getUsuarioCriacaoAlteracao(
          "c.id = {$this->getRequest()->getParam('id_corretor')}"
        );

        if (!empty($rowCorretor)) {
            $dadosCorretor = $rowCorretor->toArray();

            $nomeUsuario = $dadosCorretor['ds_nome_usuario'];
            $dadosCorretor['inicial_usuario'] = preg_match('/\./', $nomeUsuario) ? substr($nomeUsuario, 0, strpos($nomeUsuario, '.')) : $nomeUsuario;
        }

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