<?php

class Produto_RelacionarlimitelmgaestadoController extends Agro_Controller_Action {
	
	public function init() {
		if ($this->getRequest()->getParam('grupo')) {
			$NomeGrupo = new Produto_Model_ValidacaoLimitesLmga();
			$Grupo = $NomeGrupo->find($this->getRequest()->getParam('grupo'))->current();

			$this->view->title = "Gerência de Limites LMGA » Relacionar Estados";
			$this->view->grupo = $Grupo['ds_nome_grupo'];
		}
		
		$this->view->back = '/produto/produto/form/id/'.$this->getRequest()->getParam('id').'#ui-tabs-4';		
		
	}
	
	public function indexAction() {
		$session = new Zend_Session_Namespace('limitelmga');
		
		if ($this->getRequest()->isPost()) {
			$this->save($this->getRequest()->getParams());
		}
		
		$Estados = new Sistema_Model_Estados();
		$Model = new Produto_Model_ValidacaoLimitesLmgaEstados();

		$this->view->estados = $Estados->fetchAll(null, 'ds_sigla')->toArray();
		
		$Rs = $Model->fetchAll("id_validacao_limites_lmga = {$this->getRequest()->getParam('grupo')}")->toArray();
		$this->view->relacionados = array();
		if (is_array($Rs)) {
			foreach ($Rs as $relacionado) {
				$this->view->relacionados[] = $relacionado['id_estado'];
			}
		}
	}
	
	public function save(array $post) {
		$session = new Zend_Session_Namespace('limitelmga');

		try {
			$Model = new Produto_Model_ValidacaoLimitesLmgaEstados();
			$Model->deleteEstados($this->getRequest()->getParam('grupo'));
			
			if (is_array($post['estados'])) {
				foreach ($post['estados'] as $estado) {
					$data = array();
					$data['id_validacao_limites_lmga'] = $this->getRequest()->getParam('grupo');
					$data['id_estado'] = $estado;
					
					$Model->insert($data);
					$this->view->showMessage(MSG_SUCCESS, 'success');
				}
			}
		} catch (Exception $e) {

			$this->view->showMessage(MSG_ERROR, 'error');
		}
	}
	
	
}