<?php

class Comercializacao_Model_RelacionarTaxasProponente extends Agro_Db_Table_Abstract {
	protected $_schema = 'comercializacao';
	protected $_name = 'taxas_agrupamento_proponentes';
	protected $_primary = array('id_taxa_agrupamento', '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.taxas_agrupamento_proponentes
				where 
					id_proponente in (
						select
							id_proponente
						from
							comercializacao.taxas_agrupamento_proponentes
						where
							id_taxa_agrupamento in (
								select 
									id
								from
									comercializacao.taxas_agrupamento
								where 
									id_produto = (select id_produto from comercializacao.taxas_agrupamento where id = {$where['id_taxa']}))))");
			
			
		} else {
			$select->where(" p.id IN (select id_proponente from comercializacao.taxas_agrupamento_proponentes where id_taxa_agrupamento = {$where['id_taxa']})");
		}
		
		$select->order($this->_order);
		//die($select);
		return $this->_db->fetchAll($select);
	}
	
	
	public function delete($id_taxa, $id_proponente) {
		$sql = "delete from comercializacao.taxas_agrupamento_proponentes where id_taxa_agrupamento = $id_taxa and id_proponente = $id_proponente";
		return $this->_db->query($sql);
	}
}