<?php

class Sinistro2_Model_AvisosEventos extends Agro_Db_Table_Abstract {
	protected $_rowClass = 'Sinistro2_Model_Row_AvisoEvento';
	protected $_schema = 'sinistro';
	protected $_name = 'avisos_eventos';
	protected $_primary = array('id_aviso', 'id_evento');
	public $_order = 'id_aviso';
	protected $_sequence = false;
	
	
	public function getAvisosEventos($idAviso){
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('a'=>'sinistro.avisos_eventos'),array('id_aviso','id_evento'));
		$select->join(array('e'=>'produto.eventos'),'a.id_evento = e.id',array('ds_nome_evento'));
		$select->where($this->getAdapter()->quoteInto('a.id_aviso = ?',$idAviso));

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

	public function getAvisosEventosQueda(array $idsAvisos): ?array
	{
		$select = $this->select()
			->setIntegrityCheck(false)
			->from(['sae' => 'sinistro.avisos_eventos'], false)
			->join(['sa' => 'sinistro.avisos'], 'sa.id = sae.id_aviso', 'string_agg(sa.id::text, \', \') AS ids_avisos')
			->where('sa.id IN (?)', $idsAvisos)
			->where('sae.id_evento = ?', Produto_Model_Eventos::ID_EVENTO_GRANIZO)
			->where('sa.fl_ocorrencia_queda_parreiral IS TRUE');

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

	public function getEventosByPropostaCobertura($idProposta, $idCobertura){
		$select = $this->select();
		$select->setIntegrityCheck(false);

		$select->from(array('av'=>'sinistro.avisos'), false);
		$select->join(array('ae'=>'sinistro.avisos_eventos'),'ae.id_aviso = av.id', false);
		$select->join(array('ce'=>'produto.coberturas_eventos'),'ce.id_evento = ae.id_evento', 'id_evento');
		$select->join(array('e'=>'produto.eventos'),'e.id = ce.id_evento', 'ds_nome_evento');
		
		$select->where('av.id_proposta = ?', $idProposta);
		$select->where('ce.id_cobertura = ?',$idCobertura);

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