<?php

class Produto_ValidacoesvariedadeidadeController extends Agro_Controller_Action {
	
	public function init() {
		$this->view->title = 'Nome da Validação: VALIDACAO_VARIEDADE_IDADE ';
		$this->id_validacao = $this->getRequest()->getParam('id_validacao');
		$this->view->back = '/produto/validacoesvariedadeidade/index/id_validacao/'.$this->id_validacao;
	}

	public function getModel() {
		return new Produto_Model_ValidacoesVariedadeIdade();
	}
	
	public function getModelValores() {
		return new Produto_Model_ValidacoesValores();
	}	
	
	public function getFormVariedades() {
		return new Produto_Form_ValidacoesVariedades();
	}

	public function getFormVariedadesIdade() {
		return new Produto_Form_ValidacoesVariedadeIdade();
	}	
	
	/*
	Monta a tela de configuração de validações.
	Action responsavel por montar a tela, a listagem e salvar quando o formulario for postado.
	*/
	
	public function indexAction() {

		$this->view->form = new Produto_Form_ValidacoesValores();
		$this->view->form->populate(array("id_validacao" => $this->getRequest()->getParam('id_validacao')));
		$this->view->id_validacao = $this->getRequest()->getParam('id_validacao');

	}
	
	public function savegrupovariedadeAction(){
		$this->isAjax();
		$this->view->form = new Produto_Form_ValidacoesValores();
		try {
			$Model = new Produto_Model_Validacoesgrupovariedade();
			$Model->_order = array('ds_nome_grupo_variedade');
			
			$Model->save(array(
				'id_validacao' => $this->getRequest()->getParam('id_validacao'), 
				'ds_nome_grupo_variedade' => $this->getRequest()->getParam('ds_nome_grupo_variedade'),
				'id' => $this->getRequest()->getParam('id')
			));
			$this->_forward('listgrupos');
			
		} catch (Exception $e) {
			$this->getResponse()->setBody("Erro ao cadastrar grupo de Variedade!");
			return false;
		}
	}
	
	public function listgruposAction() {
		$Model = new Produto_Model_ValidacoesVariedades();
		$Model->_order = array('ds_nome_grupo_variedade');
		$this->isAjax(true);

		$id = $this->getRequest()->getParam('id_validacao');
		$this->view->paginator = $Model->fetchAllPaginator("id_validacao = $id", $this->getPageCache());
	}	

	public function loadgruposAction() {
		$Model = new Produto_Model_ValidacoesVariedades();
		$this->isAjax();
		
		$Row = $Model->find($this->getRequest()->getParam('id'))->current();
		$this->getResponse()->setBody(Zend_Json::encode($Row->toArray()));
	}	
	
	public function loadAction() {
		$Model = new Produto_Model_ValidacoesValores();
		$this->isAjax();
		
		$Row = $Model->find($this->getRequest()->getParam('id'))->current();
		$this->getResponse()->setBody(Zend_Json::encode($Row->toArray()));
	}
	
	public function savevalidacaoAction(){
		$this->isAjax();

		try {
			$Model = new Produto_Model_ValidacoesValores();
			$Model->_order = array('ds_nome_grupo_variedade', 'vl_minimo', 'vl_maximo');
			
			if ($this->getRequest()->getParam('vl_minimo') > $this->getRequest()->getParam('vl_maximo')) {
				$this->getResponse()->setBody('Não é possível cadastrar um valor mínimo maior que o máximo.');
				return false;
			}
			
			if ($Model->existeValidacao($this->getRequest()->getParams())) {
				$this->getResponse()->setBody('Já existe uma validação com estes dados.');
				return false;
			}
			
			$Model->save(array(
				'id_validacao' => $this->getRequest()->getParam('id_validacao'), 
				'id_grupo_variedade' => $this->getRequest()->getParam('id_grupo_variedade'),
				'vl_minimo' => $this->getRequest()->getParam('vl_minimo'),
				'vl_maximo' => $this->getRequest()->getParam('vl_maximo'),
				'nu_idade' => $this->getRequest()->getParam('nu_idade'),
				'id' => $this->getRequest()->getParam('id')
			));
			
			$this->_forward('listvalidacoes');
			
		} catch (Exception $e) {
			$this->getResponse()->setBody("Erro ao cadastrar validação!");
			return false;
		}
	}	
	
	public function listvalidacoesAction() {
		$Model = new Produto_Model_ValidacoesValores();
		$Model->_order = array('ds_nome_grupo_variedade', 'vl_minimo', 'vl_maximo');
		$this->isAjax(true);
		
		$id = $this->getRequest()->getParam('id_validacao');
		$this->view->valores = $Model->fetchAllPaginator("v.id_validacao = $id", $this->getPageCache());
	}
	
	
	public function relacionarvariedadesAction() {
		$this->view->id_validacao = $this->getRequest()->getParam('id_validacao');
		//tenta salvar antes de montar a tela para que as alterações ja reflitam na mesmo
		if ($this->getRequest()->isPost()) {
			$Model = new Produto_Model_Validacoesgrupovariedadesvariedade();
			
			try {
				$insert = array();
				$insert['id_grupo_variedade'] = $this->getRequest()->getParam('id_grupo_variedade');
				$id_variedades = $this->getRequest()->getParam('id_variedades');
				$Model->removeAll($insert['id_grupo_variedade']);
				foreach($id_variedades as $key => $id_variedade) {
					$Model->removeVariedade($id_variedade);
					$insert['id_variedade'] = $id_variedade;
					$Model->insert($insert);
				}
				
				$this->view->showMessage(MSG_SUCCESS, 'success');
			} catch (Exception $e) {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		}
		$this->view->form = new Produto_Form_ValidacoesRelacionarVariedades($this->getRequest()->getParam('id_grupo_variedade'));
		$this->view->form->populate(array("id_validacao" => $this->getRequest()->getParam('id_validacao'),
										  "id_grupo_variedade" => $this->getRequest()->getParam('id_grupo_variedade')));
		
		//list dos valores
		$Model = new Produto_Model_ValidacoesValores();
		$Rs = $Model->fetchAllPaginator('v.id_validacao = ' . $this->id_validacao, $this->getPageCache());
		$this->view->valores = $Rs;		
		
	}
	
	public function deleteAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$Model = $this->getModel();

		//deleta as variedades antes de deletar o grupo, senão dá erro de FK
		$Model->deleteRelacoes($this->getRequest()->getParam('id'),$this->getRequest()->getParam('id_validacao'));
		
		if ($Model->delete($this->getRequest()->getParam('id'))) {
			$this->view->message(MSG_SUCCESS, 'success', 'afterDelete()');
			$this->_redirect('/produto/validacoesvariedadeidade/index/id_validacao/' . $this->getRequest()->getParam('id_validacao'));			
		} else {
			$this->view->message(MSG_ERROR, 'error');
		}
	}
	
	public function buscavariedadesAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$id_culturas = implode(',', $this->getRequest()->getParam('id_culturas'));
		$id = $this->getRequest()->getParam('id_grupo_variedade');
		$id_validacao = $this->getRequest()->getParam('id_validacao');
		$Model = $this->getModel();
		$Variedades = $Model->getCheckBoxVariedadesCulturas($id_culturas, $id, $id_validacao);
		$ret = array();
		$html = '<table style="width:350px"><tr>';
		$i = 1;
		foreach($Variedades as $key => $val) {
			if($i % 2 != 0) {
				$html .= "
				</tr><tr>
				";
			}
			$i++;
			$disabled = true;
			$extra = '';
			if($val['id_grupo_variedade'] != '') {
				//$disabled = 'disabled';
				//$extra = '(' . $val[ds_nome_grupo_variedade] . ')';
			}
			$html .= "<td><input name='id_variedades[]' value='{$val[id]}' id='id_variedades_{$val[id]}' class='class_id_variedades' $disabled type='checkbox'></td>
			<td valign='top'><label for='id_variedades_{$val[id]}'><b>{$val[ds_nome_variedade]}</b> $extra</label></td>";
		}
		//$html .= "</tr></table><br><input type='button' id='liberarchecks' name='liberarchecks' value='Liberar registros Bloqueados'>";
		$html.= "</tr></table><br><button id='liberarchecks' name='liberarchecks' value='Liberar registros Bloqueados'>Liberar registros Bloqueados</button>";
		return $this->getResponse()->setBody($html);
	}
	
	public function valoresAction() {
		$Model = new Produto_Model_ValidacoesValores();
		if ($this->getRequest()->isPost()) {
			try {
				$Model->save($this->getRequest()->getParams());

				$this->view->showMessage(MSG_SUCCESS, 'success');
				$this->view->form->reset();
				$this->view->form->populate(array("id_validacao" => $this->getRequest()->getParam('id_validacao')));
			} catch (Exception $e) {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		}
		
		$this->view->form = new Produto_Form_ValidacoesValores($this->getRequest()->getParam('id_grupo_portaenxerto'), $this->getRequest()->getParam('id_validacao'));
		
		if($this->getRequest()->getParam('id')) {
			$this->view->form->populate($Model->find($this->getRequest()->getParam('id'))->current()->toArray());
		} else {
			$this->view->form->populate($this->getRequest()->getParam('id_validacao'));
		}
		
		try {
			if ($this->getRequest()->getParam("order")) {
				
				$order = explode('#', $this->getRequest()->getParam("order"));
				$this->view->order = $order[0];
				if(count($order) > 1){
					$this->view->orderType = $order[1];
				}
				
				$Model->_order = trim($this->view->order .' '. $this->view->orderType);
			}
			
			$Rs = $Model->fetchAllPaginator('gd.id_validacao = ' . $this->id_validacao, $this->getPageCache());
			$this->view->paginator = $Rs;
			
			if ($this->_columnList) {
				$this->getHelper('ViewRenderer')->setNoRender();
				$this->getResponse()->setBody(Agro_List_Table::getList($Rs, $this->_columnList, $this->getRequest()->getModuleName(), $this->getRequest()->getControllerName()));
			}
		} catch (Exception $e) {
			$this->view->error = $e;
		}
	}
	
	public function pesquisavaloresAction() {

		$this->getHelper('layout')->disableLayout();
		
		$this->view->form =  new Produto_Form_ValidacoesValores();

		$this->view->form->populate(array("id_validacao" => $this->getRequest()->getParam('id_validacao')));

		$Model = new Produto_Model_ValidacoesValores();
		try {
			if ($this->getRequest()->getParam("order")) {
				
				$order = explode('#', $this->getRequest()->getParam("order"));
				$this->view->order = $order[0];
				if(count($order) > 1){
					$this->view->orderType = $order[1];
				}
				
				$Model->_order = trim($this->view->order .' '. $this->view->orderType);
			}
			
			$Rs = $Model->fetchAllPaginator('v.id_validacao = ' . $this->id_validacao, $this->getPageCache());
			$this->view->valores = $Rs;
			
			if ($this->_columnList) {
				$this->getHelper('ViewRenderer')->setNoRender();
				$this->getResponse()->setBody(Agro_List_Table::getList($Rs, $this->_columnList, $this->getRequest()->getModuleName(), $this->getRequest()->getControllerName()));
			}
		} catch (Exception $e) {
			die($e);
			$this->view->error = $e;
		}
	}

		
	public function adicionavaloresAction() {
		//$this->getHelper('layout')->disableLayout();
		
		$this->view->form =  new Produto_Form_ValidacoesValores();
		$this->view->id_validacao = $this->getRequest()->getParam('id_validacao');
		
		$Model = new Produto_Model_ValidacoesValores();
		$id = $this->getRequest()->getParam('id');
		if ($id) {
			$params = $Model->find($id)->current()->toArray();
			
		} else {
			$params = array("id_validacao" => $this->getRequest()->getParam('id_validacao'));
		}

		$this->view->form->populate($params);
		if ($this->getRequest()->isPost()) {
			try {
				//if ($this->view->form->isValid($this->getRequest()->getPost())) {
				if($Model->save($this->getRequest()->getParams())){
					$this->_redirect('/produto/validacoesvariedadeidade/index/id_validacao/' . $this->getRequest()->getParam('id_validacao'));
					$this->view->message(MSG_SUCCESS, 'success', '');
				} else {
					$Errors = $this->view->form->getMessages();
					$this->view->showMessage($this->getHtmlFormError($Errors), 'error');
				}
				
			} catch (Exception $e) {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		}
	}
	
	public function ativavaloresAction() {
		$this->isAjax();
		$Model = new Produto_Model_ValidacoesValores();
		
		try{
			if ($this->getRequest()->getParam('id')) {
				if ($Model->setAtivo($this->getRequest()->getParam('id'))) {
					$this->getResponse()->setBody(MSG_SUCCESS);
				}
			}
		}catch (Exception $e){
			$this->getResponse()->setBody(MSG_ERROR);
		}
	}
	
	public function ativavariedadesAction() {
		$this->isAjax();
		$Model = new Produto_Model_ValidacoesVariedades();
		
		try{
			if ($this->getRequest()->getParam('id')) {
				if ($Model->setAtivo($this->getRequest()->getParam('id'))) {
					$this->getResponse()->setBody(MSG_SUCCESS);
				}
			}
		}catch (Exception $e){
			$this->getResponse()->setBody(MSG_ERROR);
		}
	}

	
	public function deletavaloresAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = new Produto_Model_ValidacoesValores();
		
		try {
			if ($this->getRequest()->getParam('id')) {
				if ($Model->delete($this->getRequest()->getParam('id'))) {
					$this->getResponse()->setBody(MSG_SUCCESS);
				}
			}
		} catch (Exception $e) {
			$this->getResponse()->setBody(MSG_ERROR);
		}
	}
	
	public function deletegrupoAction() {
		$this->isAjax();
		$Model = new Produto_Model_ValidacoesVariedades();
		$ModelValores = new Produto_Model_ValidacoesValores();
		$ModelGrupoVariedades = new Produto_Model_Validacoesgrupovariedadesvariedade();
		
		if ($this->getRequest()->getParam('id')) {			
			$ModelValores->delete($this->getRequest()->getParam('id'),'id_grupo_variedade');
			$ModelGrupoVariedades->delete($this->getRequest()->getParam('id'),'id_grupo_variedade');
			
			if ($Model->delete($this->getRequest()->getParam('id'))) {
				$this->getResponse()->setBody(MSG_SUCCESS);
			} else {
				$this->getResponse()->setBody(MSG_ERROR);
			}
		}
	}

	public function getgruposAction(){
		$this->isAjax();
		$Model = $this->getModel();
		
		$this->getResponse()->setBody(Zend_Json::encode($Model->getGrupos($this->getRequest()->getParam('id_validacao'))));
	}
	
	
}
