<?php

class Sistema_CorretorarquivoController extends Agro_Controller_Action {
	protected $_paginator = false;
	
	public function getModel() {
		return new Sistema_Model_CorretoresArquivos();
	}
	
	public function getForm() {
		return new Sistema_Form_UploadArquivoCorretor();
	}
	
	
	public function getFilter() {
		$session = new Zend_Session_Namespace('corretor');
		$where = array();
		
		$where[] = array(
			'field' => 'ca.id_corretor',
			'operator' => '=',
			'value' => $this->getRequest()->getParam('id')
		);
		
		return $where;
	}

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

        $post = $this->getRequest()->getParams();
        $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'];

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

        try {
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'tiff', 'pdf', 'bpm'];
            // 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();

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

            if (!in_array(strtolower($extensao), $allowedExtensions)) {
                throw new Exception('Extensão de arquivo não permitida.');
            }

            if (!intval($idCorretor)) {
                throw new Exception('Id corretor incorreto.');
            }

            $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;

                $corretorArquivo->save($data);

                $db->commit();

                $this->validaAtualizacaoStatusCorretor($idCorretor, $idTipoArquivo);
                $this->validarStatusPendencia($idCorretor);

                $this->getResponse()->setBody(
                    '<script>window.top.window.loadDocumentos(' . $data['id_corretor'] . ');</script>'
                );
            }
        } catch (Exception $e) {
            $db->rollback();
            $this->view->showMessage(MSG_ERROR . "<br />" . $e->getMessage(), 'error');
        }
    }
	
	public function listAction(){

		$this->view->id = $this->getRequest()->getParam('id');
		
		// Busca arquivos do corretor
		$CorretorArquivo = new Sistema_Model_CorretoresArquivos();
		$this->view->data = $CorretorArquivo->getCorretorArquivos($this->getRequest()->getParam('id'));
		
		parent::listAction();
	}
	
	public function deleteAction()
    {
        $this->isAjax();
        $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
            ? 0
            : (int)$this->getRequest()->getParam('id');

        $model = new Sistema_Model_CorretoresArquivos();
        $row = $model->getRow($id);

        if ($model->delete($id)) {
            $file = realpath(APPLICATION_PATH . '/upload_files/corretores/' . $row->ds_nome_arquivo);

            if (file_exists($file)) {
                @unlink($file);
            }

            $return['message'] = 'Documento excluído com sucesso!';
            $return['id'] = $this->getRequest()->getParam('id_corretor');
        } else {
            $return['message'] = 'Erro ao excluir documento!';
        }

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

	private function validaAtualizacaoStatusCorretor(int $idCorretor, int $tipoArquivo) : bool
    {
        $corretorPeriodoCadastroAnual = (new Sistema_Model_CorretoresPeriodoCadastroAnual())->getByCorretor($idCorretor, date('Y-m-d'), false);

        if (empty($corretorPeriodoCadastroAnual) || $tipoArquivo !== Sistema_Model_TipoArquivoCorretor::RECADASTRO) {
            return false;
        }

        $modelCorretores = new Sistema_Model_Corretores();
        $dadosCorretor = $modelCorretores->find($idCorretor)->current()->toArray();

        $modelStatus = new Sistema_Model_Status();
        $idStatusEmAnalise = $modelStatus->getIdStatus(
          Sistema_Model_Status::CORRETOR_EM_ANALISE, Sistema_Model_Tipostatus::CORRETOR
        );

        $dadosCorretor['id_status'] = $idStatusEmAnalise;
        $modelCorretores->salvarCorretor($dadosCorretor);

        return true;
    }

    private function validarStatusPendencia(int $idCorretor)
    {
        $rowCorretor = (new Sistema_Model_Corretores())->find($idCorretor)->current();

        if (empty($rowCorretor)) {
            return false;
        }

        $idStatusAguardandoPendencia = (new Sistema_Model_Status())->getIdStatus(
          Sistema_Model_Status::CORRETOR_AGUARDANDO_PENDENCIA, Sistema_Model_Tipostatus::CORRETOR
        );

        if ($rowCorretor['id_status'] !== $idStatusAguardandoPendencia) {
            return false;
        }

        $this->view->ds_nome_corretor = $rowCorretor['ds_nome_corretor'];

        $agroMail = new Agro_Mail();
        $agroMail->addTo("atendimento@agrobrasilseguros.com.br");
        $agroMail->inicioTextoPadrao(false);
        $agroMail->setSubject("Pendência no Cadastro de Corretor - AgroNet® 2.0");
        $agroMail->setBody($this->view->render('corretor/emailatendimentopendencias.phtml'));
        $agroMail->send();

        return true;
    }
}
