<?php

class Sistema_UsuarioTelefoneController extends Agro_Controller_Action {
	protected $_paginator = false;
	
	public function getModel() {
		return new Sistema_Model_Telefones();
	}
	
	public function getForm() {
		$this->getHelper('layout')->disableLayout();

        $origemCadastroVistoriador = $this->getRequest()->has('origemCadastroVistoriador') ? ['origemCadastroVistoriador' => true] : [];
		$Form = new Sistema_Form_Telefone(false, $origemCadastroVistoriador);
		$Form->populate($this->getRequest()->getParams());
		return $Form;
	}
	
	public function getFilter() {
		$session = new Zend_Session_Namespace('usuario');
		$where = array();
		
		$where[] = array(
			'field' => 'id_usuario',
			'operator' => '=',
			'value' => $this->getRequest()->getParam('id_usuario')
		);
		
		return $where;
	}
	
	public function indexAction() {
		$Usuario = new Sistema_Model_Usuarios();
		if($this->getRequest()->getParam('id')) {
			$Row = $Usuario->find($this->getRequest()->getParam('id'))->current();
		} else {
			$Row = $Usuario->createRow();
			if($this->getRequest()->getParam('corretor')) {
				$Row->tp_usuario = 'C';
			}
		}
		
		switch ($Row->tp_usuario) {
			case 'C':
				$Corretor = new Sistema_Model_Corretores();
				$Row = $Corretor->fetchRow("id_usuario = {$this->getRequest()->getParam('id')}");
				$this->view->title = "Gerência de Corretores » {$Row->ds_nome_corretor} » Telefones";
				$this->view->back = '/sistema/corretor';
				break;
				
			case 'F':
			case 'V':
				$Funcionario = new Sistema_Model_Funcionarios();
				$Row = $Funcionario->fetchRow("id_usuario = {$this->getRequest()->getParam('id')}");
				$this->view->title = "Gerência de Funcionários » {$Row->ds_nome_funcionario} » Telefones";
				$this->view->back = '/sistema/funcionario';
				break;
				
			case 'P':
				$Preposto = new Sistema_Model_Prepostos();
				$Row = $Preposto->fetchRow("id_usuario = {$this->getRequest()->getParam('id')}");
				$this->view->title = "Gerência de Prepostos » {$Row->ds_nome_preposto} » Telefones";
				$this->view->back = '/sistema/preposto';
				break;
			
			default:
				$Preposto = new Sistema_Model_Prepostos();
				$this->view->title = "Gerência de Telefones » {$Row->ds_nome_usuario} » Telefones";
				$this->view->back = '/sistema/corretor';
				break;
		}
		
		$this->view->form = $this->getForm();
		
		if ($this->getRequest()->isPost()) {
			$Model = $this->getModel();
			
			if ($Model->save($this->getRequest()->getPost())) {
				$this->view->showMessage(MSG_SUCCESS, 'success');
			} else {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		}
	}

    public function listAction()
    {
        parent::listAction();

        $this->view->ocultarAcoes = false;

        if ($this->getRequest()->has('acoesSomenteProprioUsuario')) {
            if ((int) Zend_Auth::getInstance()->getIdentity()->id !== (int) $this->getRequest()->getParam('id_usuario')) {
                $this->view->ocultarAcoes = true;
            }
        }

        $this->view->origemCadastroVistoriador = $this->getRequest()->has('origemCadastroVistoriador');
    }
	
	//usado pela tela de corretores
    public function saveAction() {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $adapter = Agro_Db_Table_Abstract::getDefaultAdapter();
        $Model = $this->getModel();
        $post = $this->getRequest()->getPost();

        try {
            $adapter->beginTransaction();

            if (!$Model->save($post)) {
                throw new Exception('Erro ao salvar o telefone.');
            }

            if (isset($post['replicarParticularWhatsApp']) && (bool)$post['replicarParticularWhatsApp'] === true) {
                $post['id'] = null;
                $post['id_tipo_telefone'] = Sistema_Model_Telefones::ID_WHATSAPP;

                if (!$Model->save($post)) {
                    throw new Exception('Erro ao salvar o telefone do tipo WhatsApp.');
                }
            }

            $adapter->commit();

            $this->getResponse()->setBody('Telefone salvo com sucesso!');
        } catch(Exception $e) {
            $adapter->rollBack();
            $this->view->showMessage(MSG_ERROR, 'error');
        }
    }
}