<?php

class Sistema_CorretorEnderecoController extends Agro_Controller_Action {
	protected $_paginator = false;
	
	public function getModel() {
		return new Sistema_Model_CorretoresEnderecos();
	}
	
	public function getForm() {
		return new Sistema_Form_CorretorEndereco();
	}
	
	public function indexAction() {
		$Corretor = new Sistema_Model_Corretores();
		$this->view->form = $this->getForm();
		
		$Row = $Corretor->find($this->getRequest()->getParam('id'))->current();
		$this->view->title = "Gerência de Corretores » {$Row->ds_nome_corretor} » Endereços";
		$this->view->back = '/sistema/corretor';
		$this->view->corretor = $Row->id;
		
		if ($this->getRequest()->isPost() && count($this->getRequest()->getPost())) {
			$Model = $this->getModel();
			if ($Model->save($this->getRequest()->getPost())) {
				$this->view->showMessage(MSG_SUCCESS, 'success');
			} else {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		}
	}
	
	public function getFilter() {
		$session = new Zend_Session_Namespace('corretor');
		$where = array();
		
		$where[] = array(
			'field' => 'ce.id_corretor',
			'operator' => '=',
			'value' => $this->getRequest()->getParam('id')
		);
		
		return $where;
	}

	public function salvaenderecoAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$Model = $this->getModel();
		try {
			if ($Model->save($this->getRequest()->getParams())) {
				
				$this->getResponse()->setBody('Endereço salvo com sucesso!');
			} else {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		} catch(Exception $e) {
			
		}
	}

	public function dadosenderecoAction()
    {
        $this->isAjax();

        $retorno = ['endereco' => null];
        $rows = $this->getModel()->getEnderecosFromCorretor($this->getRequest()->getParam('id_corretor'))->toArray();

        if (!empty($rows)) {
            $retorno['endereco'] = $rows[0];
        }

        $this->getResponse()->setBody(Zend_Json::encode($retorno));
    }
}
