<?php

class Produto_Model_ValidacoesSubvencao extends Agro_Db_Table_Abstract {
	protected $_schema = 'produto';
	protected $_name = 'validacoes_limites_subvencao';
	protected $_primary = 'id';
	public $_paginator = false;
	public $_order = 'id_cultura';
	
	
	public function save(array $data) {
		$Row = $this->getRow($data['id']);
		
		$Row->id_validacao = $data['id_validacao'];		
		$Row->id_cultura = $data['id_cultura'];
		$Row->id_corretor = $data['id_corretor'];
		$Row->vl_limite_subvencao = ($data['vl_limite_subvencao'] ? Agro_Util::formatCurrencyDb($data['vl_limite_subvencao']) : 0);
		$Row->fl_ativo = ($data['fl_ativo'] ? 1 : 0);

		return $Row->save();
	}

	public function getData($where) {
		$sql = "
			select
				vls.*,
				c.ds_nome_cultura,
				co.ds_nome_fantasia
			from
				produto.validacoes_limites_subvencao vls,
				produto.culturas c,
				sistema.corretores co
			where
				    vls.id_corretor = co.id 
				and vls.id_cultura = c.id";
		
		if (is_array($where)) {
			foreach ($where as $clause) {
				$field = $clause['field'];
				$operator = $clause['operator'];
				$value = $clause['value'];
				$sql .= " and  $field $operator $value ";
			}
		} elseif ($where != '') {
			$sql .= " and $where";
		}
		
		$sql .= ' order by c.ds_nome_cultura, co.ds_nome_fantasia ';
		
		return $this->_db->fetchAll($sql);
	}
}