<?php

class Agro_Controller_Action extends Zend_Controller_Action {
	protected $_forwardSettings = array();
	protected $_backAfterSave = true;
	protected $_columnList = '';
	protected $_paginator = true;
	protected $_cacheSearchName;
	protected $recordsPerPage;
	protected $_cache;
	protected $_user;
	protected $ambienteProducao = false;
    protected $_requestParams;
    protected $_return = ['erro' => false, 'mensagem' => 'Processamento concluído com sucesso.'];
    protected $protocoloUrlNovaSenha = 'https://';
    protected $parametrosUrlNovaSenha = '/login/novasenha/url/';
    protected $urlNovaSenha = 'agronet.agrobrasilseguros.com.br';

	public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
		parent::__construct($request, $response, $invokeArgs);

		if ($this->getRequest()->getParam('popup')) {
			$this->getHelper('layout')->setLayout('popup');
			$this->view->popoup = 1;
		}

		$this->_forwardSettings = array(
			'module' => $this->getRequest()->getModuleName(),
			'controller' => $this->getRequest()->getControllerName(),
			'action' => 'index'
		);

		$this->view->orderby = $this->getRequest()->getParam('o');
		$this->view->orderDirection = $this->getRequest()->getParam('s');
		$this->ambienteProducao = APPLICATION_ENV === 'production';
		$this->_requestParams = $this->getRequest()->getParams();
        $this->_user = Zend_Auth::getInstance()->getIdentity();

        if (!$this->ambienteProducao) {
            $this->protocoloUrlNovaSenha = 'http://';
            $this->urlNovaSenha = $_SERVER['HTTP_HOST'];
        }

		$this->populateMaisAcessados($this->getRequest()->getParams());
	}

	/**
	 * A cada clique na ação conta (insere na base) a ação que foi
	 * selecionada
	 */
	private function populateMaisAcessados($params) {
		if ($params['menu'] == 1) {
			$ModelMaisAcessados = new Log_Model_MaisAcessados();
			$User = Zend_Auth::getInstance()->getIdentity();
			$params['id_usuario'] = $User->id;
			$ModelMaisAcessados->save($params);
		}
		return true;
	}

	public function indexAction() {
		$this->view->title .= " » Listagem";
        $this->view->ambienteProducao = $this->ambienteProducao;
		$this->view->form = $this->getForm();

		$User = Zend_Auth::getInstance()->getIdentity();

		$Module = $this->getRequest()->getModuleName();
		$Controller = $this->getRequest()->getControllerName();

		$Session = new Zend_Session_Namespace('filtro');
		$params = $Session->{$Module}->{$Controller};

		if (is_object($this->view->form) && $params) {
			$this->view->form->populate($params);
		}
	}

	public function listAction() {
		$this->getHelper('layout')->disableLayout();

		$where = $this->getFilter();

		// Habilita ou Desabilita a paginacao pelo combo na tela
	  	if (array_key_exists('show_paginacao', $this->getRequest()->getParams())) {
			$this->_paginator = $this->getRequest()->getParam('show_paginacao');
		}

		$Module = $this->getRequest()->getModuleName();
		$Controller = $this->getRequest()->getControllerName();

		$Session = new Zend_Session_Namespace('filtro');
		$Session->{$Module}->{$Controller} = $this->getRequest()->getParams();

		$Model = $this->getModel();

		if ($this->getRequest()->getParam("o")) {
			$Model->_order = trim($this->getRequest()->getParam("o") .' '. $this->getRequest()->getParam("s"));
		}

		$recordsPerPage = ($this->recordsPerPage ? $this->recordsPerPage :  RECORDS_PER_PAGE);

		$Rs = $Model->fetchAllPaginator($where, $this->getRequest()->getParam('page'), $recordsPerPage, $this->_paginator);

		if ($this->_columnList) {
			$this->getHelper('ViewRenderer')->setNoRender();

			$List = new Agro_List_Table($this->_columnList, $Rs, $this->_paginator, $this->getRequest());
			$this->getResponse()->setBody($List->toString());
		} else {
			$this->view->paginator = $Rs;
		}
	}

	public function excelAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		ini_set('memory_limit','4096M');
		ini_set('max_execution_time',360);
		
		$where = $this->getFilter();

		$Module = $this->getRequest()->getModuleName();
		$Controller = $this->getRequest()->getControllerName();
		$Model = $this->getModel();

		if ($this->getRequest()->getParam("o")) {
			$Model->_order = trim($this->getRequest()->getParam("o") .' '. $this->getRequest()->getParam("s"));
		}

		$Rs = $Model->fetchAllPaginator($where);
		if ($Model->_columnExcel) {
			$Csv = new Agro_Plugin_Rs2Csv();
			$Csv->setTitles($Model->_columnExcel);
			$Csv->setRecordSet($Rs);
			$Csv->setType("application/octet-stream");
			$Csv->setFileName("pesquisa.csv");
			$Csv->setDisposition("attachment");
			$Csv->setSeparator(";");
			$Csv->getCsv();
		} else {
			$Csv = new Agro_Plugin_Rs2Csv();
			$Csv->setTitles($Model->_columnExcel);
			$Csv->setRecordSet(array('Excel não configurado'));
			$Csv->setType("application/octet-stream");
			$Csv->setFileName("notfound.csv");
			$Csv->setDisposition("attachment");
			$Csv->setSeparator(";");
			$Csv->getCsv();
		}
	}

	public function formAction() {
		try {
			$this->view->form = $this->getForm();
			$this->view->title .= ' » Formulário';
			$this->view->ambienteProducao = $this->ambienteProducao;
			$Model = $this->getModel();

			if (!$this->view->back) {
				$this->view->back = "/{$this->_forwardSettings['module']}/{$this->_forwardSettings['controller']}";
			}

			if ($this->getRequest()->isPost()) {

				if ($this->view->form->isValid($this->getRequest()->getPost())) {

					$this->beforeSave();

					if (method_exists($Model, 'save')) {
						try {
							$Row = $Model->save($this->getRequest()->getParams());



							if ($Row) {
								$this->view->showMessage(MSG_SUCCESS, 'success');
							} else {
								if ($Model->getMessages()) {
									$this->view->showMessage($Model->getMessages(), 'error');
								} else {
									$this->view->showMessage(MSG_ERROR, 'error');
								}

								$this->view->form->populate($this->getRequest()->getParams());
							}
						} catch (Exception $e) {
							$this->view->showMessage($e->getMessage(), 'error');
						}
					} else {
						$Row = $this->save($this->getRequest()->getParams());
					}

					if ($Row) {
						$this->afterSave($Row);
					}

					if ($this->_backAfterSave && $Row) {
						$this->view->back = '';
						$this->_forward($this->_forwardSettings['action'], $this->_forwardSettings['controller'], $this->_forwardSettings['module'], array());

					} else if ($Row && is_object($Row)) {
						$this->view->form->populate($Row->toArray());
					}
				} else {
					$Errors = $this->view->form->getMessages();
					$this->view->showMessage($this->getHtmlFormError($Errors), 'error');
					$this->view->form->populate($this->getRequest()->getParams());
				}
			} else if ($this->getRequest()->getParam('id')) {
				$row = $this->getRow();
				$this->view->form->populate($row);
			}
		} catch (Exception $e) {

			switch ($e->getCode()) {
				case 23505:
					$this->view->showMessage(MSG_UNIQUE, 'error');
					break;
				//forbidden
				case 403:
					$this->view->showMessage($e->getMessage(), 'error');
                    $this->view->form->populate($this->getRequest()->getParams());
					break;
			}

			//Agro_Util::informaErroAgronet($e->getMessage());

			return false;
		}

		/*if(isset($this->_getParam('edit')) && $this->_getParam('edit') == 0){
			$this->view->jQuery()->addJavascriptFile('/resources/javascript/sinistro2/disableall.js');
		}*/

	}

	/*
	 * Redireciona a página internamente
	 *
	 * ATENÇÃO
	 *
	 * Na nova versão do PHP a orientação a Objetos está melhor implementada e correta.
	 * Como no Zend o método forward é "final method" não é possível sobrescreve-lo
	 *
	 * Então se você utilizava este método, por favor substitua pelo metodo do Zend.
	 *
	 * Ex: $this->_forward($this->_forwardSettings['action'], $this->_forwardSettings['controller'], $this->_forwardSettings['module'], array());
	 *
	 * Vinicius Berni (09/11/2012)
	 *
	public function forward($settings, $params=array()) {
		$this->view->back = '';
		$this->_forward($settings['action'], $settings['controller'], $settings['module'], $params);
	}
	*/

	public function deleteAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = $this->getModel();
		$result = array();

		$Model->getAdapter()->beginTransaction();

		try {
			if ($Model->delete($this->getRequest()->getParam('id'))) {
				$result['execute'] = $Model->executeJsAfterDelete;
				$result['executeValue'] = $Model->executeJsValueAfterDelete;
				$result['message'] = MSG_SUCCESS;
				$result['status'] = true;

				$Model->getAdapter()->commit();
			} else {
				$result['message'] = MSG_ERROR;
				$result['status'] = false;

				$Model->getAdapter()->rollBack();
			}
		} catch (Exception $e) {
			if ($e->getCode() == 23503) {
				$result['message'] = $this->view->escape(MSG_DELETE_FK_ERROR);
			} else {
				$result['message'] = $this->view->escape($e->getMessage());
			}

			$result['status'] = false;

			$Model->getAdapter()->rollBack();

			Agro_Util::informaErroAgronet($e->getMessage());
		}

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

	public function activeAction() {
		$User = Zend_Auth::getInstance()->getIdentity();
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$result = array('status' => false);
		$Model = $this->getModel();

		if ($this->getRequest()->getParam('id')) {
			$Row = $Model->getRow($this->getRequest()->getParam('id'));
			$Old = $Row->toArray();

			if ($Row->fl_ativo) {
				$Row->fl_ativo = 0;
			} else {
				$Row->fl_ativo = 1;
			}

			if ($this->getRequest()->getParam('cb')) {
				if ($this->{$this->getRequest()->getParam('cb')}()) {
					if ($Row->save()) {
						$result['status'] = true;
					}
				}
			} else {
				if ($Row->save()) {
					$result['status'] = true;
				}
			}

			$result['ativo'] = $Row->fl_ativo;

			$info = $Model->info();
			$this->getResponse()->setBody(Zend_Json::encode($result));
		}
	}

	public function viewAction() {
		$this->getHelper('layout')->setLayout('popup');

		$this->view->data = $this->getRow();
        $this->view->ambienteProducao = $this->ambienteProducao;
		$this->setBack();
	}

	public function getRow() {
		if ($this->getRequest()->getParam('id')) {
			$params = explode(',', $this->getRequest()->getParam('id'));
			$Model = $this->getModel();
			if (count($params) == 1) {
				return $Model->find($params[0])->current()->toArray();
			}else if (count($params) == 2) {
				return $Model->find($params[0], $params[1])->current()->toArray();
			}
		}
	}

	// @param $Form		Objeto de formulario que contem os erros.
	// 		Este parametro opcional foi criado para arrumar erros em telas com
	// 		mais de um formulario.
	public function getHtmlFormError(array $error, $Form='') {
		$html = "";

		// Para compatibilidade com as telas anteriores e com um só form,
		// testa pra ver se o form foi passado ou nao.
		if($Form == '') {
			$Form = $this->view->form;
		}
		if (is_array($error)) {
			$html .= "Erros encontrados no formulário";
			$html .= "<ul class='ul_error'>";

			foreach ($error as $label => $messages) {
				$Form->{$label}->setAttrib('style', 'border: solid 2px #ff0000');
				$Label = $Form->{$label}->getLabel();
				$msg = "<ul>";
				if (is_array($messages)) {
					foreach ($messages as $message) {
						$msg .= "<li>$message</li>";
					}
				}
				$msg .= "</ul>";

				$html .= "<li>$Label: $msg</li>";
			}

			$html .= "</ul>";
		}

		return $html;
	}

	/**
	 * Valida os campos de todos os formulários utilizados em uma tela.
	 * Retorna html com mensagens de erro para cada campo inv�lido.
	 *
	 * @param array $forms
	 * @param array $post
	 * @return String $html
	 */
	public function getAllFormErros(array $forms, array $post, array $additionals=array()){

		$html = "";
		$text = "Erros encontrados no formulário";
		$text .= "<ul class='ul_error'>";

		$someError = false;

		if(count($forms) > 0){
			foreach($forms as $form){
				if(!$form->isValid($post)){
					$error = $form->getMessages();

					if(is_array($error) && count($error) > 0){
						$someError = true;
						foreach ($error as $label => $messages) {
							$msg = "<ul>";
							$form->{$label}->setAttrib('style', 'border: solid 2px #ff0000');
							$Label = $form->{$label}->getLabel();
							if (is_array($messages)) {
								foreach ($messages as $message) {
									$msg .= "<li>$message</li>";
								}
							}
							$msg .= "</ul>";

							$text .= "<li>$Label: $msg</li>";
						}
					}
				}
			}
		}

		if(count($additionals) > 0){
			foreach ($additionals as $item){
				$isValid = true;

				switch ($item['type']){
					case 'checkbox':
						if(array_key_exists('minCheckeds',$item) && $item['minCheckeds']){
							$minCheckeds = $item['minCheckeds'];
						}else{
							$minCheckeds = 1;
						}

						if(is_array($item['fields'])){
							if(count($item['fields']) > 0){
								$count = 0;
								foreach($item['fields'] as $field){
									if($post[$field])
										$count++;
								}

								if($count < $minCheckeds){
									$isValid = false;
								}

							}else{
								$erro = '
									<b>Erro! </b><br />
									Agro_Controller_Action::getAllFormErros(): O array com o nome dos campos
									para a validação dos checkboxes não pode estar vazio.';
								die($erro);
							}
						}elseif(is_string($item['fields'])){
							if(is_array($post[$item['fields']])){

								if(count($post[$item['fields']]) < $minCheckeds){
									$isValid = false;
								}
							}else{
								$isValid = false;
							}
						}else{
							$erro = '
									<b>Erro! </b><br />
									Agro_Controller_Action::getAllFormErros(): É esperado um array ou string
									com o nome do(s) campo(s) para a validação dos checkboxes.';
								die($erro);
						}

					break;
					case 'text':
						if(!array_key_exists($item['fields'],$post) || !$post[$item['fields']]){
							$isValid = false;
						}
					break;
					case 'radio':
						if(!array_key_exists($item['fields'],$post) || !$post[$item['fields']]){
							$isValid = false;
						}
					break;

					default:
						$erro = '
								<b>Erro! </b><br />
								Agro_Controller_Action::getAllFormErros(): É necessário definir um tipo
								de campo válido para a validação!. Ex.: array(\'type\' => \'text\')';
								die($erro);
					break;
				}

				if(!$isValid){
					$msg = "<ul>";
					$msg .= "<li>{$item['message']}</li>";
					$msg .= "</ul>";
					$text .= "<li>{$item['label']}: $msg</li>";
					$someError = true;
				}
			}
		}

		$text .= "</ul>";

		if($someError){
			$html = $text;
		}

		return $html;
	}

	public function loadAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = $this->getModel();

		$Row = $Model->find($this->getRequest()->getParam('id'))->current();

		$this->getResponse()->setBody(Zend_Json::encode($Row->toArray()));

	}

	public function getPageCache() {
		return $this->getRequest()->getParam('page');
	}

	public function isAjax($render=false) {
		$this->getHelper('layout')->disableLayout();

		if (!$render) {
			$this->getHelper('ViewRenderer')->setNoRender();
		}
	}

    public function validarUsuario(array $parametros)
    {
        if (empty($parametros['id'])) {
            Sistema_Model_Usuarios::validarPadraoUsuario($parametros['ds_nome_usuario']);
        }

        if (!empty($parametros['id_usuario'])) {
            $modelUsuarios = new Sistema_Model_Usuarios();
            $nomeUsuario = $modelUsuarios->getNameById($parametros['id_usuario']);

            if ($nomeUsuario !== $parametros['ds_nome_usuario']) {
                Sistema_Model_Usuarios::validarPadraoUsuario($parametros['ds_nome_usuario']);
            }
        }

        Sistema_Model_Usuarios::validarUsuarioExistente((int) $parametros['id_usuario'], $parametros['ds_nome_usuario']);
    }

    public function getUsuarioLogado()
    {
        return $this->_user;
    }

	public function save(){ return; }

	public function getForm(){ return; }

	public function getModel(){ return; }

	public function getFilter(){ return; }

	public function setBack(){ return; }

	public function beforeSave(){ return; }

	public function afterSave(){ return; }
}
