<?

class Comercializacao_RelacionartaxausuarioController extends Agro_Controller_TaxaAgrupamento {
	
	public function init() {
		$session = new Zend_Session_Namespace('agrupamento');
		
		if ($session->id) {
			$TaxaAgrupamento = new Comercializacao_Model_TaxasAgrupamentos();
			$Agrupamento = $TaxaAgrupamento->find($session->id)->toArray();
			
			$this->view->title = "Gerência de Taxas » {$Agrupamento[0]['ds_nome_agrupamento_taxas']} » Relacionar Usuários";
		}
		
		$this->view->back = '/comercializacao/taxausuario';
	}
	
	public function indexAction() {
		$Model = new Comercializacao_Model_TaxasAgrupamentoUsuarios();
		$Corretores = new Sistema_Model_Corretores();
		
		$session = new Zend_Session_Namespace('agrupamento');
		if ($this->getRequest()->isPost()) {
			$this->save($this->getRequest()->getParams());
		}
		
		$this->view->usuarios = $Corretores->getCheckUsuarios();
		
		
		$Rs = $Model->fetchAll("id_taxa_agrupamento = {$session->id}")->toArray();
		$this->view->relacionados = array();
		if (is_array($Rs)) {
			foreach ($Rs as $relacionado) {
				$this->view->relacionados[] = $relacionado['id_usuario'];
			}
		}
	}
	
	public function save(array $post) {
		$session = new Zend_Session_Namespace('agrupamento');
		
		try {
			$Model = new Comercializacao_Model_TaxasAgrupamentoUsuarios();
			$Model->deleteUsuarios($session->id);
			
			if (array_key_exists('usuarios', $post)) {
				if (is_array($post['usuarios'])) {
					foreach ($post['usuarios'] as $usuario) {
						$data = array();
						$data['id_taxa_agrupamento'] = $session->id;
						$data['id_usuario'] = $usuario;
						
						$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/relacionartaxausuario');
	}
}
