<?php

class Sistema_TreinamentoController extends Agro_Controller_Action {
	public function init() {
		$this->view->title = 'Sistema » Cadastro » Treinamentos';
	}

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

    public function getForm()
    {
        return new Sistema_Form_Treinamento();
    }

    public function formAction()
    {
        $this->view->back = "/sistema/treinamento/index/menu/1";
        parent::formAction();
    }

    public function listAction()
    {
        parent::listAction();
        $this->view->origem = ($this->getRequest()->getParam('origem')) ? $this->getRequest()->getParam('origem') : 'treinamento';
    }

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

        if ($this->getRequest()->getParam('id_empresas')) {
            $ids = implode(', ', $this->getRequest()->getParam('id_empresas'));
            $where['id_empresas'] = "e.id in ({$ids})";
        }

        if ($this->getRequest()->getParam('id_vistoriadores')) {
            $ids = is_array($this->getRequest()->getParam('id_vistoriadores')) ? implode(', ', $this->getRequest()->getParam('id_vistoriadores')) : $this->getRequest()->getParam('id_vistoriadores');
            $where['id_vistoriadores'] = "fv.id in ({$ids})";
        }

        if ($this->getRequest()->getParam('id_agronomos')) {
            $ids = is_array($this->getRequest()->getParam('id_agronomos')) ? implode(', ', $this->getRequest()->getParam('id_agronomos')) : $this->getRequest()->getParam('id_agronomos');
            $where['id_agronomos'] = "agronomos.ids_agronomos && ARRAY[{$ids}]";
        }

        if ($this->getRequest()->getParam('id_tipo_vistoria')) {
            $idTipoVistoria = $this->getRequest()->getParam('id_tipo_vistoria');

            if (is_array($idTipoVistoria)) {
                $idTipoVistoria = implode(",", $idTipoVistoria);
            }

            $where['id_tipo_vistoria'] = "ttv.id_tipo_vistoria in ($idTipoVistoria)";
        }

        if ($this->getRequest()->getParam('id_grupamento_cultura')) {
            $idGrupamentoCultura = $this->getRequest()->getParam('id_grupamento_cultura');

            if (is_array($idGrupamentoCultura)) {
                $idGrupamentoCultura = implode(",", $idGrupamentoCultura);
            }

            $where['id_grupamento_cultura'] = "ttac.id_grupamento_cultura in ($idGrupamentoCultura)";
        }

        if ($this->getRequest()->getParam('dt_treinamento')) {
            $where['dt_treinamento'] = "t.dt_treinamento i= '{$this->getRequest()->getParam('dt_treinamento')}'";
        }

        if ($this->getRequest()->getParam('id_estados')) {
            $ids = implode(', ', $this->getRequest()->getParam('id_estados'));
            $where['id_estados'] = "m.id_estado in ({$ids})";
        }

        return $where;
    }

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

        $idsEmpresas = $this->getRequest()->getParam('idEmpresas');
        $validarTreinamento = $this->getRequest()->getParam('validarTreinamento');
        $idTipoVistoria = $this->getRequest()->getParam('idTipoVistoria');
        
        $modelFuncionarios = new Sistema_Model_Funcionarios();
        $combo = $modelFuncionarios->getComboVistoriadoresByEmpresas($idsEmpresas);
        $rowsFuncionariosTreinamentos = $modelFuncionarios->getFuncionariosTreinamentosByEmpresa($idsEmpresas)
            ->toArray();
        $result = [];
        $funcionariosTreinamentos = [];

        foreach ($rowsFuncionariosTreinamentos as $row) {
            $funcionariosTreinamentos[$row['id_funcionario']][] = $row['id_tipo_vistoria'];
        }
        
        foreach ($combo as $key => $value) {
            if ($validarTreinamento && !array_key_exists($key, $funcionariosTreinamentos)) {
                continue;
            }

            if (!empty($idTipoVistoria) && !in_array($idTipoVistoria, $funcionariosTreinamentos[$key])) {
                continue;
            }

			$result[] = array(
				'value' => $key,
				'text' => $value,
                'selected' => in_array($key, $this->getRequest()->getParam('idVistoriadores'))
			);
		}

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

    public function salvarAction()
    {
        $this->isAjax();
        $result = ['status' => true, 'message' => 'Treinamento salvo com sucesso.'];

        try {
            Agro_Db_Table_Abstract::getDefaultAdapter()->beginTransaction();
            $params = $this->getRequest()->getParams();
            
            if (empty($params['id_vistoriadores'])) {
                throw new Exception("Nenhum vistoriador informado.");
            }

            if (empty($params['id_tipo_vistoria'])) {
                throw new Exception("Nenhum tipo de vistoria informado.");
            }

            if (empty($params['id_grupamento_cultura'])) {
                throw new Exception("Nenhum grupo de cultura informado.");
            }

            if (empty($params['id_agronomos'])) {
                throw new Exception("Nenhum agrônomo informado.");
            }

            if (empty($params['dt_treinamento'])) {
                throw new Exception("Data do treinamento não informada.");
            }

            if (empty($params['ds_local_treinamento'])) {
                throw new Exception("Local de treinamento não informado.");
            }
            
            if (empty($params['ds_assuntos_abordados'])) {
                throw new Exception("Assuntos abordados não informados.");
            }
            $modelTreinamentos = new Sistema_Model_Treinamentos();

            $vistoriadoresAnteriores = [];
            if (!empty($params['id'])) {
                $vistoriadoresAnteriores = $modelTreinamentos->getVistoriadoresByTreinamento($params['id']);
            }
           
            $modelTreinamentos->save($params);

            $vistoriadores = array_merge($params['id_vistoriadores'], $vistoriadoresAnteriores);
            $this->validarLiberacaoPreviaDigital($vistoriadores);

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

        } catch (\Throwable $th) {
            Agro_Db_Table_Abstract::getDefaultAdapter()->rollBack();
            $result['status'] = false;
            $result['message'] = $th->getMessage();
        }

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

    private function validarLiberacaoPreviaDigital(array $vistoriadores)
    {
        $modelUsuario = new Sistema_Model_Usuarios();
        $modelFuncionarios = new Sistema_Model_Funcionarios();
        $modelVistoriadoresAuxiliares = new Sistema_Model_VistoriadoresAuxiliares();

        $rs = $modelVistoriadoresAuxiliares->getVistoriadoresTreinamento($vistoriadores);
        
        foreach ($rs as $vistoriador) {
            $treinado = $vistoriador['fl_possui_treinamento'] ? 't' : 'f';

            $rowUsuario = $modelUsuario->getRow($vistoriador['id_usuario']);
            $rowUsuario->fl_liberado_tablet_previa = $treinado;
            $rowUsuario->deviceid = $rowUsuario->deviceid;
            $rowUsuario->save();

            $modelFuncionarios->treinado($vistoriador['id'], $vistoriador['fl_possui_treinamento']);
        }
    }

    public function deleteAction()
    {
        $this->isAjax();
        try {
            Agro_Db_Table_Abstract::getDefaultAdapter()->beginTransaction();

            if (empty($this->getRequest()->getParam('id'))) {
                throw new Exception("ID do treinamento não informado.");
            }

            $idTreinamento = $this->getRequest()->getParam('id');
            $modelTreinamento = $this->getModel();
            $modelTreinamentoVistorias = new Sistema_Model_TreinamentoVistorias();
            $modelTreinamentosTiposVistorias = new Sistema_Model_TreinamentosTiposVistoria();
            $modelTreinamentosTipoGrupamentoCulturas = new Sistema_Model_TreinamentosTipoGrupamentoCulturas();
            $modelTreinamentosArquivos = new Sistema_Model_TreinamentosArquivos();

            $vistoriadoresAnteriores = $modelTreinamento->getVistoriadoresByTreinamento($idTreinamento);

            if (!$modelTreinamentosArquivos->deleteByTreinamento($idTreinamento)) {
                throw new Exception("Erro ao excluir as fotos do treinamento.");
            }
            
            if (!$modelTreinamentoVistorias->delete($idTreinamento, 'id_treinamento')) {
                throw new Exception("Erro ao excluir o vínculo com os vistoriadores.");
            }
            
            if (!$modelTreinamentosTiposVistorias->delete($idTreinamento, 'id_treinamento')) {
                throw new Exception("Erro ao excluir o vínculo com o tipo de vistoria.");
            }
            
            if (!$modelTreinamentosTipoGrupamentoCulturas->delete($idTreinamento, 'id_treinamento')) {
                throw new Exception("Erro ao excluir o vínculo com o grupo de cultura.");
            }

            if (!$modelTreinamento->delete($idTreinamento)) {
                throw new Exception("Erro ao excluir o treinamento.");
            }

            $this->validarLiberacaoPreviaDigital($vistoriadoresAnteriores);

            $result['message'] = "Treinamento excluído com sucesso.";
            $result['status'] = true;

            Agro_Db_Table_Abstract::getDefaultAdapter()->commit();
        } catch (\Throwable $th) {
            Agro_Db_Table_Abstract::getDefaultAdapter()->rollBack();
            $result['status'] = false;
            $result['message'] = $th->getMessage();
        }

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

    public function fotosAction()
    {
        $this->isAjax(true);
        $modelTreinamentosArquivos = new Sistema_Model_TreinamentosArquivos();
        $this->view->id_treinamento = $this->getRequest()->getParam('id');
        $this->view->origem = $this->getRequest()->getParam('origem');
        $this->view->fotos = $modelTreinamentosArquivos->getArquivosByTreinamento($this->getRequest()->getParam('id'));
    }

    public function adicionarfotosAction()
    {
        $this->isAjax();
        $return = ['status' => true, 'message' => 'Salvo com sucesso.'];

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

            $modelTreinamentosArquivos = new Sistema_Model_TreinamentosArquivos();
            $params = $this->getRequest()->getParams();
            $nomesArquivos = [];
            $idTreinamento = !Agro_Util::filterVariable($params['id_treinamento'])
                ? 0
                : (int)$params['id_treinamento'];

            if (empty($idTreinamento)) {
                throw new Exception("ID do treinamento não informado.");
            }

            if (empty($_FILES)) {
                throw new Exception("Ao menos um arquivo deve ser informado.");
            }

            $diretorio = Sistema_Model_TreinamentosArquivos::FILE_PATH;

            if (!file_exists($diretorio)) {
                mkdir($diretorio, '0755', true);
            }

            $adapter = new Zend_File_Transfer_Adapter_Http();
            $adapter->setDestination($diretorio);
            $adapter->addValidator('Extension', false, ['png', 'jpg', 'jpeg', 'jfif']);

            if (!$adapter->isValid()) {
                throw new Exception("Formato de arquivo inválido (formato aceito: PNG, JPG, JPEG ou JFIF).");
            }

            $contadorArquivos = 0;
            $files = $adapter->getFileInfo();

            foreach ($files as $file) {
                $hash = time() + $contadorArquivos;
                $nomeArquivo = $idTreinamento . '_' . $hash . '_' . $file['name'];

                if (!copy($file['tmp_name'], $diretorio . "/" . $nomeArquivo)) {
                    throw new Exception("Não foi possível copiar o arquivo {$file['name']} para a pasta.");
                }

                $params['ds_nome_arquivo'] = $nomeArquivo;
                $nomesArquivos[] = $nomeArquivo;

                $modelTreinamentosArquivos->save($params);
                $contadorArquivos++;
            }

            Agro_Db_Table_Abstract::getDefaultAdapter()->commit();
        } catch (\Throwable $th) {
            foreach ($nomesArquivos as $nomeArquivo) {
                if (file_exists(Sistema_Model_TreinamentosArquivos::FILE_PATH . "/" . $nomeArquivo)) {
                    unlink(Sistema_Model_TreinamentosArquivos::FILE_PATH . "/" . $nomeArquivo);
                }
            }

            $return['status'] = false;
            $return['message'] = $th->getMessage();
            Agro_Db_Table_Abstract::getDefaultAdapter()->rollBack();
        }

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

    public function deletarfotoAction()
    {
        $this->isAjax();
        $return = ['status'=> true, 'message' => 'Excluído com sucesso.'];

        try {
            Agro_Db_Table_Abstract::getDefaultAdapter()->beginTransaction();
            $params = $this->getRequest()->getParams();

            if (empty($params['id'])) {
                throw new Exception("ID do arquivo não informado.");
            }
            
            $modelTreinamentosArquivos = new Sistema_Model_TreinamentosArquivos();
            if (!$modelTreinamentosArquivos->deleteById($params['id'])) {
                throw new Exception("Erro ao excluír as fotos do treinamento.");
            }
			
			Agro_Db_Table_Abstract::getDefaultAdapter()->commit();
        } catch (\Throwable $th) {

			$return['status'] = false;
			$return['message'] = $th->getMessage();
			Agro_Db_Table_Abstract::getDefaultAdapter()->rollBack();
        }

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