<?php
 
 class Sistema_Model_AssessoriasArquivos extends Agro_Db_Table_Abstract {
 	protected $_schema = 'sistema';
 	protected $_name = 'assessorias_arquivos';
 	protected $_primary = 'id';

 	public function save($data) {
 		$TipoArquivo = new Sistema_Model_TipoArquivoCorretor();
 		$Row = $this->getRow($data['id']);

 		$Row->id_tipo_arquivo = $data['id_tipo_arquivo'];
 		$Row->ds_nome_arquivo = $data['ds_nome_arquivo'];
 		$Row->id_assessoria = $data['id_assessoria'];

 		return $Row->save();
 	}

 	public function getData($where) {
 		$select = $this->select()->setIntegrityCheck(false);
 		$select->from(array('aa' => 'sistema.assessorias_arquivos'), array('dt_criacao','id','id_tipo_arquivo','ds_nome_arquivo'));
 		$select->join(array('a' => 'sistema.assessorias'), 'aa.id_assessoria = a.id', 'id as id_assessoria');
 		$select->join(array('tp' => 'sistema.tipo_arquivo_corretor'), 'aa.id_tipo_arquivo = tp.id', array('ds_tipo_arquivo','ds_chave_tipo_arquivo'));

 		if(is_array($where)) {
 			foreach($where as $clause) {
 				$field = $clause['field'];
 				$operator = $clause['operator'];
 				$value = $clause['value'];

 				$select->where("$field $operator ?", $value);
 			}
 		} elseif ($where != '') {
 			$select->where($where);
 		}

 		return $select;
 	}

 	public function getAssessoriaArquivos($idAssessoria) {
 		$select = $this->select()->setIntegritCheck(false);
 		$select->from(array('aa' => 'sistema.assessorias_arquivos'), '*');
 		$select->join(array('ta' => 'sistema.tipo_arquivo_corretor'), 'aa.id_tipo_arquivo = ta.id', 'ds_tipo_arquivo');

 		$select->where('aa.fl_del = false and ' .
 			$this->getAdapter()->quoteInto('aa.id_assessoria = ?', $idAssessoria)
 		);

 		return $this->fetchAll($select)->toArray();
 	}

	public function nextSequenceId() {
		$value = $this->_db->fetchOne("SELECT NEXTVAL('sistema.assessorias_arquivos_id_seq')");
		return $value;
	} 	
 }