<?php
class Sinistro2_Model_TipoLaudoPreliminar extends Agro_Db_Table_Abstract {
	public $_pairs = array('key' => 'id', 'field' => 'ds_nome_tipo_laudo_final');
	protected $_schema = 'sinistro';
	protected $_name = 'tipo_laudo_preliminar';
	protected $_primary = 'id';
	public $_order = 'ds_chave';

	public function getData($where=false)
	{
		$select = $this->select();
	
		$select->setIntegrityCheck(false);
		$select->from("{$this->_schema}.{$this->_name}");
		$select->where($this->_name.'.id_safra is null');
	
		if ($this->_order) {
			$select->order($this->_order);
		}
	
		$this->getWhere($select, $where);
	
		return $select;
	}
	
	public function save(array $data)
	{
		$this->getAdapter()->beginTransaction();
		try {
			$Row = $this->getRow($data['id']);

			$Row->ds_nome_tipo_laudo_preliminar = $data['ds_nome_tipo_laudo_preliminar'];
			$Row->ds_chave = $data['ds_chave'];
			$Row->ds_descricao_tipo_laudo_preliminar = $data['ds_descricao_tipo_laudo_preliminar'];
			$Row->id_grupamento_cultura = $data['id_grupamento_cultura'];
			$Row->ds_nome_arquivo = ($data['ds_nome_arquivo'] ? $data['ds_nome_arquivo'] : $Row->ds_nome_arquivo);
            $Row->ds_versao = $data['ds_versao'];
            $Row->fl_import_xml = $data['can_import_xml'] ? 't' : 'f';
				
			$Row->save();
				
			$this->getAdapter()->commit();
			
			return $Row; 
			
		} catch (Exception $e) {
			$this->getAdapter()->rollBack();
			throw new Exception($e);
		}
	}
	
	public function getComboTipoLaudoPreliminar($first=true, $idProdCob) {
		
		$params = explode(',',$idProdCob);

		$ModelSafraProduto = new Produto_Model_Safras();
		$idSafra = $ModelSafraProduto->getSafraByProduto($params[0]);

		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('lp' => $this->_schema.".".$this->_name), array('id', 'ds_chave'));		

		if($idSafra >= 18){
			$Select->where('lp.id_safra is null'); 
		}else{
			$Select->where('lp.id_safra in(select id_safra from produto.produtos where id = ?)',$params[0]);
		}
		
		$Select->order('ds_chave');

		return $this->getDefaultAdapter()->fetchPairs($Select);		
	}	
	
}