<?

class Produto_CondicaopagamentousuariosController extends Agro_Controller_Action{
	
	public function init() {
		$this->getHelper('layout')->disableLayout();
	}
	
	public function getModel() {
		return new Produto_Model_CondicoesPagamentoUsuarios();
	}
	
	public function getForm() {
		return new Produto_Form_CondicaoPagamentoUsuario();
	}
	
	public function formAction() {
		$Corretores = new Sistema_Model_Corretores();
		$Model = $this->getModel();
		
		$this->view->id = $this->getRequest()->getParam('id');
		$this->view->usuarios = $Corretores->getCheckUsuarios();
		
		$this->view->corretores = $Corretores->fetchAll(null, 'ds_nome_fantasia');
		
		$Rs = $Model->fetchAll("id_condicao_pagamento = {$this->view->id}")->toArray();
		
		$this->view->relacionados = array();
		if (is_array($Rs)) {
			foreach ($Rs as $relacionado) {
				$this->view->relacionados[] = $relacionado['id_usuario'];
			}
		}
		
	}
	
	public function saveAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$post = $this->getRequest()->getParams();

		if ($post['id']) {
			try {
				$Db = Agro_Db_Table_Abstract::getDefaultAdapter();
				$Db->beginTransaction();
				
				$Model = $this->getModel();
				$Model->delete($post['id'], 'id_condicao_pagamento');
				
				foreach ($post['id_usuario'] as $key => $value) {
					$data = array(
						'id_condicao_pagamento' => $post['id'],
						'id_usuario' => $value
					);
				
					$Model->insert($data);
					
				}
				$Db->commit();
				
				$this->getResponse()->setBody("Usuários Relacionados com sucesso!");
			} catch (Exception $e) {
				$Db->rollBack();
				print_r($e);
			}
		}
	}
}
