<?php

class Sistema_Model_CorretoresArquivos extends Agro_Db_Table_Abstract {
	protected $_schema = 'sistema';
	protected $_name = 'corretores_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_corretor = $data['id_corretor'];

		if (!empty($data['id_usuario_criacao'])) {
            $Row->id_usuario_criacao = $data['id_usuario_criacao'];
        }
		
		return $Row->save();
	}
	
	public function getData($where) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('ca' => 'sistema.corretores_arquivos'), '*');
		$select->join(array('c' => 'sistema.corretores'), 'ca.id_corretor = c.id', '*');
		
		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 getCorretorArquivos($idCorretor) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('ca'=>'sistema.corretores_arquivos'),'*');
		$select->join(array('ta'=>'sistema.tipo_arquivo_corretor'),'ca.id_tipo_arquivo = ta.id','ds_tipo_arquivo');
		
		$select->where('ca.fl_del = false and ' . 
			$this->getAdapter()->quoteInto('ca.id_corretor = ?',$idCorretor)
		);

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