<?php

class Produto_Model_Validacoes extends Agro_Db_Table_Abstract {
	protected $_schema = 'produto';
	protected $_name = 'validacoes';
	protected $_primary = 'id';
	public $_order = 'ds_nome_validacao';


	public function save($data) {
		$Row = $this->getRow($data['id']);

		$Row->ds_nome_validacao = $data['ds_nome_validacao'];
		$Row->ds_chave = $data['ds_chave'];
		$Row->ds_acao = $data['ds_acao'];
		$Row->id_tipo_validacao = $data['id_tipo_validacao'];
		$Row->ds_descricao_validacao = $data['ds_descricao_validacao'];
		$Row->fl_ativo = ($data['fl_ativo'] ? 1 : 0);

		return $Row->save();
	}

	public function getData($where=false) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array("v" => "{$this->_schema}.{$this->_name}"));

		if ($this->_order) {
			$select->order($this->_order);
		}
		$select->join(array('tv'=>'produto.tipo_validacao'), 'v.id_tipo_validacao = tv.id', "ds_chave as tipo");

		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 getValidacaoProduto($idProduto, $tipo='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('pv' => 'produto.produtos_validacoes'), null);
		$Select->join(array('v' => 'produto.validacoes'), 'pv.id_validacao = v.id', array('id', 'ds_chave'));
		$Select->where('pv.id_produto = ?', $idProduto);

		if ($tipo) {
			$Select->join(array('tv' => 'produto.tipo_validacao'), 'v.id_tipo_validacao = tv.id', null);
			$Select->where('tv.ds_chave = ?', $tipo);
		}

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

	public function verificaDataSemeadura($idValidacao, $idTipoSolo, $idProduto, $idCiclo, $idMunicipio, $dtSemeadura, $dtSemeaduraFinal = null) {
		if(!$dtSemeadura) return false;

		if(!$idCiclo) return false;
		
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('z'=>'produto.validacoes_zoneamento_graos'));
		$Select->join(array('m'=>'produto.validacoes_zoneamento_graos_municipios'), 'z.id = m.id_validacao_zoneamento_graos', false);
		$Select->where('m.id_municipio = ?', $idMunicipio);
		$Select->where('? between (dt_inicial) and (dt_final)', Agro_Util::formatDate($dtSemeadura, Zend_Date::W3C));

		if ($dtSemeaduraFinal) {
			$Select->where('? between (dt_inicial) and (dt_final)', Agro_Util::formatDate($dtSemeaduraFinal, Zend_Date::W3C));
		}

		if ($idTipoSolo) {
			$idTipoSolo = (int) $idTipoSolo;
			$Select->where('z.id_tipo_solo = ?', $idTipoSolo);
		}

		$Select->where('z.id_produto = ?', $idProduto);

		if($idCiclo <> 16){
		    $Select->where('z.id_ciclo = ?', $idCiclo);
		}

		return $this->fetchAll($Select)->count();
	}
	
	public function verificaZoneamento($idTipoSolo, $idProduto, $idCiclo, $idMunicipio, $dtSemeadura, $vlAltitude=0, $idSistemaPlantio=null) {
		$return['status'] = true;
	
		if(!$idCiclo){
			$return['status'] = false;
			$return['msg'] = 'Ciclo não informado.';
			return $return;
		}
			
		if(!$dtSemeadura){
			$return['status'] = false;
			$return['msg'] = 'Data de Semeadura não informada.';
			return $return;
		}
	
		//busca o cadastro de zoneamento conforme criterio informado
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('z'=>'produto.validacoes_zoneamento_graos'));
		$Select->join(array('m'=>'produto.validacoes_zoneamento_graos_municipios'), 'z.id = m.id_validacao_zoneamento_graos', array('vl_altitude', 'id_sistema_plantio'));
		$Select->where('? between (dt_inicial) and (dt_final)', Agro_Util::formatDate($dtSemeadura, Zend_Date::W3C));
		$Select->where('m.id_municipio = ?', $idMunicipio);
		$Select->where('z.id_produto = ?', $idProduto);
	
		if ($idTipoSolo) {
			$idTipoSolo = (int) $idTipoSolo;
			$Select->where('z.id_tipo_solo = ?', $idTipoSolo);
		}
		if($idCiclo <> 16){
			$Select->where('z.id_ciclo = ?', $idCiclo);
		}
	
		$rsZoneamento = $this->fetchAll($Select);
	
		if(!$rsZoneamento->count() > 0){
			$return['status'] = false;
			$return['msg'] = 'Data de plantio está em desacordo com o Zoneamento Agrícola e, em virtude disso, o valor segurado deve ser zerado';
			return $return;
		} else {
			foreach($rsZoneamento as $zoneamento){
				
				if($zoneamento[vl_altitude] > 0 && $vlAltitude > 0  && ($vlAltitude > $zoneamento[vl_altitude])){
					$return['status'] = false;
					$return['msg'] = 'Altitude está em desacordo com o Zoneamento Agrícola e, em virtude disso, o valor segurado deve ser zerado';
					return $return;
				}
	
				if($zoneamento[id_sistema_plantio] > 0 && $idSistemaPlantio > 0 && ($idSistemaPlantio <> $zoneamento[id_sistema_plantio])){
					$return['status'] = false;
					$return['msg'] = 'Sistema de plantio está em desacordo com o Zoneamento Agrícola e, em virtude disso, o valor segurado deve ser zerado';
					return $return;
				}
	
			}
				
			$return['status'] = true;
			return $return;
		}
	}
}