<?php

class Comercializacao_Model_RelacionarProponente extends Agro_Db_Table_Abstract {
	protected $_schema = 'comercializacao';
	protected $_name = 'comercializacoes_proponentes';
	protected $_primary = array('id_comercializacao', 'id_proponente');
	
	public function getData($where=null){
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('p'=>'seguro.proponentes'), '*');
		$select->joinLeft(array('m' => 'sistema.municipios'), 'p.id_municipio = m.id', 'ds_nome_municipio');
		$select->joinLeft(array('e' => 'sistema.estados'), 'm.id_estado = e.id', 'ds_sigla');
		
		if (is_array($where)) {
			if($where['nome']) {
				$select->where("
					p.nome ilike '%{$where['nome']}%'");
			}
			
			if($where['cpf_cnpj']) {
				$select->where("
					p.cpf_cnpj = '{$where['cpf_cnpj']}'");
			}
		}
		
		//o 'in' determina se estao sendo mostrados os que estao vinculados ou os disponiveis
		if(!$where['in']) {
			//$select->where(" p.id NOT IN (select id_proponente from comercializacao.taxas_agrupamento_proponentes where id_taxa_agrupamento = {$where['id_taxa']})");
			
			$select->where(	
			" p.id NOT IN (
				select 
					id_proponente 
				from 
					comercializacao.comercializacoes_proponentes
				where 
					id_proponente in (
						select
							id_proponente
						from
							comercializacao.comercializacoes_proponentes
						where
							id_comercializacao in (
								select 
									id
								from
									comercializacao.comercializacoes
								where 
									id_produto = (select id_produto from comercializacao.comercializacoes where id = {$where['id_comercializacao']}))))");
			
			
		} else {
			$select->where(" p.id IN (select id_proponente from comercializacao.comercializacoes_proponentes where id_comercializacao = {$where['id_comercializacao']})");
		}
		
		$select->order($this->_order);
		//die($select);
		return $this->_db->fetchAll($select);
	}
	
	
	public function delete($id_comercializacao, $id_proponente) {
		$sql = "delete from comercializacao.comercializacoes_proponentes where id_comercializacao = $id_comercializacao and id_proponente = $id_proponente";
		return $this->_db->query($sql);
	}
}