<?php

class Comercializacao_RelacionartaxaestadoController extends Agro_Controller_Action {
	
	public function init() {
		if ($this->getRequest()->getParam('id')) {
			$TaxaAgrupamento = new Comercializacao_Model_TaxasAgrupamentos();
			$Agrupamento = $TaxaAgrupamento->find($this->getRequest()->getParam('id'))->current();
			$this->view->title = "Gerência de Taxas » Relacionar Estados";
			$this->view->taxa = $Agrupamento->ds_nome_agrupamento_taxas;
		}
		
		switch ($Agrupamento->tp_taxa_agrupamento) {
			case 'E':
				$this->view->back = '/comercializacao/taxaestado';
				break;
			case 'M':
				$this->view->back = '/comercializacao/taxamunicipio';
				break;
			case 'U':
				$this->view->back = '/comercializacao/taxausuario';
				break;
			case 'P':
				$this->view->back = '/comercializacao/taxaproponente';
				break;
		}
	}
	
	public function indexAction() {
		//$session = new Zend_Session_Namespace('agrupamento');
		
		if ($this->getRequest()->isPost()) {
			$this->save($this->getRequest()->getParams());
		}
		
		$Estados = new Sistema_Model_Estados();
		$Model = new Comercializacao_Model_TaxasAgrupamentoEstados();
		$this->view->estados = $Estados->fetchAll(null, 'ds_sigla')->toArray();
		
		$Rs = $Model->fetchAll("id_taxa_agrupamento = {$this->getRequest()->getParam('id')}")->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('agrupamento');

		try {
			$Model = new Comercializacao_Model_TaxasAgrupamentoEstados();
			$Model->deleteEstados($this->getRequest()->getParam('id'));
			
			if (is_array($post['estados'])) {
				foreach ($post['estados'] as $estado) {
					$data = array();
					$data['id_taxa_agrupamento'] = $this->getRequest()->getParam('id');
					$data['id_estado'] = $estado;
					
					$Model->insert($data);
					$this->view->showMessage(MSG_SUCCESS, 'success');
				}
			}
		} catch (Exception $e) {
			$this->view->showMessage(MSG_ERROR, 'error');
		}
	}
	
	public function settaxaAction() {
		$session = new Zend_Session_Namespace('agrupamento');
		$session->id = $this->getRequest()->getParam('id');
		$this->_redirect('/comercializacao/relacionartaxaestado');
	}
	
}