<?php

class Produto_CoberturaEventoController extends Agro_Controller_Action {
	
	public function getModel() {
		return new Produto_Model_CoberturasEventos();
	}
	
	public function indexAction() {
		
		if ($this->getRequest()->isPost()) {
			$this->saveAction();
		}

		if ($this->getRequest()->getParam('id')) {
			
			$Cobertura = new Produto_Model_Coberturas();
			$Row = $Cobertura->getRow($this->getRequest()->getParam('id'));
			
			$this->view->title = "Gerência de Coberturas » Eventos";
			$this->view->id = $this->getRequest()->getParam('id');
			$this->view->cobertura = $Row['ds_nome_cobertura'];
			
			$CoberturaEvento = new Produto_Model_CoberturasEventos();
			//$this->view->relacionados = $CoberturaEvento->getEventos($this->getRequest()->getParam('id'));
            $this->view->coberturaEventos = $CoberturaEvento->getCoberturaEventos($this->getRequest()->getParam('id'));
			
			$this->view->back = '/produto/cobertura';
		}
	}

	public function saveAction() {
		$Model = $this->getModel();
		
        try {
            $Model->delete($this->getRequest()->getParam('id_cobertura'), 'id_cobertura');
            
            if(is_array($this->getRequest()->getParam('ar_eventos'))) {
            	
            	$arEventosSeguradora = $this->getRequest()->getParam('ar_eventos_seguradora');

                foreach ($this->getRequest()->getParam('ar_eventos') as $idEvento) {
                    $data = array();
                    $data['id_cobertura']         = $this->getRequest()->getParam('id_cobertura');
                    $data['id_evento']            = $idEvento;
                    $data['cd_evento_seguradora'] = $arEventosSeguradora[$idEvento];

                    $Model->insert($data);
                }
            }
			$this->view->showMessage( MSG_SUCCESS, 'success');
			
        } catch (Exception $e) {
			$this->view->showMessage( MSG_ERROR, 'error');
        }        
	}

}
