<?php

class Sistema_EmpresaController extends Agro_Controller_Action {
	public $_backAfterSave = false;
	public $_columnList = array(
		'ds_nome_fantasia' => 'Nome',
		'ds_nome_categoria' => 'Categoria',
		'ds_telefone' => 'Telefone',
		'ds_email' => 'Email',
		'ds_sigla' => array('label'=>'UF', 'align'=>'center'),
		'ds_nome_municipio' => 'Município'
	);

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

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

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

	public function getForm() {
		$this->view->formEndereco = new Sistema_Form_Endereco();
		return new Sistema_Form_Empresa();
	}

	public function formAction(){
		parent::formAction();
		$Model = $this->getModel();
		$this->view->grupamentoculturas = $Model->buscaGrupamentoCulturas($this->getRequest()->getParam("id"));

		if($this->getRequest()->getParam("id")){
			$this->view->mobile = $Model->getMobileData($this->getRequest()->getParam("id"));
		}
	}

	public function viewAction() {
		parent::viewAction();

		$Model = $this->getModel();
		$this->view->data['endereco'] = $Model->getEndereco($this->getRequest()->getParam('id'));
		$this->view->data['categoria'] = $Model->getCategoria($this->getRequest()->getParam('id'));
		$this->view->data['informacoes_bancarias'] = $Model->getInformacoesBancarias($this->getRequest()->getParam('id'));
		$this->view->data['departamentos'] = $Model->getDepartamentos($this->getRequest()->getParam('id'));
	}

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

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

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

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

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

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


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

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

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

		return $where;
	}

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

		if ($this->getRequest()->getParam('id')) {
			$Empresas = new Sistema_Model_Empresas();
			$Empresa = $Empresas->getRow($this->getRequest()->getParam('id'));
			$combo = $Empresa->departamentos();

			$opt = array();
			$opt[] = array('id'=>'','label'=>'');
			if ($combo->count()) {
				foreach ($combo as $option) {
					if ($option['fl_ativo']) {
						$opt[] = array('id'=>$option['id'],'label'=>$option['ds_nome_departamento']);
					}
				}
			}

			$Json = new Zend_Json();
			$this->getResponse()->setBody($Json->encode($opt));
		}
	}

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

		$Empresas = new Sistema_Model_Empresas();
		$combo = $Empresas->getComboByCategoria($this->getRequest()->getParam('id_categoria'));

		$opt = array();
		$opt[] = array('id' => '', 'label' => '');
		if ($combo->count()) {
			foreach ($combo as $option) {
				$opt[] = array('id' => $option['id'], 'label' => $option['ds_nome_fantasia']);
			}
		}

		$Json = new Zend_Json();
		$this->getResponse()->setBody($Json->encode($opt));
	}

	/*
	 * Função chamada pelo WS através de uma cURL chamada através da App
	*/
	public function empresasAction() {
		$result = array();
		$result['empresa'] = null;

		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		if (($this->getRequest()->getParam('id')) && ($this->getRequest()->getParam('cod_acesso_mobile'))) {
			$Empresa = $this->getModel();
			$empresas = $Empresa->getEmpresasMobile($this->getRequest()->getParam('id'), $this->getRequest()->getParam('cod_acesso_mobile'));
			$result['empresa'] = $empresas;
		}

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

	public function documentoAction() {
		ini_get('upload_max_filesize');
		$this->isAjax();

		if ($this->getRequest()->getParam('id_empresa') && $this->getRequest()->getParam('id_tipo_arquivo')) {
			$EmpresaArquivos = new Sistema_Model_EmpresaArquivos();

			try {
				$file = Agro_File::upload('empresas');
				if ($file['status']) {
					if ($EmpresaArquivos->save($this->getRequest()->getParams(), $file)) {
						$this->getResponse()->setBody("<script>window.top.window.$.listArquivos();</script>");
					} else {
						$this->getResponse()->setBody("<script>window.top.alert('Ocorreu um erro ao enviar o arquivo.');</script>");
					}
				} else {
					$this->getResponse()->setBody('<script>window.top.alert("Erro ao enviar o aquivo!\n\n'.$file['message'].'");</script>');
				}
			} catch (Exception $e) {
				$this->getResponse()->setBody('<script>window.top.alert("Erro ao enviar o aquivo!\n\n'.$e.'");</script>');
			}
		}
	}

	public function deletearquivoAction() {
		$result = array('id' => $this->getRequest()->getParam('id'));
		$this->isAjax();

		try {
			$EmpresaArquivos = new Sistema_Model_EmpresaArquivos();

			if ($this->getRequest()->getParam('id')) {
				if ($EmpresaArquivos->delete($this->getRequest()->getParam('id'))) {
					$result['status'] = true;
				} else {
					$result['status'] = false;
				}
			} else {
				$result['status'] = false;
			}
		} catch (Exception $e) {
			$result['status'] = false;
		}

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

	public function arquivosAction() {
		$this->isAjax(true);

		if ($this->getRequest()->getParam('id_empresa')) {
			$EmpresaArquivos = new Sistema_Model_EmpresaArquivos();
			$this->view->arquivos = $EmpresaArquivos->getArquivos($this->getRequest()->getParam('id_empresa'));
		}
	}

	public function afterSave($id) {
		require_once(APPLICATION_PATH . "/../library/Agro/nusoap/nusoap.php");

		$Model = $this->getModel();
		$Row = $Model->find($id)->current()->toArray();
		$this->view->form->populate($Row);

		$this->view->id = $id;
		$this->view->cod_acesso_mobile = $Row['cod_acesso_mobile'];

        $modelEmpresasAgronomos = new Sistema_Model_EmpresasAgronomos();
        $modelEmpresasAgronomos->deleteByEmpresa($id);

        foreach ($this->getRequest()->getParam('idFuncionarios') as $idFuncionario) {
            $modelEmpresasAgronomos->save(['id_empresa' => $id, 'id_funcionario' => $idFuncionario]);
        }

        if ((int)$Row['id_categoria'] === Sistema_Model_Categorias::ID_EMPRESA_VISTORIA) {
            $modelDepartamentos = new Sistema_Model_Departamentos();
            $rowsDepartamentos = $modelDepartamentos->fetchAll("id_empresa = {$Row['id']}")->toArray();

            if (empty($rowsDepartamentos)) {
                $modelDepartamentos->save([
                    'id_empresa' => $Row['id'],
                    'ds_nome_departamento' => 'EMPRESA DE VISTORIA',
                    'ds_chave' => 'VISTORIADOR',
                ]);
            }
        }
	}

	public function activeAction(){
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$result = array('status' => false);

		$Model = $this->getModel();

		if ($this->getRequest()->getParam('id')) {
			$Row = $Model->getRow($this->getRequest()->getParam('id'));
			$Row->fl_ativo = ($Row->fl_ativo ? 0 : 1);
		}

		try{

			if ($Row->save()) {

				$Funcionarios = new Sistema_Model_Funcionarios();
				$Funcionarios->update(array('fl_ativo' => ($Row->fl_ativo ? 1 : 0)), "id_empresa = $Row->id");

				$F = $Funcionarios->fetchAll("id_empresa = $Row->id")->toArray();
				$Usuarios = new Sistema_Model_Usuarios();

				foreach($F as $func){
					$Usuarios->update(array('fl_ativo' => ($Row->fl_ativo ? 1 : 0)), "id = ".$func['id_usuario']);
				}

				$result = array('ativo' => $Row->fl_ativo);
			}

		}catch (Exception $e){
			$result = $e->getTraceAsString();
		}

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

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

        if ($this->getRequest()->getParam('id')) {
            $retorno = [];
            $row = (new Sistema_Model_Departamentos())->getComboDeptEmpresa($this->getRequest()->getParam('id'));

            if (!empty($row)) {
                if (count($row) > 1) {
                    $retorno[] = ['id' => '', 'label' => ''];
                }

                foreach ($row as $idDepartamento => $nomeDepartamento) {
                    $retorno[] = ['id' => $idDepartamento, 'label' => $nomeDepartamento];
                }
            }

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

    /**
     * @return void
     * @throws Exception
     */
    public function beforeSave()
    {
        $parametros = $this->getRequest()->getParams();

        if (empty($parametros['idFuncionarios'])) {
            throw new Exception('É obrigatório cadastrar ao menos 1 agrônomo responsável.', 403);
        }

        if (!empty($parametros['id'])) {
            $rowEmpresa = $this->getModel()->getRow($parametros['id']);

            if ((int)$rowEmpresa['id_categoria'] !== Sistema_Model_Categorias::ID_EMPRESA_VISTORIA
                && (int)$parametros['id_categoria'] === Sistema_Model_Categorias::ID_EMPRESA_VISTORIA
            ) {
                throw new Exception('Não é possível realizar a alteração da categoria para ‘Empresa de Vistoria’. Nesse caso deve ser inativado o cadastro atual e cadastrada uma nova empresa.', 403);
            }
        }
    }

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

        $retorno = (new Sistema_Model_EmpresasAgronomos())->getAgronomoByEmpresa($this->getRequest()->getParam('id_empresa'));

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

	public function deleteAction(){
		try{
			$result = array();
			$this->getHelper('ViewRenderer')->setNoRender();
			$this->getHelper('layout')->disableLayout();
			
			$Model = $this->getModel();

			$idEmpresa = $this->getRequest()->getParam('id');
	
			$modelEmpresasAgronomos = new Sistema_Model_EmpresasAgronomos();
			$modelDepartamentos = new Sistema_Model_Departamentos();

			$modelEmpresasAgronomos->deleteByEmpresa($idEmpresa);
			$modelDepartamentos->deleteByEmpresa($idEmpresa);

		}catch (Exception $e) {
			if ($e->getCode() == 23503) {
				$result['message'] = $this->view->escape(MSG_DELETE_FK_ERROR);
			} else {
				$result['message'] = $this->view->escape($e->getMessage());
			}

			$result['status'] = false;

			Agro_Util::informaErroAgronet($e->getMessage());
		}
		parent::deleteAction();
		$this->getResponse()->setBody(Zend_Json::encode($result));

	}
}
