<?php

class Atendimento_Model_Row_Chamado extends Agro_Db_Table_Row_Abstract {

	public function empresaVistoriadora() {
		$Select = $this->select()->setIntegrityCheck(false);
    	$Select->from(array('sp' => 'sinistro.processos'), false);
    	$Select->join(array('pe' => 'sinistro.processos_empresas'), 'pe.id_processo = sp.id and pe.fl_ativo=true', false);
    	$Select->join(array('e' => 'sistema.empresas'), 'e.id = pe.id_empresa', 'ds_nome_fantasia');
    	$Select->where('sp.id_proposta = ?', $this->id_proposta);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function corretor() {
		$Select = $this->select()->setIntegrityCheck(false);
    	$Select->from(array('a' => 'atendimento.chamados'), false);
    	$Select->join(array('b' => 'seguro.propostas_corretores'), 'a.id_proposta = b.id_proposta', false);
    	$Select->join(array('c' => 'sistema.corretores'), 'b.id_usuario = c.id_usuario', 'ds_nome_fantasia');
    	$Select->where('a.id = ?', $this->id);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function destinatario() {
		switch ($this->ds_tipo_destinatario) {
			case Atendimento_Model_ChamadoDestinatario::DESTINATARIO_CORRETOR:
				return 'Corretor';
			case Atendimento_Model_ChamadoDestinatario::DESTINATARIO_EMPRESA_VISTORIA:
				return 'Vistoriador';
			case Atendimento_Model_ChamadoDestinatario::DESTINATARIO_SEGURADORA:
				return 'Seguradora';
		}
	}

	public function arquivos() {
		$Arquivos = new Atendimento_Model_Chamadoarquivos();
		return $Arquivos->getArquivosChamados($this->id);
	}

	public function respostas() {
		$Model = new Atendimento_Model_Chamado();
		return $Model->getFilhos($this->id);
	}

	public function criador() {
		$Select = $this->select()->setIntegrityCheck(false);
    	$Select->from(array('c' => 'atendimento.chamados'), 'dt_criacao');
    	$Select->join(array('u' => 'sistema.usuarios'), 'c.id_usuario_criacao = u.id', 'ds_nome_usuario');
    	$Select->where('c.id = ?', $this->id);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
	}

	public function ultimaAlteracao() {
    	$Select->from(array('c' => 'atendimento.chamados'), 'dt_criacao');
    	$Select->joinLeft(array('u' => 'sistema.usuarios'), 'c.id_usuario_criacao = u.id', 'id as id_usuario_alteracao');
    	$Select->where('c.id_parent = ?', $this->id)->order('c.dt_criacao DESC')->limit(1);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
	}

	public function status() {
		$Select = $this->select()->setIntegrityCheck(false);
    	$Select->from(array('s' => 'sistema.status'), 'ds_status');
    	$Select->where('s.id = ?', $this->id_status);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

}
