<?php

class Produto_Model_Validacoesgrupodensidade extends Agro_Db_Table_Abstract {
	protected $_schema = 'produto';
	protected $_name = 'validacoes_grupo_densidade';
	protected $_primary = 'id';
	public $_paginator = false;
	public $_order = 'ds_nome_grupo_densidade';

	public function getData($where=false) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		
		$select->from(array('gd' => "produto.validacoes_grupo_densidade"), '*');
		$select->join(array('pe' => 'produto.validacoes_grupo_portaenxerto'), 'gd.id_grupo_portaenxerto = pe.id', 'ds_nome_grupo_portaenxerto');
		
		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);
		}
		//die($select);
		return $select;
	}
	
	public function save(array $values) {
		$Row = $this->getRow($values['id']);
		$Row->id_grupo_portaenxerto = $values['id_grupo_portaenxerto'] ? $values['id_grupo_portaenxerto'] : null;
		$Row->ds_nome_grupo_densidade = $values['ds_nome_grupo_densidade'];
		$Row->vl_densidade_minima = $values['vl_densidade_minima'];
		$Row->vl_densidade_maxima = $values['vl_densidade_maxima'];
		$Row->id_validacao = $values['id_validacao'];
		return $Row->save();
	}

    public function setAtivo($id) {
        $Row = $this->getRow($id);

        if($Row['fl_ativo'] == 0)
            $Row['fl_ativo'] = 'true';
        else
            $Row['fl_ativo'] = 'false';
        if($Row->save()) {
            return true;
        } else {
            return false;
        }
    }
	
	public function getCombo($first=true,$field=null, $id_validacao=null) {
		$where = 'fl_ativo = true';
		if($id_validacao != null) {
			$where .= " and id_validacao = $id_validacao";
		}
		$Rs = $this->fetchAll($where, $this->_order)->toArray();
		
		$options = array();
		if (is_array($Rs)) {
			if ($first) {
				$options[''] = '';
			}
			
			$field = $field ? $field : $this->_order;
			foreach ($Rs as $row) {
				$options[$row['id']] = $row[$field];
			}
			
			return $options;
		} else {
			return false;
		}
	}

	public function getGrupos($idValidacao) {
		return $this->fetchPairs('id', 'ds_nome_grupo_densidade', false, false, 1, 'id_validacao = '.$idValidacao, true, 'ASC');
	}

}
