<?

class Sinistro_AgendamentorevistoriaController extends Agro_Controller_Action{
	
	public function getdadosrevistoriaAction() {
		
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
			
		if($this->getRequest()->getParam('id_proposta') && $this->getRequest()->getParam('id_cobertura')){
			
			$idProposta = $this->getRequest()->getParam('id_proposta');
			$idCobertura = $this->getRequest()->getParam('id_cobertura');
						
				
			$VistoriaLaudoFinal = new Sistema_Model_VistoriasLaudosFinais();
			$arrayVistorias = $VistoriaLaudoFinal->getVistFinaisByPropostaCobertura($idProposta, $idCobertura);

			$data = array(
				'vistorias' => $arrayVistorias
			);
			
			// Executa na operação Editar Agendamento			
			if($this->getRequest()->getParam('id_revistoria')){
				
				$idRevistoria = $this->getRequest()->getParam('id_revistoria');
				/* Busca os dados da revistoria */
				$Revistoria = new Sistema_Model_Revistorias();
				$rs = $Revistoria->find($idRevistoria)->current();

				$data['ds_motivo'] = $rs['ds_motivo'];
				$data['fl_remunerada'] = $rs['fl_remunerada'];
				/* Busca os ids das vistorias selecionadas na revistoria*/
				$RevistoriaVistoria = new Sistema_Model_RevistoriasVistorias();
				$checkedsVistorias = $RevistoriaVistoria->getVistoriasByRevistoria($idRevistoria);

				/* Informa se a vistoria já foi ou não selecionada no agendamento */					
				for($i = 0; $i < count($data['vistorias']); $i++){
					if(in_array($data['vistorias'][$i]['id_vistoria'], $checkedsVistorias)){
						$data['vistorias'][$i]['checked'] = true;
					}else{
						$data['vistorias'][$i]['checked'] = false;
					}
				}
			}

			$this->getResponse()->setBody(Zend_Json::encode($data));
		}
	}

	public function getdadosagendamentorevistoriaAction() {
		
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
			
		// Executa na operação Editar Agendamento			
		if($this->getRequest()->getParam('id_agendamento')){
			
			$idAgendamento = $this->getRequest()->getParam('id_agendamento');
			
			/* Busca os dados do agendamento */
			$Agendamento = new Sistema_Model_Agendamentos();
			$rs = $Agendamento->find($idAgendamento)->current();

			$data['turno_revistoria'] = $rs['ds_turno'];
			$data['dt_revistoria'] = Agro_Util::formatDate($rs['dt_agendamento'], 'dd/MM/yyyy');
		}

		$this->getResponse()->setBody(Zend_Json::encode($data));
	}
	
	public function revistoriaAction(){
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$erro = array();
		
		$idRevistoria    = $this->getRequest()->getParam('id_revistoria');
		$dsMotivo        = $this->getRequest()->getParam('ds_motivo');
		$flRemunerada    = $this->getRequest()->getParam('fl_remunerada');
		$vistoriasFinais = $this->getRequest()->getParam('vistorias_finais');
		
		/* Verifica se os campos de motivo e remuneracao foram preenchidos*/
		if(!$dsMotivo || !$flRemunerada){
			$erro[] = array(
				'error' => 'Preencha os campos corretamente.',
				'id'  => 'form'
			);			
		}
		
		/* Verifica se alguma vistoria final foi selecionada */
		if(!is_array($vistoriasFinais) || count($vistoriasFinais) == 0){
			
			$erro[] = array(
				'error' => 'Selecione pelo menos uma vistoria final.',
				'id'  => 'vistorias_finais'
			);
			
		}
		
		/* Se não houve erros, insere ou edita o agendamento*/
		if(count($erro) == 0){
			if(!$idRevistoria){
				$res = $this->inserirRevistoria();
			} else{
				$res = $this->editarRevistoria();
			}	
				
			if(!$res){
				$erro[] = array(
					'error' => $res, //'Erro ao tentar agendar a revistoria.',
					'id'  => ''
				);
			}
		}
		
		$this->getResponse()->setBody(Zend_Json::encode($erro));
	}

	public function agendamentorevistoriaAction(){
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$erro = array();
		
		$idAgendamento   = $this->getRequest()->getParam('id_agendamento_revistoria');
		$turnoRevistoria = $this->getRequest()->getParam('turno_revistoria');
		$dtRevistoria    = $this->getRequest()->getParam('dt_revistoria');
		
		/* Verifica se os campos de motivo e remuneracao foram preenchidos*/
		if(!$turnoRevistoria || !$dtRevistoria){
			$erro[] = array(
				'error' => 'Preencha os campos corretamente.',
				'id'  => 'form'
			);			
		}
		
		/* Se não houve erros, insere ou edita o agendamento*/
		if(count($erro) == 0){
			if(!$idAgendamento){
				$res = $this->inserirAgendamentoRevistoria();
			} else{
				$res = $this->editarAgendamentoRevistoria();
			}	
				
			if(!$res){
				$erro[] = array(
					'error' => $res, //'Erro ao tentar agendar a revistoria.',
					'id'  => ''
				);
			}
		}
		
		$this->getResponse()->setBody(Zend_Json::encode($erro));
	}
	
	public function inserirRevistoria(){
		
		$post = $this->getRequest()->getParams();
		
		$Db = Agro_Db_Table_Abstract::getDefaultAdapter();
		$Db->beginTransaction();
		
		try {
					
			//Inclusão na tabela vistorias
			$Vistoria = new Sistema_Model_Vistorias();
			$data = array('id_tipo' => '3');
			$idRevistoria = $Vistoria->insert($data);

			// Inclusão na tabela revistorias
			$Revistoria = new Sistema_Model_Revistorias();
			$data = array(
				'id_vistoria' => $idRevistoria,
				'ds_motivo' => $post['ds_motivo'],
				'fl_remunerada' => $post['fl_remunerada'] == 'S' ? 1 : 0
			);
			$Revistoria->insert($data);
			
			// Inclusão na tabela vistorias_coberturas
			$VistoriaCobertura = new Sistema_Model_VistoriasCoberturas();
			$data = array(
				'id_vistoria' => $idRevistoria,
				'id_cobertura' => $post['id_cobertura']
			);
			$VistoriaCobertura->insert($data);

			// Inclusão na tabela vistorias_empresas
			$VistoriaEmpresa = new Sistema_Model_VistoriasEmpresas();

			$ProcessoEmpresa = new Sinistro_Model_ProcessosEmpresas();
			$rs = $ProcessoEmpresa->getEmpresaByProcesso($post['id_processo']);
			$idEmpresa = $rs['id_empresa'];
			$data = array(
				'id_vistoria' => $idRevistoria,
				'id_empresa' => $idEmpresa
			);
			$VistoriaEmpresa->insert($data);

			// Inclusão na tabela revistorias_vistorias
			$RevistoriaVistoria = new Sistema_Model_RevistoriasVistorias();
			foreach ($post['vistorias_finais'] as $vist) {
				$RevistoriaVistoria->insert(array('id_revistoria'=>$idRevistoria, 'id_vistoria'=>$vist));
			}
			
			// Inclusão na tabela vistorias_itens_segurados
			$VistoriaItemSegurado = new Sistema_Model_VistoriasItensSegurados();
			$itens = $VistoriaItemSegurado->getItensByVistoria($post['vistorias_finais']);
			foreach ($itens as $it) {
				$VistoriaItemSegurado->insert(array('id_vistoria'=>$idRevistoria, 'id_item_segurado'=>$it));
			}
			
			$Db->commit();

			return true;
		} catch (Exception $e) {
			$Db->rollback();
			echo "Mensagem de erro: <br /><br />" . $e->getMessage();
			return false;
		}
	}

	public function inserirAgendamentoRevistoria(){
		
		$post = $this->getRequest()->getParams();
		
		$Db = Agro_Db_Table_Abstract::getDefaultAdapter();
		$Db->beginTransaction();
		
		try {
					
			// Inclusão na tabela agendamentos
			$Agendamento = new Sistema_Model_Agendamentos();
			$data = array(
				'ds_turno' => $post['turno_revistoria'],
				'dt_agendamento' => $post['dt_revistoria']
			);
			$idAgendamento = $Agendamento->insert($data);

			
			// Inclusão na tabela vistorias_agendamentos
			$VistoriaAgendamento = new Sistema_Model_VistoriasAgendamentos();
			$data = array(
				'id_vistoria' => $post['id_revistoria_agendamento'],
				'id_agendamento' => $idAgendamento
			);
			$VistoriaAgendamento->insert($data);

			$Db->commit();

			return true;
		} catch (Exception $e) {
			$Db->rollback();
			echo "Mensagem de erro: <br /><br />" . $e->getMessage();
			return false;
		}
	}
	
	public function editarRevistoria(){
		
		$post = $this->getRequest()->getParams();
		
		$Db = Agro_Db_Table_Abstract::getDefaultAdapter();
		$Db->beginTransaction();
		try {	
			// Update na tabela revistorias;
			$Revistoria = new Sistema_Model_Revistorias();
			$data = array(
				'ds_motivo'  	 => $post['ds_motivo'],
				'fl_remunerada' => $post['fl_remunerada'] == 'S' ? 1 : 0
			);
			$Revistoria->update($data, 'id_vistoria = ' . $post['id_revistoria']);

			// Exclui antigos relacionamentos entre revistoria e vistoria
			$RevistoriaVistoria = new Sistema_Model_RevistoriasVistorias();
			$RevistoriaVistoria->delete($post['id_revistoria']);

			// Inclusão na tabela revistorias_vistorias
			foreach ($post['vistorias_finais'] as $vist) {
				$RevistoriaVistoria->insert(array('id_revistoria'=>$post['id_revistoria'], 'id_vistoria'=>$vist));
			}
			
			// Exclui antigos relacionamentos entre vistoria e itens segurados
			$VistoriaItemSegurado = new Sistema_Model_VistoriasItensSegurados();
			$VistoriaItemSegurado->delete($post['id_revistoria']);
			
			// Inclusão na tabela vistorias_itens_segurados
			$itens = $VistoriaItemSegurado->getItensByVistoria($post['vistorias_finais']);
			foreach ($itens as $it) {
				$VistoriaItemSegurado->insert(array('id_vistoria'=>$post['id_revistoria'], 'id_item_segurado'=>$it));
			}
			
			$Db->commit();

			return true;
		} catch (Exception $e) {
			$Db->rollback();
			echo "Mensagem de erro: <br /><br />" . $e->getMessage();
			return false;
		}
	}

	public function editarAgendamentoRevistoria(){
		
		$post = $this->getRequest()->getParams();
		
		$Db = Agro_Db_Table_Abstract::getDefaultAdapter();
		$Db->beginTransaction();
		try {	
			// Update na tabela agendamentos;
			$Agendamento = new Sistema_Model_Agendamentos();
			$data = array(
				'ds_turno' => $post['turno_revistoria'],
				'dt_agendamento' => $post['dt_revistoria']
			);
			$Agendamento->update($data, 'id = ' . $post['id_agendamento_revistoria']);
			
			$Db->commit();

			return true;
		} catch (Exception $e) {
			$Db->rollback();
			echo "Mensagem de erro: <br /><br />" . $e->getMessage();
			return false;
		}
	}
	
	public function excluirrevistoriaAction(){
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$idRevistoria    = $this->getRequest()->getParam('id_revistoria');
				
		$Db = Agro_Db_Table_Abstract::getDefaultAdapter();
		$Db->beginTransaction();
		try {			
			// Exclui vistoria
			$Vistoria = new Sistema_Model_Vistorias();
			$Vistoria->remove($idRevistoria);
			
			// Exclui revistoria
			$Revistoria = new Sistema_Model_RevistoriasVistorias();
			$Revistoria->delete($idRevistoria);
			
			$Db->commit();
			
			$this->getResponse()->setBody(Zend_Json::encode(true));
		} catch (Exception $e) {
			$Db->rollback();
			echo "Mensagem de erro: <br /><br />" . $e->getMessage();
			
			$this->getResponse()->setBody(Zend_Json::encode(false));
		}
	}
	
	public function excluiragendamentorevistoriaAction(){
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$idAgendamento    = $this->getRequest()->getParam('id_agendamento');
				
		$Db = Agro_Db_Table_Abstract::getDefaultAdapter();
		$Db->beginTransaction();
		try {			
			// Exclui vistoria relacionada com o agendamento
			$VistoriaAgendamento = new Sistema_Model_VistoriasAgendamentos();
			$VistoriaAgendamento->delete($idAgendamento);
			
			// Exclui o agendamento
			$Agendamento = new Sistema_Model_Agendamentos();
			$Agendamento->delete($idAgendamento);
			
			$Db->commit();
			
			$this->getResponse()->setBody(Zend_Json::encode(true));
		} catch (Exception $e) {
			$Db->rollback();
			echo "Mensagem de erro: <br /><br />" . $e->getMessage();
			
			$this->getResponse()->setBody(Zend_Json::encode(false));
		}
	}
}