<?php

class Seguro_Model_PropostasProponentesSocios extends Agro_Db_Table_Abstract {
	protected $_schema = 'seguro';
	protected $_name = 'propostas_proponentes_socios';
	protected $_primary = 'id';
	public $_order = 'ds_nome_socio asc';
	
	public function save($data) {
		
		try {
			$Row = $this->getRow($data['id']);
			
			$Row->tp_pessoa = $data['tp_pessoa'] ? $data['tp_pessoa'] : 'F';
			$Row->ds_nome_socio = $data['ds_nome_socio'];
			$Row->cpf_cnpj = $data['cpf_cnpj'];
			$Row->id_parent = $data['id_parent'] ? $data['id_parent'] : $Row->id_parent;
			$Row->tp_relacionamento= $data['tp_relacionamento'] ? $data['tp_relacionamento'] : '';
			$Row->cnpj_segurado = $data['cnpj_segurado'] ? $data['cnpj_segurado'] : $Row->cnpj_segurado;

			return $Row->save();
		} catch (Exception $e) {
			if ($e->getCode() == 23505) {
				$this->setMessage(MSG_CPFCNPJ_EXISTENTE);
			}

			return false;
		}
	}
	
	
	public function getSociosByCnpjSegurado($cnpj_segurado, $id_parent=''){
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_proponentes_socios'),array('id','ds_nome_socio','cpf_cnpj','tp_pessoa','id_parent','tp_relacionamento'));
		$Select->where('cnpj_segurado = ?', $cnpj_segurado);
		if($id_parent && $id_parent != 'null'){
			$Select->where('id_parent = ?', $id_parent);
		}else{
			$Select->where('id_parent is null');
		}
		$Row = $this->fetchAll($Select);
		//die($Select);
		if ($Row) {
			return $Row->toArray();
		}
		return;
	}
	
	public function getSocio($id){
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_proponentes_socios'),array('id','cnpj_segurado','ds_nome_socio','cpf_cnpj','tp_pessoa','id_parent','tp_relacionamento'));
		$Select->where('id = ?', $id);

		$Row = $this->fetchRow($Select);
		if ($Row) {
			return $Row->toArray();
		}
		return;
	}
	
	public function removeSocio($id){
		try{
			
			$this->getAdapter()->query("DELETE FROM seguro.propostas_proponentes_socios WHERE id = $id");
			$this->getAdapter()->query("DELETE FROM seguro.propostas_proponentes_socios WHERE id_parent = $id");
			
			return true;
		
		}catch (Exception $e){
			die($e);
		}
	}
	
	
}