<?php

Goweb::loadClass('Index_Controller', ADMIN_PATH);

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.0
 * @category   Backoffice
 * @package    Painel
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
*/
class Painel_GenericController extends Index_Controller {

    /**
     * Titulo do Modulo
     * @var string
    */
    protected $_title;
    
    /**
     * Nomes das linguas
     * @var string
    */
    protected $_langsNames;
    /**
     * Controller do Modulo
     * @var string
    */
    protected $_controller = 'painel';
    
    /**
     * Seccoes do Modulo
     * @var array
    */
    protected $_sections;
    
    /**
     * Objecto Goweb_Config_Ini
     * @var Goweb_Config_Ini
    */
    protected $_configModel = null;
    
    /**
     * Objecto Sistema_Model_Utilizador
     * @var Sistema_Model_Utilizador
    */
    protected $_utilizadorModel = null;
    
    /**
     * Objecto Sistema_Model_Perfil
     * @var Sistema_Model_Perfil
    */
    protected $_perfilModel = null;
    
    /**
     * Objecto Sistema_Model_Permissao
     * @var Sistema_Model_Permissao
    */
    protected $_permissaoModel = null;
    
    /**
     * Objecto Sistema_Model_Modulo
     * @var Sistema_Model_Modulo
    */
    protected $_moduloModel = null;
    
    /**
     * Objecto Sistema_Model_CmsPermissao
     * @var Sistema_Model_CmsPermissao
    */
    protected $_cmsPermissaoModel = null;
    
    /**
     * Objecto Cms_Model_Pagina
     * @var Cms_Model_Pagina
    */
    protected $_paginaModel = null;

    /**
     * Mensagem de erro
     *
     * @var strint
    */
    protected $_error = null;
    
    /**
     * Mensagem de sucesso
     *
     * @var strint
    */
    protected $_message = null;

    /**
     * Construtor da classe
    */
    public function init() {
        /**
         * costumização para este módulo especifico
         */
        if ($this->_request->getActionName() == 'edit' && !$this->_getParam('section')) $this->_forward('editPainel');
        $this->_title = translateAdmin('Painel de Controlo');
        $this->_sections = array(array('title'   => translateAdmin('Configura&ccedil;&atilde;o'),
                                       'section' => 'config',
                                       'link'    => '/painel/editPainel/config/'),
                                 array('title'   => translateAdmin('Metatags'),
                                       'section' => 'meta',
                                       'link'    => '/painel/editPainel/sub_section/meta/'),
                                 array('title'   => translateAdmin('Google'),
                                       'section' => 'google',
                                       'link'    => '/painel/editPainel/sub_section/google/'),
                                 array('title'   => translateAdmin('Utilizadores'),
                                       'section' => 'utilizadores',
                                       'link'    => '/painel/list_utilizadores/sub_section/utilizadores'),
                                 array('title'   => translateAdmin('Perfis de Utilizadores'),
                                       'section' => 'utilizadores',
                                       'link'    => '/painel/list_perfis/sub_section/utilizadores')
                                       );
        $this->_langsNames = goweb::registry('langsNames');
        parent::init();
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_paginatorParams = array('rows_per_page' => 20, 'links_per_page' => 10);
        $this->_initDefaultLinks();
        $this->_configModel = Goweb::getModelInstance('Painel_Model_Config', 'db');
        $this->view->title    = $this->_title;
        $this->view->sections = $this->_sections;
        $this->_links['excel'] = $this->_links['xml'] = '';
    }
    
   
    /**
     * LIstagem dos Perfis dos Utilizadores
     */
    public function listAclAction() {
        $this->_links['list'] = '/painel/list_acl/';
        $this->_links['add'] = null;
        $this->_links['edit'] = '/painel/edit_acl/id/';
        $this->_links['delete'] = '/painel/delete_acl/id/';
        $this->_links['deletelist'] = null;
        
        $this->_perfilModel = Goweb::getModelInstance('Utilizadores_Model_Perfil', 'db');    
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Access Control List'));
        $section->setTitleSingular(translateAdmin('Access Control List'));
        $section->setModel($this->_perfilModel);               
        $section->setListCols(array('nome', 'activo', 'criado'));
        $section->setSearchCols(array('nome'));
        $section->setOrdering('nome');
        
        $this->view->model  = $this->_configModel;
        $this->view->output = $this->_listGeneric($section, $this->view, false);        
        $this->_helper->viewRenderer->setRender('base');
    }
    

    public function editAclAction() {
        $this->_perfilModel = Goweb::getModelInstance('Utilizadores_Model_Perfil', 'db');
                
        $id = $this->_getParam('id');
        
        if (!$this->_validateId($id) || !$this->_perfilModel->find($id)) {            
            return $this->listPerfisAction();
        }

        $this->_links['edit'] = '/painel/edit_acl/id/' . $id . '/';
        $this->_links['save'] = '/painel/save_acl/id/' . $id . '/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Access Control List'));
        $section->setTitleSingular(translateAdmin('Access Control List'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree($id));

        $this->view->modulos = $this->_getPaginasTreeModulos();
        
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_editGeneric($section, $this->view, null, 0, true, true, 'form_acl.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    

    /**
     * Salva um perfil
    */
    public function saveAclAction() {
        $this->_utilizadorModel = Goweb::getModelInstance('Utilizadores_Model_Perfil', 'db');
        $perfil_id = $this->_getParam($this->_utilizadorModel->getPrimary());

        $this->_saveAcl();
        if ($this->_request->submit) {
            return $this->listAclAction();
        }
        if ($this->_request->submit_and_new) {
            return $this->addAclAction(true);
        }
        if ($this->_request->submit_and_continue) {

            $model = $this->_utilizadorModel;

            if (!$this->_getParam($model->getPrimary())){
                $this->_request->setParam($model->getPrimary(), $model->{$model->getPrimary()});
                $this->_links['save'] .= $model->getPrimary() . '/' . $model->{$model->getPrimary()} . '/';
            }
            return $this->editAclAction();
        }

    }

    /**
     * Editar Config
    */
    public function editPainelAction() {
        $sectionPainel = $this->_getParam('sub_section');
        if ($sectionPainel != 'config' && $sectionPainel != 'meta' && $sectionPainel != 'google') {
            $sectionPainel = 'config';
        }

        if (!$this->_configModel->find('1')) {
            throw new Goweb_Exception('As configura&ccedil;&otilde;es do "Painel" n&atilde;o existem no sistema.');
        }

        $this->_links['save'] = '/painel/savePainel/sub_section/' . $sectionPainel . '/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Configura&ccedil;&otilde;es'));
        $section->setTitleSingular(translateAdmin('Configura&ccedil;&atilde;o'));
        $section->setModel($this->_configModel);               

        Goweb::loadClass('Form_Generic', ADMIN_PATH . DIRECTORY_SEPARATOR . 'Index');
        $form = new Form_Generic($section, Goweb::link($this->_links['save']));
        $form->setup($section, $section->getLabels(), $this->_configModel);
        $form->render();
        
        if ($sectionPainel == 'config') {
            $this->view->show_elements = array('linguas_activas');
        } elseif ($sectionPainel == 'meta') {
            $this->view->show_elements = array('title', 'meta_copyright', 'meta_keywords', 'meta_description', 'meta_extra');
        } elseif ($sectionPainel == 'google') {
            $this->view->show_elements = array('google_sitemap', 'google_analytics');
        }
        
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->model            = $this->_configModel;
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->form             = $form;
        $this->view->output           = $this->view->render('form.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Metodo de actualizacao da base de dados
    */
    public function savePainelAction() {
        $sectionPainel = $this->_getParam('sub_section');
        if ($sectionPainel != 'config' && $sectionPainel != 'meta' && $sectionPainel != 'google') {
            $sectionPainel = 'config';
        }
        
        if (!$this->_configModel->find('1')) {
            throw new Goweb_Exception('As configura&ccedil;&otilde;es n&atilde;o existem no sistema.');
        }

        $this->_links['save'] = '/painel/savePainel/sub_section/' . $sectionPainel . '/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Configura&ccedil;&otilde;es'));
        $section->setTitleSingular(translateAdmin('Configura&ccedil;&atilde;o'));
        $section->setModel($this->_configModel);
        
        Goweb::loadClass('Form_Generic', ADMIN_PATH . DIRECTORY_SEPARATOR . 'Index');
        $form = new Form_Generic($section, Goweb::link($this->_links['save']));
        $form->setup($section, $section->getLabels(), $this->_configModel);

        $updateElements = array();
        if ($sectionPainel == 'config') {
            $updateElements = array('linguas_activas');
        } elseif ($sectionPainel == 'meta') {
            $updateElements = array('title', 'meta_copyright', 'meta_keywords', 'meta_description', 'meta_extra');
        } elseif ($sectionPainel == 'google') {
            $updateElements = array('google_sitemap', 'google_analytics');
        }
        
        if (!$form->validate()) {
            if (count($form->getErrorMessages()) > 1) {
                $this->_error = translateAdmin('Corrija por favor os erros no formul&aacute;rio');
                $this->_message = null;
            } else {
                $this->_error = translateAdmin('Corrija por favor o erro no formul&aacute;rio');
                $this->_message = null;
            }
        } else {
            $this->_error = null;
            $this->_message = translateAdmin('Configura&ccedil;&otilde;es gravas com sucesso');
            foreach ($updateElements as $element) {
                if (is_array($form->{$element}->value)) {
                    $this->_configModel->{$element} = serialize($form->{$element}->value);
                } else {
                    $this->_configModel->{$element} = $form->{$element}->value;
                }
            }
            $this->_configModel->save();            
        }

        $form->render();

        $this->view->show_elements = $updateElements;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->model            = $this->_configModel;
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->form             = $form;
        $this->view->output           = $this->view->render('form.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');                
    }
    /**
     * Listagem de traduções
     */
    public function translaterAction(){
    	$this->_config22 = Goweb::registry('config');
    	$this->_links['list'] = '/painel/translater/';
        $this->_links['edit'] = null;
        $this->_links['save'] = '/painel/saveTranslater/';
        $this->_links['deletelist'] = null;
        
        $page = $this->_request->page > 0 ? $this->_request->page : '1'; 
        $row_por_pag = 20;
        $this->_translaterModel = Goweb::getModelInstance('Cms_Model_Translater', 'db'); 
        $db = $this->_translaterModel->getAdapter();
          
        foreach ($_POST as $key => $value) {
        	$key_temp = explode("_", $key);
        	if(count($key_temp) == 3 && $key_temp[0] == 'texto') {
        		if ($_POST['texto_' . $key_temp[1] . '_' . $key_temp[2] . '_change'] == "true" && $this->_validateId($key_temp[1]) && $this->_translaterModel->find($key_temp[1])) {
        			$value = str_replace("'", "&#39;", $value);
        			$tabela = "cms_translater_" . $key_temp[2];
       				$sql = "UPDATE $tabela SET translater = '$value', actualizado = '" . date("Y-m-d H:i:s") . "' WHERE id = " . $key_temp[1];
       				//Goweb::dump($sql);
       				$db->query($sql);
        		}
        	}
        	
        }
        $this->view->links  =  $this->_links;
        $this->view->action  = translateAdmin('Tradu&ccedil;&otilde;es');
        $this->view->section_title = translateAdmin('Tradu&ccedil;&otilde;es');
        $this->view->section_singular = translateAdmin('Tradu&ccedil;&atilde;o');
        $this->view->model  = $this->_configModel;
        
        $link_paginator = "/admin/painel/translater/";
  
       
        $paginator = new Goweb_Paginator(Goweb::link( $link_paginator, 'page='),
                                         $this->_translaterModel->count(),
                                         $page,
                                         $row_por_pag,
                                         10);
                                                                     
        $this->view->paginator = $paginator;
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->paginator_output = $this->view->render('paginator.tpl');
        
        $langs = array();
        $traducoes_temp = array();
        $this->_langsNames = goweb::registry('langsNames');
        $available = explode(',', $this->_config22->languages->available);
       
        foreach ($available as $lang) {
        	$traducoes_temp[$lang] = array();
            $langs[$lang] = $this->_langsNames[$lang];
        }
        //Goweb::dump($langs);
       // $langs['en'] = "Inglês";
        //$langs['es'] = "Espanhol";
        //$langs['fr'] = "Francês";
        
       
       $orderBy = 'texto ASC';
       
       $i = 0;
       $lang_1 = 'pt';
       
       foreach ($langs as $lang => $value) {
       			$tabela = "cms_translater_$lang";
       			$sql = "SELECT id, texto, translater FROM $tabela ORDER BY $orderBy LIMIT  " . ($paginator->getRowsPerPage() * $paginator->getPage() - $paginator->getRowsPerPage()) . ', ' . $paginator->getRowsPerPage();
       			$traducoes_temp[$lang] = $db->fetchAll($sql);
       			if($i == 0) $lang_1 = $lang;
       			$i++;
           	}
        $traducoes = array();
        for ($i = 0; $i < count($traducoes_temp[$lang_1]); $i++)
        {
        	//Goweb::dump($traducoes_temp[$lang_1][$i]);
        	$array_linha_temp = array();
        	
        	$array_linha_temp['texto'] =  html_entity_decode($traducoes_temp[$lang_1][$i]['texto'], ENT_NOQUOTES, CHARSET);
        	
        	foreach ($langs as $lang => $value){
        		if(isset($traducoes_temp[$lang][$i]['translater']))
    			$array_linha_temp[$lang] = html_entity_decode($traducoes_temp[$lang][$i]['translater'], ENT_NOQUOTES, CHARSET);
    			else
    			$array_linha_temp[$lang] = html_entity_decode($array_linha_temp['texto'], ENT_NOQUOTES, CHARSET);
        	}
        	
        	
        	$traducoes[$traducoes_temp[$lang_1][$i]['id']] = $array_linha_temp;
        } 
        
        $this->view->langs = $langs;
        $this->view->traducoes = $traducoes;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('translater.tpl'); 
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
        
    }
    /**
     * Listagem de traduções Backoffice
     */
    public function translaterAdminAction(){
    	$this->_config22 = Goweb::registry('config');
    	$this->_links['list'] = '/painel/translaterAdmin/';
        $this->_links['edit'] = null;
        $this->_links['save'] = '/painel/saveTranslaterAdmin/';
        $this->_links['deletelist'] = null;
        
        $page = $this->_request->page > 0 ? $this->_request->page : '1'; 
        $row_por_pag = 20;
        $this->_translaterModel = Goweb::getModelInstance('Cms_Model_TranslaterAdmin', 'db'); 
        $db = $this->_translaterModel->getAdapter();
          
        foreach ($_POST as $key => $value) {
        	$key_temp = explode("_", $key);
        	if(count($key_temp) == 3 && $key_temp[0] == 'texto') {
        		if ($_POST['texto_' . $key_temp[1] . '_' . $key_temp[2] . '_change'] == "true" && $this->_validateId($key_temp[1]) && $this->_translaterModel->find($key_temp[1])) {
        			$value = str_replace("'", "&#39;", $value);
        			$tabela = "cms_translater_admin_" . $key_temp[2];
       				$sql = "UPDATE $tabela SET translater = '$value', actualizado = '" . date("Y-m-d H:i:s") . "' WHERE id = " . $key_temp[1];
       				//Goweb::dump($sql);
       				$db->query($sql);
        		}
        	}
        	
        }
        $this->view->links  =  $this->_links;
        $this->view->action  = translateAdmin('Tradu&ccedil;&otilde;es Backoffice');
        $this->view->section_title = translateAdmin('Tradu&ccedil;&otilde;es BackOffice');
        $this->view->section_singular = translateAdmin('Tradu&ccedil;&atilde;o BackOffice');
        $this->view->model  = $this->_configModel;
        
        $link_paginator = "/admin/painel/translaterAdmin/";
  
       
        $paginator = new Goweb_Paginator(Goweb::link( $link_paginator, 'page='),
                                         $this->_translaterModel->count(),
                                         $page,
                                         $row_por_pag,
                                         10);
                                                                     
        $this->view->paginator = $paginator;
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->paginator_output = $this->view->render('paginator.tpl');
        
        $langs = array();
        $traducoes_temp = array();
       $available = explode(',', $this->_config22->languages->available);
       
        foreach ($available as $lang) {
        	$traducoes_temp[$lang] = array();
            $langs[$lang] = $this->_langsNames[$lang];
        }
        //Goweb::dump($langs);
       // $langs['en'] = "Inglês";
        //$langs['es'] = "Espanhol";
        //$langs['fr'] = "Francês";
        
       
       $orderBy = 'texto ASC';
       
       $i = 0;
       $lang_1 = 'pt';
       
       foreach ($langs as $lang => $value) {
       			$tabela = "cms_translater_admin_$lang";
       			$sql = "SELECT id, texto, translater FROM $tabela ORDER BY $orderBy LIMIT  " . ($paginator->getRowsPerPage() * $paginator->getPage() - $paginator->getRowsPerPage()) . ', ' . $paginator->getRowsPerPage();
       			$traducoes_temp[$lang] = $db->fetchAll($sql);
       			if($i == 0) $lang_1 = $lang;
       			$i++;
           	}
        $traducoes = array();
        for ($i = 0; $i < count($traducoes_temp[$lang_1]); $i++)
        {
        	//Goweb::dump($traducoes_temp[$lang_1][$i]);
        	$array_linha_temp = array();
        	
        	$array_linha_temp['texto'] =  html_entity_decode($traducoes_temp[$lang_1][$i]['texto'], ENT_NOQUOTES, CHARSET);
        	
        	foreach ($langs as $lang => $value){
        		if(isset($traducoes_temp[$lang][$i]['translater']))
    			$array_linha_temp[$lang] = html_entity_decode($traducoes_temp[$lang][$i]['translater'], ENT_NOQUOTES, CHARSET);
    			else
    			$array_linha_temp[$lang] = html_entity_decode($array_linha_temp['texto'], ENT_NOQUOTES, CHARSET);
        	}
        	
        	
        	$traducoes[$traducoes_temp[$lang_1][$i]['id']] = $array_linha_temp;
        } 
        
        $this->view->langs = $langs;
        $this->view->traducoes = $traducoes;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('translater.tpl'); 
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
        
    }
    /**
     * Listagem de Utilizadores do Sistema
     */
    public function listUtilizadoresAction() {
        $this->_links['list'] = '/painel/list_utilizadores/';
        $this->_links['add'] = '/painel/add_utilizador/';
        $this->_links['edit'] = '/painel/edit_utilizador/id/';
        $this->_links['delete'] = '/painel/delete_utilizador/id/';
        $this->_links['deletelist'] = null;
        
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');    
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $section->setModel($this->_utilizadorModel);               
        $section->setListCols(array('nome', 'username', 'perfil', 'activo', 'criado'));
        $section->setSearchCols(array('username', 'nome'));
        $section->setOrdering('nome');

        $this->view->model  = $this->_configModel;
        $this->view->output = $this->_listGeneric($section, $this->view, false);        
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Adiciona um utilizador do Sistema
    */
    public function addUtilizadorAction() {    
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
        
        $this->_links['add'] = '/painel/add_utilizador/';
        $this->_links['save'] = '/painel/save_utilizador/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $this->_utilizadorModel->where('perfil_id <> ?', '1');
        $section->setModel($this->_utilizadorModel);

        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->output = $this->_addGeneric($section, $this->view);        
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Edita um utilizador do sistema
    */
    public function editUtilizadorAction() {    
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
        
        $id = $this->_getParam('id');

        if (!$this->_validateId($id) || !$this->_utilizadorModel->find($id)) {            
            return $this->listUtilizadoresAction();
        }        
        
        $this->_links['edit'] = '/painel/edit_utilizador/id/' . $id . '/';
        $this->_links['save'] = '/painel/save_utilizador/id/' . $id . '/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));        
        $section->setModel($this->_utilizadorModel);

        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->output = $this->_editGeneric($section, $this->view);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Salva um utilizador do sistema
    */
    public function saveUtilizadorAction() {                
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');

        $this->_links['save'] = '/painel/save_utilizador/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $section->setModel($this->_utilizadorModel);

        $output = $this->_saveGeneric($section, $this->view);
        if (is_bool($output)) {
            if ($this->_request->submit) {
                return $this->listUtilizadoresAction();
            }
            if ($this->_request->submit_and_new) {
                return $this->addUtilizadorAction(true);
            }
            
        }
        
        
        
        $this->view->output = $output;
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Remove um utilizador do sistema
    */
    public function deleteUtilizadorAction() {        
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
        if (!$this->_validateId($this->_getParam('id')) || $this->_getParam('id') == '1' || !$this->_utilizadorModel->find($this->_getParam('id'))) {
            $this->_error = translateAdmin('Este Utilizador n&atilde;o pode ser removido.');
            return $this->listUtilizadoresAction();
        }
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $section->setModel($this->_utilizadorModel);
        $this->_deleteGeneric($section, $this->view);
        $this->listUtilizadoresAction();
    }

    /**
     * LIstagem dos Perfis dos Utilizadores do Sistema
    */
    public function listPerfisAction() {
        $this->_links['list'] = '/painel/list_perfis/';
        $this->_links['add'] = '/painel/add_perfil/';
        $this->_links['edit'] = '/painel/edit_perfil/id/';
        $this->_links['delete'] = '/painel/delete_perfil/id/';
        $this->_links['deletelist'] = null;
        
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');    
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);               
        $section->setListCols(array('nome', 'activo', 'criado'));
        $section->setSearchCols(array('nome'));
        $section->setOrdering('nome');
        
        $this->view->model  = $this->_configModel;
        $this->view->output = $this->_listGeneric($section, $this->view, false);        
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Adiciona Perfis dos Utilizadores do Sistema
    */
    public function addPerfilAction() {    
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        
        $this->_links['add'] = '/painel/add_perfil/';
        $this->_links['save'] = '/painel/save_perfil/';        
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree());
        
        $this->_moduloModel->where('permissao=?', '1');
        //$this->view->modulos = $this->_moduloModel->fetchAll();
        $this->view->modulos = $this->_getPaginasTreeModulos('back');
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_addGeneric($section, $this->view, null, 0, false, true, true, 'form_perfil.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Edita Perfis dos Utilizadores do Sistema
    */
    public function editPerfilAction() {    
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        $this->_permissaoModel = Goweb::getModelInstance('Sistema_Model_Permissao', 'db');
                
        $id = $this->_getParam('id');
        
        if (!$this->_validateId($id) || !$this->_perfilModel->find($id)) {            
            return $this->listPerfisAction();
        }

        $this->_links['edit'] = '/painel/edit_perfil/id/' . $id . '/';
        $this->_links['save'] = '/painel/save_perfil/id/' . $id . '/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree($id));
        
        $this->_permissaoModel->where('perfil_id=?', $id);
        $modulosPermissao = array();
        $permissoesRowset = $this->_permissaoModel->fetchAll();
        if ($permissoesRowset) {
            foreach ($permissoesRowset as $permissao) {
                $modulosPermissao[] = $permissao->modulo_id;
            }
        }
        $this->_moduloModel->where('permissao=?', '1');
        //$this->view->modulos = $this->_moduloModel->fetchAll();
        $this->view->modulos = $this->_getPaginasTreeModulos('back');
        //goweb::dump($this->view->modulos);
        $this->view->modulos_permissao = $modulosPermissao;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_editGeneric($section, $this->view, null, 0, true, true, 'form_perfil.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }   
    
    /**
     * Insert ou Update de Perfil de Utilizadores do Sistema
    */
    public function savePerfilAction() {
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        $this->_permissaoModel = Goweb::getModelInstance('Sistema_Model_Permissao', 'db');
        
        $this->_links['save'] = '/painel/save_perfil/';      
        
        $id = $this->_getParam('id');

        if (!$this->_validateId($id) || !$this->_perfilModel->find($id)) {            
            $id = 0;
        }

        $modulosAcesso = $this->_request->modulos_acesso;
        if (!is_array($modulosAcesso)) {
            $modulosAcesso = array();            
        }
        
        $paginasAcesso = $this->_request->paginas_acesso;
        if (!is_array($paginasAcesso)) {
            $paginasAcesso = array();
        }

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree($id, $paginasAcesso));

        $modulosPermissao = array();

        if ($id > 0) {
            $this->_permissaoModel->where('perfil_id=?', $id);        
            $permissoesRowset = $this->_permissaoModel->fetchAll();
            if ($permissoesRowset) {
                foreach ($permissoesRowset as $permissao) {
                    $modulosPermissao[] = $permissao->modulo_id;
                }
            }
        }
        
        $this->_moduloModel->where('menu=?', '1');
        $this->_moduloModel->orWhere('nome=?', 'Cms');
        $this->view->modulos = $this->_moduloModel->fetchAll();
        $this->view->modulos_permissao = $modulosAcesso;

        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $output = $this->_saveGeneric($section, $this->view, null, 0, false, true, false, 'form_perfil.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        if ($this->_error == null) {
            if (!$id){
                //$id = $this->_perfilModel->getAdapter()->lastInsertId();
                $model = $this->_perfilModel;
                $id = $model->{$model->getPrimary()};

                if (!$this->_getParam($model->getPrimary())){
                    $this->_request->setParam($model->getPrimary(), $model->{$model->getPrimary()});
                    $this->_links['save'] .= $model->getPrimary() . '/' . $model->{$model->getPrimary()} . '/';
                }
            }
            // modulos com acesso
            $this->_permissaoModel->setUseCache();
            foreach ($modulosAcesso as $moduloId) {
                if (!in_array($moduloId, $modulosPermissao)) {
                    preg_match_all("/controller_(.*)_action_(.*)/i", $moduloId, $match);
                    if (!isset($match[1][0])) continue;
                    $controller = $match[1][0];
                    $this->_permissaoModel->reset();
                    if (!is_numeric($moduloId)){
                        $this->_moduloModel->findBy('nome', $controller);
                        $this->_permissaoModel->modulo_id = $this->_moduloModel->id;
                    } else {
                        $this->_permissaoModel->modulo_id = $moduloId;
                    }
                    
                    $this->_permissaoModel->perfil_id = $id;
                    $this->_permissaoModel->save();
                }
            }

            if ($id > 0) {
                foreach ($modulosPermissao as $moduloId) {
                    if (!in_array($moduloId, $modulosAcesso)) {
                        $this->_permissaoModel->deleteWhere("modulo_id=$moduloId AND perfil_id=$id");
                    }
                }
            }
            $this->_permissaoModel->setUseCache(false);
            $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
            $this->_saveAcl('back');
            // paginas com acesso
            $paginasPermissao = array();
            if ($id > 0) {
                $this->_cmsPermissaoModel->where('perfil_id=?', $id);                        
                $paginasRowset = $this->_cmsPermissaoModel->fetchAll();
                if ($paginasRowset) {
                    foreach ($paginasRowset as $permissao) {
                        $paginasPermissao[] = $permissao->pagina_id;
                    }
                }
            }
            
            foreach ($paginasAcesso as $paginaId) {
                //if (!in_array($paginaId, $paginasPermissao) && $paginaId > 0) {
                if (!in_array($paginaId, $paginasPermissao)) {
                    $this->_cmsPermissaoModel->reset();
                    $this->_cmsPermissaoModel->pagina_id = $paginaId;
                    $this->_cmsPermissaoModel->perfil_id = $id;
                    $this->_cmsPermissaoModel->save();
                }
            }
            if ($id > 0) {
                foreach ($paginasPermissao as $paginaId) {
                    if (!in_array($paginaId, $paginasAcesso)) {
                        $this->_cmsPermissaoModel->deleteWhere("pagina_id=$paginaId AND perfil_id=$id");
                    }
                }
            }
            $this->_cmsPermissaoModel->setUseCache(false);
        }
        
        if (is_bool($output)) {
            if ($this->_request->submit) {
                return $this->listPerfisAction();
            }
            if ($this->_request->submit_and_new) {
                return $this->addPerfilAction(true);
            }
            if ($this->_request->submit_and_continue) {
                return $this->editPerfilAction();
            }
        }
        
        $this->view->output = $output;
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Remover Perfis dos Utilizadores do Sistema
    */
    public function deletePerfilAction() {
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db', false);
        $this->_permissaoModel = Goweb::getModelInstance('Sistema_Model_Permissao', 'db', false);
        $this->_cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        if (!$this->_validateId($this->_getParam('id')) || $this->_getParam('id') == '1' || !$this->_perfilModel->find($this->_getParam('id'))) {
            $this->_error = translateAdmin('Este Perfil n&atilde;o pode ser removido.');
            return $this->listPerfisAction();
        }
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $this->_permissaoModel->deleteWhere("perfil_id='" . $this->_getParam('id') . "'");
        $this->_cmsPermissaoModel->deleteWhere("perfil_id='" . $this->_getParam('id') . "'");
        $this->_deleteGeneric($section, $this->view);
        $this->listPerfisAction();
    }

    /**
     * Devolve um objecto Goweb_Js_Tree - monta a arvore dos modulos
     *
     * @param integer
     * @param array
     *
     * @return Goweb_Js_Tree
    */
    protected function _getPaginasTreeModulos($type = 'front') {
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        
        
        Goweb::loadClass('Goweb_Js_Tree');
        Goweb::loadClass('Goweb_Js_Tree_Node');

        $tree = new Goweb_Js_Tree('modulos_acesso');
        $tree->useSelection = false;
        $tree->setExpand(false);
        

        $node = new Goweb_Js_Tree_Node(0, -1, translateAdmin('Raiz'));
        $tree->addNode($node);
        
        $paginas = $this->_moduloModel->fetchAll();
        $actionModel = Goweb::getModelInstance('Sistema_Model_Action', 'db', false);

        if ($paginas) {
            $treeValue = array();
            if ($this->_getParam('id') && $this->_validateId($this->_getParam('id'))){
                if (strcmp($type, 'back') == 0){
                    $aclModel = Goweb::getModelInstance('Acl_Model_Backoffice', 'db');
                } else {
                    $aclModel = Goweb::getModelInstance('Acl_Model_Frontoffice', 'db');
                }
                $aclModel->where('perfil_id = ?', $this->_getParam('id'));
                $aclResult = $aclModel->fetchAll();
                if ($aclResult){
                    foreach ($aclResult as $item){
                        $treeValue[] = 'controller_' . $item->controller . '_action_' . $item->action;
                    }
                }
            }

            foreach ($paginas as $pagina) {
                if (strcmp($type, 'back') == 0){
                    $controllerPath = ADMIN_PATH;
                } else {
                    $controllerPath = APPLICATION_PATH;
                }
                $accoes = array();
                if (file_exists($controllerPath . '/' . $pagina->nome . '/Controller.php')){
                    $accoes = $this->_getClassActions($controllerPath . '/' . $pagina->nome . '/Controller.php', $pagina->nome . '_Controller');
                }
                /*if (file_exists($controllerPath . '/' . $pagina->nome . '/GenericController.php')){
                    $accoes = array_merge($accoes, $this->_getClassActions($controllerPath . '/' . $pagina->nome . '/GenericController.php'));
                }*/
                if (file_exists(APPLICATION_PATH . '/' . $pagina->nome . '/Admin.php')){
                    $accoes = array_merge($accoes, array('add', 'list', 'edit', 'save', 'delete', 'deletelist'));
                }
                if ($accoes && count($accoes)>1){
                    $node = new Goweb_Js_Tree_Node('controller_' . $pagina->nome, 0, $pagina->titulo);
                    $node->form_element = 'checkbox';
                    $tree->addNode($node);
                    foreach ($accoes as $accao){
                        $accaoTitulo = $accao;
                        $actionModel->where('modulo_id = ?', $pagina->id);
                        $actionModel->where('nome = ?', $accao);
                        $result = $actionModel->fetchAll();
                        if ($result){
                            $accaoTitulo = $result->current()->titulo;
                        }
                        $node = new Goweb_Js_Tree_Node(	'controller_' . $pagina->nome . '_action_' . $accao,
                            							'controller_' . $pagina->nome,
                                                        $accaoTitulo);
                        $node->form_element = 'checkbox';
                        if (in_array('controller_' . $pagina->nome . '_action_' . $accao, $treeValue)) {
                            $node->form_checked = true;
                        }
                        $tree->addNode($node);

                    }
                }
                }
            }


        return $tree;
    }
    
    /**
     * Obter as ações de um controller
     *
     * @param String $file path para o controller
     * @param String $className nome da classe do controller
     * @return array com as ações do controller
     */
    protected function _getClassActions($file, $className = null){
        if (!file_exists($file)) return array();
        $arr_methods = array();
        require_once $file;
        $arr = get_class_methods($className);
        foreach ($arr as $line) {
            if (substr($line,0,1) !== '_' && substr($line,-6) === 'Action') {
                $arr_methods[] = substr($line,0,-6);
            }
        }
        return $arr_methods;
    }

    /**
     * Devolve um objecto Goweb_Js_Tree - monta a arvore
     *
     * @param integer
     * @param array
     *
     * @return Goweb_Js_Tree
    */
    protected function _getPaginasTree($perfilId = 0, $permissoes = array()) {
        $this->_cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        $this->_paginaModel = Goweb::getModelInstance('Cms_Model_Pagina', 'db', false);
        
        Goweb::loadClass('Goweb_Js_Tree');
        Goweb::loadClass('Goweb_Js_Tree_Node');

        $tree = new Goweb_Js_Tree('paginas_acesso');
        $tree->useLines = false;
        $tree->useSelection = false;
        $tree->setExpand(true);

        if ($perfilId > 0 && count($permissoes) == 0) {
            $this->_cmsPermissaoModel->where('perfil_id=?', $perfilId);
            $permissoesRowset = $this->_cmsPermissaoModel->fetchAll();
            if ($permissoesRowset) {
                foreach ($permissoesRowset as $permissao) {
                    $permissoes[] = $permissao->pagina_id;
                }
            }
        }
        $node = new Goweb_Js_Tree_Node(0, -1, translateAdmin('Raiz'));
        $node->form_element = 'checkbox';
        if (in_array("0", $permissoes)) {
            $node->form_checked = true;
        }
        $tree->addNode($node);
        
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.sistema=?', '0');        
        $paginas = $this->_paginaModel->fetchAll();

        if ($paginas) {
            foreach ($paginas as $pagina) {
                $node = new Goweb_Js_Tree_Node($pagina->id,
                                               $pagina->pai_id,
                                               $pagina->titulo);
                $node->form_element = 'checkbox';
                if (in_array($pagina->id, $permissoes)) {
                    $node->form_checked = true;
                }
                $tree->addNode($node);
            }
        }

        return $tree;
    }
    
    protected function _saveAcl($type = 'front'){
        $perfil_id = $this->_getParam($this->_utilizadorModel->getPrimary());
        if (strcmp($type, 'back') == 0){
            $aclModel = Goweb::getModelInstance('Acl_Model_Backoffice', 'db');
        } else {
            $aclModel = Goweb::getModelInstance('Acl_Model_Frontoffice', 'db');
        }
        $aclModel->setUseCache();

        $aclModel->deleteWhere($aclModel->getAdapter()->quoteInto('perfil_id = ?', $perfil_id));
        if ($this->_request->modulos_acesso
                && is_array($this->_request->modulos_acesso)
                && count($this->_request->modulos_acesso)>0){

            $controllers = array();
            $modulos_acesso = $this->_request->modulos_acesso;
            foreach ($modulos_acesso as $acesso){
                preg_match_all("/controller_(.*)_action_(.*)/i", $acesso, $match);
                if (!isset($match[1][0]) || !isset($match[2][0])) continue;
                $controller = $match[1][0];
                $action = $match[2][0];

                $aclModel->perfil_id  = $perfil_id;
                $aclModel->controller = $controller;
                $aclModel->action     = $action;
                $aclModel->save();
                $aclModel->reset();

            }

        }
        $aclModel->setUseCache(true);
        goweb::loadClass('Zend_Cache');
        $cache = Zend_Registry::get('cache');
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
    }
}