<?php

class Sinistro2_MotivoquadranaovistoriadaController extends Agro_Controller_Action {
	public $_columnList = array('ds_motivo' => 'Motivo', 'ds_status' => "Status", 'ds_descricao' => 'Tipo');
	
	private $mandatoryFormFields = array('ds_motivo' => 'Motivo', 'id_status' => 'Status', 'id_tipo_motivo_quadra_nao_vistoriada' => 'Tipo');

	public function init() {
		$this->view->title = 'Sistema » Cadastro » Motivo quadra não vistoriada';
	}
	
	public function setBack() {
		$this->view->back = '/sistema/motivoquadranaovistoriada';
	}
	
	public function getModel() {
		return new Sinistro2_Model_MotivosQuadraNaoVistoriada();
	}
	
	public function getForm() {
		return new Sinistro2_Form_MotivoQuadraNaoVistoriada();
	}

	public function formAction(): void
	{
		$this->view->form = $this->getForm();
		$this->view->title .= ' » Formulário';

		$idMotivo = $this->getRequest()->getParam('id');
		$modelMotivos = new Sinistro2_Model_MotivosQuadraNaoVistoriada();

		if ($this->getRequest()->isPost()) {
			try {
				$params = $this->getRequest()->getParams();

				$this->checkMandatoryFormFields($params);

				$database = Agro_Db_Table_Abstract::getDefaultAdapter();
				$database->beginTransaction();

				$modelTiposMotivo = new Sinistro2_Model_MotivosQuadraNaoVistoriadaTipos();
				
				$idMotivo = $modelMotivos->save([
					'id' => $params['id'],
					'id_status' => $params['id_status'],
					'ds_motivo' => $params['ds_motivo'],
					'id_motivo_quadra_nao_vistoriada' => $params['id_motivo_quadra_nao_vistoriada'],
					'id_tipo_motivo_quadra_nao_vistoriada' => $params['id_tipo_motivo_quadra_nao_vistoriada']
				]);

				$database->commit();

				if ($idMotivo) {
					$arrMotivo = $modelMotivos->fetchAll("id = {$idMotivo}")->toArray();
					
					$this->_forward($this->_forwardSettings['action'], $this->_forwardSettings['controller'], $this->_forwardSettings['module'], array());
					$this->view->showMessage(MSG_SUCCESS, 'success');
				}
			} catch (Exception $e) {
				if ($database) {
					$database->rollback();
				}
				
				$this->view->showMessage($e->getMessage(), 'error');
				$this->view->form->populate($this->getRequest()->getParams());
			}
		}
		
		if ($idMotivo) {
			$arrMotivo = $modelMotivos->fetchAll("id = {$idMotivo}")->toArray();
			$this->view->form->populate($arrMotivo[0]);
		}
	}

	private function checkMandatoryFormFields(array $fields): void
	{	
		$errorMessage = $separator = '';

		foreach ($this->mandatoryFormFields as $fieldId => $label) {
			if (empty($fields[$fieldId])) {
				$errorMessage .= $separator . $label;
				$separator = ', ';
			}
		}

		if (!empty($errorMessage)) {
			throw new Exception("Necessário informar os campos: {$errorMessage}.");
		}
	}
	
	public function deleteAction(): void
	{
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		try {
			$result = [];
			$database = Agro_Db_Table_Abstract::getDefaultAdapter();

			$database->beginTransaction();

			$this->getModel()->delete((int) $this->getRequest()->getParam('id'));

			$database->commit();

			$result['message'] = MSG_SUCCESS;
			$result['status'] = true;
		} catch (Exception $e) {
			$database->rollback();

			$result['message'] = $this->view->escape($e->getMessage());
			$result['status'] = false;
		}

		$this->getResponse()->setBody(Zend_Json::encode($result));
	}
	
	public function getFilter() {
		$where = array();
		
		if ($this->getRequest()->getParam('ds_motivo')) {
			$where[] = array (
				'field' => 'm.ds_motivo',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_motivo').'%'
			);
		}
				
		if ($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array (
				'field' => 'm.fl_ativo',
				'operator' => ' = ',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}		
		
		return $where;
	}
}