<?php
class Regulacao_Model_Lvp001ItensSegurados extends Agro_Db_Table_Abstract {
	protected $_schema = 'regulacao';
	protected $_name = 'lvp001_itens_segurados';
	protected $_primary = 'id';
	public $_order = 'id';

	public function save($dados){ 
		$modelVP = new Seguro_Model_VistoriaPreviaEmpresa;
		$lvpItensSegurados = $modelVP->getItensLaudo(array('id_laudo' => $dados['id_laudo_previa'], 'module' => 'regulacao', 'controller' => 'lvp001'));
		$callbackItens = function($item) {
			return $item['id'];
		};
		$lvpItensSegurados = array_map($callbackItens, $lvpItensSegurados);
		$amostras = array_map($callbackItens, $dados['amostras']);
		$exclude = array_diff($lvpItensSegurados, $amostras);
		foreach ($exclude as $key => $value) {
			$this->delete($value);
		}

		foreach($dados['amostras'] as $key => $amostra){ 
			$Row = $this->getRow($amostra['id']);
			$Row->id_laudo_previa = $dados['id_laudo_previa'];
			$Row->nr_quadra = $amostra['nr_quadra'] ? $amostra['nr_quadra'] : null;
			$Row->ds_coordenadas = $amostra['ds_coordenadas'] ? $amostra['ds_coordenadas'] : null;
			$Row->tipo_solo = $amostra['tipo_solo'] ? $amostra['tipo_solo'] : null;
			$Row->vl_altitude = $amostra['vl_altitude'] ? Agro_Util::formatCurrencyDb($amostra['vl_altitude']) : null;
			$Row->id_variedade = $amostra['id_variedade'] ? $amostra['id_variedade'] : null;
			$Row->dt_inicio_semeadura = ($amostra['dt_inicio_semeadura'] ? Agro_Util::formatDate($amostra['dt_inicio_semeadura'], Zend_Date::W3C) : null);
			$Row->dt_final_semeadura = ($amostra['dt_final_semeadura'] ? Agro_Util::formatDate($amostra['dt_final_semeadura'], Zend_Date::W3C) : null);
			$Row->vl_area_declarada = $amostra['vl_area_declarada'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_declarada']) : null;
			//if ($amostra['fl_area_plantada'] == true) {
				$Row->vl_area_vistoriada = $amostra['vl_area_vistoriada'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_vistoriada']) : null;
			//} else {
			//	$Row->vl_area_vistoriada = $amostra['vl_area_declarada'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_declarada']) : null;
			//}
			$Row->vl_area_asseguravel = $amostra['vl_area_asseguravel'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_asseguravel']) : null;
			$Row->vl_area_excluida = $amostra['vl_area_excluida'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_excluida']) : null;
			$Row->vl_rendimento_proposta = $amostra['vl_rendimento_proposta'] ? Agro_Util::formatCurrencyDb($amostra['vl_rendimento_proposta']) : null;
			$Row->fl_rendimento_inferior = $amostra['fl_rendimento_inferior'];
			$Row->vl_rendimento_estimado = $amostra['vl_rendimento_estimado'] ? Agro_Util::formatCurrencyDb($amostra['vl_rendimento_estimado']) : null;
			$Row->fl_area_plantada = $amostra['fl_area_plantada'];
			$Row->tipo_semeadura = $amostra['tipo_semeadura'] ? $amostra['tipo_semeadura'] : null;
			$Row->id_item_segurado = $amostra['id_item_segurado'] ? $amostra['id_item_segurado'] : null;
			$Row->fl_area_segurado = $amostra['fl_area_segurado'];
			$Row->fl_plantio_futuro = $amostra['fl_plantio_futuro'];
			$Row->nro_item = $amostra['nro_item'] ? $amostra['nro_item'] : null;
			$Row->negar_ciclo_anterior = $amostra['negar_ciclo_anterior'];
			$Row->cultivo_anterior = $amostra['cultivo_anterior'] ? $amostra['cultivo_anterior'] : null;
			$Row->negar_nro_safra = $amostra['negar_nro_safra'];
			$Row->nro_safra = $amostra['nro_safra'] ? $amostra['nro_safra'] : null;
			$Row->tamanho_planta = $amostra['tamanho_planta'] ? $amostra['tamanho_planta'] : null;
			$Row->estadio_fenologico = $amostra['estadio_fenologico'] ? $amostra['estadio_fenologico'] : null;
			$Row->unid_medida_stand_plantas = $amostra['unid_medida_stand_plantas'] ? $amostra['unid_medida_stand_plantas'] : null;
			$Row->espacamento_linhas = $amostra['espacamento_linhas'] ? Agro_Util::formatCurrencyDb($amostra['espacamento_linhas']) : null;
			$Row->amostra_1 = $amostra['amostra_1'] ? Agro_Util::formatCurrencyDb($amostra['amostra_1']) : null;
			$Row->amostra_2 = $amostra['amostra_2'] ? Agro_Util::formatCurrencyDb($amostra['amostra_2']) : null;
			$Row->amostra_3 = $amostra['amostra_3'] ? Agro_Util::formatCurrencyDb($amostra['amostra_3']) : null;
			$Row->amostra_4 = $amostra['amostra_4'] ? Agro_Util::formatCurrencyDb($amostra['amostra_4']) : null;
			$Row->media_amostras = $amostra['media_amostras'] ? Agro_Util::formatCurrencyDb($amostra['media_amostras']) : null;
			$Row->populacao_ha = $amostra['populacao_ha'] ? Agro_Util::formatCurrencyDb($amostra['populacao_ha']) : null;
			$Row->incidencia_doencas = $amostra['incidencia_doencas'];
			$Row->incidencia_pragas = $amostra['incidencia_pragas'];
			$Row->incidencia_invasores = $amostra['incidencia_invasores'];
			$Row->desuniformidade_plantio = $amostra['desuniformidade_plantio'];
			$Row->inundacao = $amostra['inundacao'];
			$Row->baixo_stand = $amostra['baixo_stand'];
			$Row->geada = $amostra['geada'];
			$Row->erosao = $amostra['erosao'];
			$Row->toxidez = $amostra['toxidez'];
			$Row->outros = $amostra['outros'];
			$Row->fl_habilitar_nova_vistoria = $amostra['fl_habilitar_nova_vistoria'];
			$Row->motivos_negacao = $amostra['motivos_negacao'];
			
			$Propostas = new Seguro_Model_Propostas();
			$Proposta = $Propostas->find($dados['id_proposta'])->current();

			$Ciclos = new Produto_Model_Ciclos();
			$Propriedade = $Proposta->propriedade();

			$flZoneamentoRegiao = $Proposta->atributo_rn('PROPRIEDADE', 'PROD_ZONEAMENTO_REGIAO');

			if(!$flZoneamentoRegiao){
				$idCiclo = $Ciclos->getCicloEstado($Proposta->id_produto, $Row->id_variedade, $Propriedade['id_estado']);
			    $Row->id_ciclo = $idCiclo ? $idCiclo : null;
			} else {
			    $idCiclo = $Ciclos->getCicloRegiao($Proposta->id_produto, $Row->id_variedade, $Propriedade['id_estado'], $Propriedade['id_regiao']);
			    $Row->id_ciclo = $idCiclo ? $idCiclo : null;
			}

			try{
				$Row->save();
			}catch (Exception $e){
				die($e);
			}

		}
	}

	public function saveMobile($dados){ 

		foreach($dados['amostras'] as $key => $amostra){

			$Row = $this->getRow($amostra['id']);;
			$Row->id_laudo_previa = $dados['id_laudo_previa'];
			$Row->nr_quadra = $amostra['nr_quadra'] ? $amostra['nr_quadra'] : null;
			$Row->ds_coordenadas = $amostra['ds_coordenadas'] ? $amostra['ds_coordenadas'] : null;
			$Row->tipo_solo = $amostra['tipo_solo'] ? $amostra['tipo_solo'] : null;
			$Row->vl_altitude = $amostra['vl_altitude'] ? Agro_Util::formatCurrencyDb($amostra['vl_altitude']) : null;
			$Row->id_variedade = $amostra['id_variedade'] ? $amostra['id_variedade'] : null;
			$Row->dt_inicio_semeadura = Agro_Util::formatDate($amostra['dt_inicio_semeadura'], Zend_Date::W3C);
			$Row->dt_final_semeadura = Agro_Util::formatDate($amostra['dt_final_semeadura'], Zend_Date::W3C);
			$Row->vl_area_declarada = $amostra['vl_area_declarada'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_declarada']) : null;
			$Row->vl_area_vistoriada = $amostra['vl_area_vistoriada'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_vistoriada']) : null;
			$Row->vl_area_asseguravel = $amostra['vl_area_asseguravel'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_asseguravel']) : null;
			$Row->vl_area_excluida = $amostra['vl_area_excluida'] ? Agro_Util::formatCurrencyDb($amostra['vl_area_excluida']) : null;
			$Row->vl_rendimento_proposta = $amostra['vl_rendimento_proposta'] ? Agro_Util::formatCurrencyDb($amostra['vl_rendimento_proposta']) : null;
			$Row->vl_rendimento_estimado = $amostra['vl_rendimento_estimado'] ? Agro_Util::formatCurrencyDb($amostra['vl_rendimento_estimado']) : null;
			$Row->fl_area_plantada = $amostra['fl_area_plantada'] ? $amostra['fl_area_plantada'] : 0;
			$Row->tipo_semeadura = $amostra['tipo_semeadura'] ? $amostra['tipo_semeadura'] : null;
				
			$Propostas = new Seguro_Model_Propostas();
			$Proposta = $Propostas->find($dados['id_proposta'])->current();

			$Ciclos = new Produto_Model_Ciclos();
			$Propriedade = $Proposta->propriedade();

			$flZoneamentoRegiao = $Proposta->atributo_rn('PROPRIEDADE', 'PROD_ZONEAMENTO_REGIAO');

			if(!$flZoneamentoRegiao){
				$idCiclo = $Ciclos->getCicloEstado($Proposta->id_produto, $Row->id_variedade, $Propriedade['id_estado']);
				$Row->id_ciclo = $idCiclo ? $idCiclo : null;
			} else {
				$idCiclo = $Ciclos->getCicloRegiao($Proposta->id_produto, $Row->id_variedade, $Propriedade['id_estado'], $Propriedade['id_regiao']);
				$Row->id_ciclo = $idCiclo ? $idCiclo : null;
			}

			try{
				$Row->save();
			}catch (Exception $e){
				die($e);
			}

		}
	}

	public function get($dados){
	    $amostras = $this->fetchAll("id_laudo_previa = ".$dados["id_laudo"], "nro_item");

	    if($amostras){

	        $amostras = ($amostras ? $amostras->toArray() : array());

	        $dados = array();
	        foreach ($amostras as $key => $amostra){
	        	$dados["amostras"][$key] = $amostra;
	        }
	        
	        return $dados;
	    }else{
        	return false;
        }
	}

	public function getItensLaudo(array $params) {
		$select = $this->select()->setIntegrityCheck(false);
        $select->from(array("vp" => "seguro.propostas_vistorias_previas"), false);
        $select->join(array("lvp" => "regulacao.lvp001"), "vp.id = lvp.id_proposta_vistoria", 'id_proposta_vistoria');
        $select->join(array("lvp_itens" => "regulacao.lvp001_itens_segurados"), "lvp.id = lvp_itens.id_laudo_previa", '*');
        $select->where('vp.id = ?', $params['id_proposta_vistoria']);

        if ($params['fl_necessario_nova_vistoria']) {
        	$select->where('lvp_itens.fl_habilitar_nova_vistoria = ?', $params['fl_necessario_nova_vistoria']);
        }

        $select->order('lvp_itens.nro_item DESC');

        $Rs = $this->getAdapter()->fetchAll($select);

        return $Rs;
    }
}
