<?php

class Sistema_Model_VistoriasAgendamentos extends Agro_Db_Table_Abstract {
	protected $_schema = 'sistema';
	protected $_name = 'vistorias_agendamentos';
	protected $_primary = array('id_vistoria','id_agendamento');
	protected $_sequence = false;

	public function save(array $data) {
		$Row = $this->find($data[id_vistoria],$data[id_agendamento])->current();
		if (!$Row){
			$Row = $this->createRow();
		}
		$Row->id_vistoria = $data[id_vistoria];
		$Row->id_agendamento = $data[id_agendamento];

  		if ($Row->save()) {
  			if($data[id_processo]){
  				$this->marcaAvisoLido($Row->id_agendamento, $data[id_processo]);
  			}

  			return true;
  		}


	}

	public function delete($idAgendamento) {
		$select = "	delete from	{$this->_schema}.{$this->_name} where id_agendamento = $idAgendamento";
		$this->_db->query($select);
	}

	public function deleteVistoriaAgendamento($idVistoria) {
		$select = "	delete from	{$this->_schema}.{$this->_name} where id_vistoria = $idVistoria";
		$this->_db->query($select);
	}

	private function marcaAvisoLido($idAgendamento, $idProcesso){

		$ModelProcesso = new Sinistro2_Model_Processos();
		$Processo = $ModelProcesso->fetchRow("id = $idProcesso");
		$ModelAgendamento = new Sistema_Model_Agendamentos();
		$Agendamento = $ModelAgendamento->fetchRow("id = $idAgendamento");

		$ModelAviso = new Sinistro2_Model_AvisosSinistro();
		$data = array('fl_novo' => 'false');
		$Aviso = $ModelAviso->update($data, "id_proposta = $Processo->id_proposta AND dt_aceitacao < to_date('$Agendamento->dt_agendamento','yyyy-mm-dd') AND fl_novo is true");
	}
}