<?php

class Produto_Model_RestricoesUsuarios extends Agro_Db_Table_Abstract {
	protected $_schema = 'produto';
	protected $_name = 'produtos_validacoes_restricoes_usuarios';
	protected $_primary = array('id_validacao_usuario', 'id_usuario');
    protected $_sequence = false;

	public function save($idRestricao, $idUsuario) {
		try{
			return $this->insert([
				'id_validacao_restricao' => $idRestricao,
				'id_usuario' => $idUsuario
			]);
		}catch(Exception $e){
			return false;
		}
	}

	public function getData($where=null){
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('c'=>'comercializacao.v_taxas_agrupamento'), '*');


		if (is_array($where)) {
			$temp = '';
			if (isset($where['id_estado']) or isset($where['id_municipio'])) {
				if($where['id_estado']) {
					$temp = " where id_estado = " . $where['id_estado'];
					unset($where['id_estado']);
				};
				if($where['id_municipio']) {
					$temp = " where sm.id = " . $where['id_municipio'];
					unset($where['id_municipio']);
				}

				$select->where('
				c.id IN (
					select
						id_taxa_agrupamento
					from
						comercializacao.taxas_agrupamento_municipios m left join
						sistema.municipios sm on m.id_municipio = sm.id
					' . $temp . '
				)');
			}

			foreach ($where as $clause) {

				$field = $clause['field'];
				$operator = $clause['operator'];
				$value = $clause['value'];

				$select->where("$field $operator ?", $value);
			}
		} elseif ($where != '') {
			$select->where($where);
		}

		$select->order($this->_order);

		return $select;
	}

	public function clearUsuarios($id) {
		try {
			return $this->getAdapter()->query("delete from produto.produtos_validacoes_restricoes_usuarios where id_validacao_restricao = $id");
		} catch (Exception $e) {
			return false;
		}
	}

	public function getUsuariosRelacionados($idRestricao) {
		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->where('id_validacao_restricao = ?', $idRestricao);
		
		$ret = array();
		$Rs = $this->fetchAll($select);
		if ($Rs->count()) {
			foreach ($Rs as $Row) {
				$ret[] = $Row->id_usuario;
			}
		}
		
		return $ret;
	}
}
