<?php
 
 class Sistema_Model_AssessoriasCorretores extends Agro_Db_Table_Abstract {
 	protected $_schema = 'sistema';
 	protected $_name = 'assessorias_corretores';
 	protected $_primary = 'id_corretor';

 	public function save(array $dados) {
		$Row = $this->getRow($dados['id_corretor']);
		$Row->id_corretor   = $dados['id_corretor'];
		$Row->id_assessoria = $dados['id_assessoria'];
		$Row->vl_percentual = number_format(str_replace(',', '.', $dados['vl_percentual']), 2, '.', '');
		return $Row->save();
 	}

	/**
	* Bsuca corretores e monta combo com "id_corretoror" para assessorias
	*/
	public function getComboAssessoria() {
		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array('c' => 'sistema.corretores'), array('id as id_corretor','ds_nome_fantasia','ds_nome_abreviado', 'id_usuario'));
		$select->joinLeft(array('ac' => 'sistema.assessorias_corretores'), 'c.id = ac.id_corretor', 'vl_percentual');
		$select->where('c.fl_ativo = true');
		$select->order('c.ds_nome_abreviado');
		$Rs = $this->fetchAll($select);

		return $Rs->toArray();
	}

	public function getData($where) {
		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array('ae' => 'sistema.assessorias_corretores'), '*');
		$select->join(array('c' => 'sistema.corretores'), 'ae.id_corretor = c.id', 'ds_nome_fantasia');
		$select->order('c.ds_nome_fantasia');

		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 getPercentualByCorretor($idCorretor) {
		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array('ae' => 'sistema.assessorias_corretores'), 'vl_percentual');
		$select->where('id_corretor = ?', $idCorretor);

		return $this->getAdapter()->fetchOne($select);
	}

	public function getAssessoriaByCorretor($idCorretor, $dtCriacao = '') {
		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array('ae' => 'sistema.assessorias_corretores'), 'vl_percentual');
		$select->join(array('a' => 'sistema.assessorias'), 'ae.id_assessoria = a.id', 
			array('id', 'cpf_cnpj', 'ds_nome_assessoria', 'ds_email', 'ds_telefone', 'tp_tipo', 'tp_comissao'));
		$select->where('ae.id_corretor = ?', $idCorretor);

		if ($dtCriacao) {
			$select->where("ae.dt_criacao <= '".$dtCriacao."'");
		}

		return $this->fetchRow($select);
	}
}
