<?php

class Sistema_Model_Empresas extends Agro_Db_Table_Abstract {
    const AGROBRASIL = 20;
    const ESSOR_SEGUROS = 181;

	protected $_schema = 'sistema';
	protected $_name = 'empresas';
	protected $_view = 'v_empresas';
	protected $_primary = 'id';
	protected $_rowClass = 'Sistema_Model_Row_Empresa';
	public $_order = 'ds_nome_fantasia';
	public $_columnExcel = array(
		'ds_cnpj' => 'CNPJ',
		'ds_razao_social' => 'Nome',
		'ds_nome_fantasia' => 'Nome Fantasia',
		'ds_telefone' => 'Telefone',
		'ds_email' => 'Email',
		'ds_endereco_rua' => 'Endereço',
		'ds_endereco_nro' => 'Nro',
		'ds_endereco_bairro' => 'Bairro',
		'ds_endereco_cep' => 'CEP',
		'ds_endereco_complemento' => 'Complemento',
		'ds_sigla' => 'UF',
		'ds_nome_municipio' => 'Município',
		'ds_responsavel' => 'Responsável',
		'grupamento_culturas' => 'Culturas',
		'data_criacao' => 'Data Cadastro',
		'ativo' => 'Ativo'
	);

	protected $_referenceMap    = array (
		'Sistema_Model_Departamentos' => array (
			'columns'           => array('id'),
			'refTableClass'     => 'Sistema_Model_Departamentos',
			'refColumns'        => array('id_empresa')
		)
    );

	public function save(array $data) {
		$this->getDefaultAdapter()->beginTransaction();

		try {
			$Row = $this->getRow($data['id']);
			// print_r($Row); die;
			$Row->id_categoria = $data['id_categoria'];
			$Row->cpf_cnpj = $data['cpf_cnpj'];
			$Row->ds_nome_fantasia = $data['ds_nome_fantasia'];
			$Row->ds_razao_social = $data['ds_razao_social'];
			$Row->ds_endereco_rua = $data['ds_endereco_rua'];
			$Row->ds_endereco_nro = $data['ds_endereco_nro'];
			$Row->ds_endereco_bairro = $data['ds_endereco_bairro'];
			$Row->ds_endereco_cep = $data['ds_endereco_cep'];
			$Row->ds_endereco_complemento = $data['ds_endereco_complemento'];
			$Row->id_municipio = $data['id_municipio'];
			$Row->ds_telefone = $data['ds_telefone'];
			$Row->ds_telefone_fax = $data['ds_telefone_fax'];
			$Row->ds_telefone_adicional = $data['ds_telefone_adicional'];
			$Row->ds_observacao = $data['ds_observacao'];
			$Row->ds_email = $data['ds_email'];
			$Row->ds_nome_responsavel = $data['ds_nome_responsavel'];
			$Row->ds_email_responsavel = $data['ds_email_responsavel'];
			$Row->fl_empresa_tagh = 0;
			$Row->id_codigo_ibge = $data['id_codigo_ibge'];
			//sempre começa inativo, solicitação 3275
			if (empty($data['id'])) {
				$Row->fl_ativo = 0;
			}

			if(!$data['id']){
				$Row->cod_acesso_mobile = rand(1000,9999);
			}

			if ($Row->save()){
                if (empty($data["id_grupamento_cultura"])) {
                    throw new Exception('É necessário selecionar ao menos 1 grupo de cultura, na aba Grupamento de Culturas.');
                }

				if ($data["id_grupamento_cultura"] && !empty($data["id"])){
					$ModelGrupamento = new Sistema_Model_EmpresaGrupamentoCulturas();

					$ModelGrupamento->delete($data["id"],"id_empresa");
					
					foreach ($data["id_grupamento_cultura"] as $id_grupamento_cultura){
						$ModelGrupamento->insert(
							array(
								"id_grupamento_cultura" => $id_grupamento_cultura,
								"id_empresa" => $data["id"]
							)
						);
					}
				}
			}

			$this->getDefaultAdapter()->commit();

			return $Row->id;

		} catch (Exception $e) {
			$this->getDefaultAdapter()->rollback();
			$this->setMessage($e->getMessage());
			return false;
		}
	}

	public function getData($where = false){
		$select = $this->select();

		if ($this->_view) {
			$select->setIntegrityCheck(false);
			$select->from("sistema.v_empresas");
		}


		if ($this->_user->tp_usuario == 'F' && $this->_user->ds_chave == 'SEGURADORA') {
			$select->where('ds_chave_categoria = ?', 'VISTORIADORA');
			$select->where('fl_ativo = ?', 'true');
		}

		if ($this->_order) {
			$select->order($this->_order);
		}

		if (is_array($where)) {
			foreach ($where as $clause) {
				if (is_array($clause)) {
					$field = $clause['field'];
					$operator = $clause['operator'];
					$value = $clause['value'];
					$select->where("$field $operator ?", $value);

				} else {
					$select->where($clause, '');
				}
			}
		} elseif ($where != '') {
			$select->where($where);
		}

		return $select;
	}

	public function beforeDelete($id) {
		$InformacoesBancariasEmpresas = new Sistema_Model_InformacoesBancariasEmpresas();
		$InformacoesBancarias = new Sistema_Model_InformacoesBancarias();

		$Contas = $InformacoesBancariasEmpresas->fetchAll("id_empresa = $id");
		if ($Contas->count()) {
			foreach ($Contas as $Conta) {
				$InformacoesBancariasEmpresas->delete($Conta->id_informacoes_bancarias, "id_informacoes_bancarias");
				$InformacoesBancarias->delete($Conta->id_informacoes_bancarias, 'id');
			}
		}

		$Departamentos = new Sistema_Model_Departamentos();
		$Rs = $Departamentos->fetchAll("id_empresa = $id");
		if ($Rs->count()) {
			foreach ($Rs as $Row) {
				$Departamentos->delete($Row->id, 'id');
			}
		}
	}

	public function getInformacoesBancarias($id) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('ib' => 'sistema.informacoes_bancarias'));
		$select->join(array('b' => 'sistema.bancos'),'ib.id_banco = b.id', 'ds_nome_banco');
		$select->join(array('ibe' => 'sistema.informacoes_bancarias_empresas'),'ib.id = ibe.id_informacoes_bancarias', null);
		$select->where("ibe.id_empresa=?",$id);
		$select->where("ib.fl_ativo=true");
		$select->where("b.fl_ativo=true");

		return $this->fetchAll($select);
	}

	public function getEndereco($id) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('e' => 'sistema.empresas'), false);
		$select->join(array('m' => 'sistema.municipios'), 'e.id_municipio = m.id');
		$select->join(array('u' => 'sistema.estados'), 'm.id_estado = u.id');
		$select->where("e.id = ?",$id);

		return $this->fetchAll($select)->current();
	}

	public function getCategoria($id) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('e' => 'sistema.empresas'), false);
		$select->join(array('c' => 'sistema.categorias'), 'e.id_categoria = c.id');
		$select->where("e.id = ?",$id);

		return $this->fetchAll($select)->current()->toArray();
	}

	public function getDepartamentos($id) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('d' => 'sistema.departamentos'), array('id', 'ds_nome_departamento'));
		$select->where("d.id_empresa = ?",$id);
		$select->where("d.fl_ativo = true");
		$select->order("ds_nome_departamento");

		return $this->fetchAll($select);
	}

	public function getMobileData($id) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('e' => 'sistema.empresas'), array('id', 'cod_acesso_mobile'));
		$select->where("e.id = ?",$id);
		$select->where("e.fl_ativo = true");

		return $this->fetchRow($select);
	}

	public function getComboByCategoria($idCategoria) {
		$select = $this->select()
			->setIntegrityCheck(false)
			->from(array('e' => 'sistema.v_empresas'), array('id', 'ds_nome_fantasia'));
		if ($idCategoria>0) {
			$select->where('e.id_categoria = ?', $idCategoria);
		}

		$select->where('e.fl_del = false')
			->where('e.fl_ativo = true')
			->order('ds_nome_fantasia');
		
		return $this->fetchAll($select);
	}

	public function getCombo($chaveCategoria='') {
		if (!is_array($chaveCategoria)) {
			$chaveCategoria = array($chaveCategoria);
		}

		if ($chaveCategoria) {
			$select = $this->select();
			$select->setIntegrityCheck(false);
			$select->from(array('e' => 'sistema.v_empresas'), array('id', 'ds_nome_fantasia'));

			if (count($chaveCategoria)) {
				$select->join(array('c' => 'sistema.categorias'),'e.id_categoria = c.id', false);

				foreach ($chaveCategoria as $item) {
					if ($item) {
						$select->orWhere("c.ds_chave = ?", $item);
					}
				}
			}

			$select->where("e.fl_ativo=true");
			$select->order("ds_nome_fantasia");
			$Rs = $this->fetchAll($select);
			if ($Rs) {
				$options[''] = '';
				foreach ($Rs as $row) {
					$options[$row['id']] = $row['ds_nome_fantasia'];
				}

				return $options;
			} else {
				return array();
			}
		} else {
			$Model = new Sistema_Model_Categorias();
			$Categorias = $Model->fetchPairs();

			$options = array();
			$options[0] = '';
			if (count($Categorias)) {
				foreach ($Categorias as $id => $nome) {
					$Empresas = $this->fetchAll("id_categoria = $id and fl_ativo = true", "ds_nome_fantasia");

					$options["Categosria_$id"] = $nome;
					if ($Empresas->count()) {
						foreach ($Empresas as $Empresa) {
							$options[$Empresa->id] = "--- ".$Empresa->ds_nome_fantasia;
						}
					}
				}

				return $options;
			}
		}
	}

	public function getComboVistoriadoras(){
		$User = Zend_Auth::getInstance()->getIdentity();

		$select = $this->select();
		$select->from(array('e'=>'sistema.empresas'),array('id','ds_nome_fantasia'));
		$select->join(array('c'=>'sistema.categorias'),"e.id_categoria = c.id and (c.ds_chave = 'VISTORIADORA' or c.ds_chave = 'EMPRESA')",false);
		$select->join(array('f'=>'sistema.funcionarios'),'e.id = f.id_empresa and f.fl_ativo = true',false);
		$select->join(array('u'=>'sistema.usuarios'),"f.id_usuario = u.id and (u.tp_usuario = 'V' or u.tp_usuario = 'F')", false);
		$select->where('e.fl_ativo = true');

		//Se o usuário não for do tipo funcionário, busca somente a empresa dele.
		$options = array();

		$options = array(''=>'');
		$emp = $this->fetchRow('id = 1');
		$options[$emp['id']] = $emp['ds_nome_fantasia'];

		$select->group(array('e.id','e.ds_nome_fantasia'));
		$select->order('e.ds_nome_fantasia');

		$Rs = $this->fetchAll($select);

		if ($Rs) {
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_nome_fantasia'];
			}
		}

		return $options;
	}

	public function getVistoriadoraByProcesso($idProcesso){

		$select = $this->select();
		$select->from(array('e'=>'sistema.empresas'),array('id','ds_nome_fantasia'));
		$select->join(array('pe'=>'sinistro.processos_empresas'),"pe.id_empresa = e.id and pe.fl_ativo = true",false);
		$select->where('pe.id_processo = ?', $idProcesso);
		$select->where('e.fl_ativo = true');

		$Rs = $this->fetchAll($select);

		if ($Rs) {
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_nome_fantasia'];
			}
		}

		return $options;
	}

	public function getComercial($flLinhaNula=false,$flAtivo=true) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('f' => 'sistema.funcionarios'), array('id_usuario','UPPER(ds_nome_funcionario) as ds_nome_funcionario'));
		$Select->joinInner(array('d' => 'sistema.departamentos'), 'f.id_departamento = d.id', null);
		$Select->joinInner(array('e' => 'sistema.empresas'), 'f.id_empresa = e.id', null);
		$Select->joinInner(array('c' => 'sistema.categorias'), 'e.id_categoria = c.id', null);

		//solicitacao 02682
		if ($flAtivo) {
			$Select->where("f.fl_ativo = true");
		}

		$Select->where("f.fl_del = false");
		$Select->where("d.ds_chave = 'COMERCIAL'");
		$Select->where("c.ds_chave = 'EMPRESA'");
		$Select->order("ds_nome_funcionario");
		$Rs = $this->fetchAll($Select);

		$ret = array();

		if ($Rs->count()) {
		    if($flLinhaNula){ $ret[] = ''; }
			foreach($Rs as $Row) {
				$ret[$Row->id_usuario] = $Row->ds_nome_funcionario;
			}
		}

		return $ret;
	}


	public function getIdEmpresaUsuarioCorrente() {
		$User = Zend_Auth::getInstance()->getIdentity();
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('f' => 'sistema.funcionarios'), false);
		$Select->join(array('e' => 'sistema.empresas'), 'f.id_empresa = e.id', 'id');
		$Select->where('f.id_usuario = ?', $User->id);

		return $this->getAdapter()->fetchOne($Select);
	}

	public function getIdEmpresaUsuario($idFuncionario): string
    {
        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('f' => 'sistema.funcionarios'), false);
        $select->join(array('e' => 'sistema.empresas'), 'f.id_empresa = e.id', 'id');
        $select->where('f.id = ?', $idFuncionario);

        return $this->getAdapter()->fetchOne($select);
    }

	public function getNomeEmpresaById($idEmpresa) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('e' => 'sistema.empresas'), 'ds_nome_fantasia');
		$Select->where('e.id = ?', $idEmpresa);

		return $this->getAdapter()->fetchOne($Select);
	}

	public function buscaGrupamentoCulturas($id){
		$Model = new Sistema_Model_EmpresaGrupamentoCulturas();
		
		$ModelGrupamento = new Produto_Model_GrupamentoCulturas();

		if ($id){
			$Row = $Model->fetchAll("id_empresa=$id");
		} else {
			$Row = false;
		}

		$grupamentos_empresa = array();

		if ($Row){
			foreach ($Row as $grupamento){
				$grupamentos_empresa[]=$grupamento->id_grupamento_cultura;
			}
		}
		
		$Grupamentos = $ModelGrupamento->fetchAll("fl_ativo=true");
		
		$result = array();
		foreach ($Grupamentos as $group){
		
			$parcial = $group->toArray();
			$parcial["checked"] = (in_array($parcial["id"], $grupamentos_empresa) || !$Row ? true : false);
			$result[] = $parcial;

		}
		return $result;
	}

	/*
	 * Recupera a empresa através do ID e do Codigo de Acesso.
	*/
	function getEmpresasMobile($id, $cod_acesso_mobile) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('e' => 'sistema.empresas'), array('id','ds_nome_fantasia'));
		$Select->where('e.id = ?', $id);
		$Select->where('e.cod_acesso_mobile = ?', $cod_acesso_mobile);

		return $this->fetchAll($Select)->toArray();
	}

	public function getIdEmpresaByIdUsuario(int $idUsuario): int
	{
		$row = $this->fetchRow(
			$this->select()
				->setIntegrityCheck(false)
				->from(['se' => 'sistema.empresas'], 'id')
				->join(['sf' => 'sistema.funcionarios'], 'sf.id_empresa = se.id', false)
				->where('sf.id_usuario = ?', $idUsuario)
		);
	
		return $row['id'];
	}

    public function getEmpresaByIdCombo(int $idEmpresa) : array
    {
        $empresa = [];
        $select = $this->select()->setIntegrityCheck(false);
        $select->from(['se' => "{$this->_schema}.{$this->_name}"], ['id', 'ds_nome_fantasia']);
        $select->where('id = ?', $idEmpresa);

        $row = $this->fetchRow($select);

        if (!empty($row)) {
            $empresa[$row['id']] = $row['ds_nome_fantasia'];
        }

        return $empresa;
    }
}
