<?php

class Produto_Model_Condicaopagamentoproponente extends Agro_Db_Table_Abstract {
	protected $_schema = 'produto';
	protected $_name = 'condicoes_pagamento_proponentes';
	protected $_primary = array('id_condicao_pagamento', 'id_proponente');
	
	public function save($values) {
		$Row = $this->find($values['id_condicao_pagamento'], $values['id_proponente'])->current();
		if (!$Row) $Row = $this->createRow();
		
		$Row->id_condicao_pagamento = $values['id_condicao_pagamento'];
		$Row->id_proponente = $values['id_proponente'];
		
		return $Row->save();
	}
	
	public function getData($where=null){
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('p'=>'seguro.proponentes'), '*');
		
		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 
					produto.condicoes_pagamento_proponentes
				where 
					id_proponente in (
						select
							id_proponente
						from
							produto.condicoes_pagamento_proponentes
						where
							id_condicao_pagamento in (
								select 
									id
								from
									produto.condicoes_pagamento
								where 
									id_produto = (select id_produto from produto.condicoes_pagamento where id = {$where['id_condicao_pagamento']}))))");
			
			
		} else {
			$select->where(" p.id IN (select id_proponente from produto.condicoes_pagamento_proponentes where id_condicao_pagamento = {$where['id_condicao_pagamento']})");
		}
		
		$select->order($this->_order);
		return $this->_db->fetchAll($select);
	}
	
	public function desmarcaProponete($id_condicao_pagamento, $id_proponente) {
		return $this->_db->query("delete from produto.condicoes_pagamento_proponentes where id_condicao_pagamento = $id_condicao_pagamento and id_proponente = $id_proponente");
	}
	
	public function getProponentesRelacionados($id) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('cpp' => 'produto.condicoes_pagamento_proponentes'), null);
		$Select->join(array('p' => 'seguro.proponentes'), 'cpp.id_proponente = p.id', array('id', 'ds_nome_proponente', 'cpf_cnpj'));
		$Select->where("id_condicao_pagamento = ?", $id);
		$Select->order("ds_nome_proponente");
		
		return $this->fetchAll($Select);
	}
}