<?php

Goweb::loadClass('Goweb_Form');

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.0
 * @category   Backoffice
 * @package    Cms
 * @subpackage Form
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
*/
class Form_Pagina extends Goweb_Form {
    
    /**
     * Objecto Goweb_Db_Model
     *
     * @var Goweb_Db_Model
    */
    protected $_model;
    
    /**
     * Atribui um valor a propriedade $_model
     *
     * @param Goweb_Db_Model
    */
    public function setModel(Goweb_Db_Model $model) {
        $this->_model = $model;
    }
    
    /**
     * Metodo obrigatorio as classes herdeiras do Goweb_Form
    */
    public function setup($pai_id = 0) {
        $perfis = array();
        $perfilModel = Goweb::getModelInstance('Utilizadores_Model_Perfil', 'db');
        $perfilRowset = $perfilModel->fetchAll();
        if ($perfilRowset) {
            foreach ($perfilRowset as $row) {
                $perfis[$row->id] = $row->nome;
            }
        }
        
        // pai_id
        $this->pai_id = $this->Select();
        $this->pai_id->label = $this->_model->getColParam('pai_id', 'label');
        $this->_model->where($this->_model->getTableName() . '.sistema=?', '0');
        if ($this->_model->isLoaded()) {
            $this->_model->where($this->_model->getTableName() . '.id<>' .  $this->_model->id);
            $this->pai_id->value = $this->_model->pai_id;
        } elseif ($pai_id) {                     
            $this->pai_id->value = $pai_id;
        }
        /*
         * Filtrar permissoes, por Pedro Pinto 
         */
        $session = Goweb::registry('session');
        if ($session->utilizador['perfil']['superuser'] == '0'){
            $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
            $cmsPermissaoModel->where('perfil_id=?', $session->utilizador['perfil_id']);
            $permissoes=$cmsPermissaoModel->fetchAll();
            $permissoespagina=array();
            foreach ($permissoes as $permissao){
                $permissoespagina[]=$permissao->pagina_id;
            }
            if ($this->pai_id->value)
                $permissoespagina[]=$this->pai_id->value;
            $this->_model->where($this->_model->getTableName() . '.id in (' . implode(",", $permissoespagina) . ')');
        }
        $options = array();
        $options['0'] = translateAdmin('Raiz');
        $rowset = $this->_model->fetchAll();
        if ($rowset) {
            foreach ($rowset as $row) {
                $options[$row->id] = $row->titulo;
            }
        }
        $this->pai_id->options = $options;        
        $this->pai_id->error_class = 'error';
        $this->pai_id->focus_class = 'focus';
        $this->pai_id->help = $this->_model->getColParam('pai_id', 'help');
        $this->pai_id->validators->Required(translateAdmin('O campo <b>{{campo}}</b> &eacute; de preenchimento obrigat&oacute;rio.', $this->pai_id->label));
        $colName = 'pai_id';
        $foreignModelName = get_class($this->_model);
        $this->{$colName . '_tafel'} = $this->Button();
        $this->{$colName . '_tafel'}->label = '<span>' . translateAdmin("Alterar {{campo}}", strip_tags($this->{$colName}->label)) . '</span>';
        $this->{$colName . '_tafel'}->setAttrib('onclick', 'Modalbox.show("' . str_replace('/admin', '', goweb::link('/index/treeSelect/')) . '?model=' . $foreignModelName . '&col=' . $colName . '", {title: "' . strip_tags($this->{$colName}->label) . '", evalScripts: true});');
        $this->{$colName . '_tafel'}->setAttrib('class', 'submitBtn');
        $this->{$colName . '_tafel'}->setAttrib('escape', false);
        goweb::loadJavascript('/admin/media/js/prototype.js');
        goweb::loadJavascript('/admin/media/js/scriptaculous/scriptaculous.js');
        goweb::loadJavascript('/admin/media/js/scriptaculous/effects.js');
        goweb::loadJavascript('/admin/media/js/modalbox.js');
        goweb::loadCss('/admin/media/css/modalbox.css');
        Goweb::loadCss('/admin/media/js/tafelTree/css/tree.css');
        Goweb::loadJavascript('/admin/media/js/tafelTree/Tree-optimized.js');

        // ordem
        $this->ordem = $this->Text();
        $this->ordem->size = '3';
        $this->ordem->maxlength = $this->_model->getColParam('ordem', 'maxlength');
        $this->ordem->label = $this->_model->getColParam('ordem', 'label');        
        $this->ordem->error_class = 'error';
        $this->ordem->focus_class = 'focus';
        $this->ordem->help = $this->_model->getColParam('ordem', 'help');
        
        // titulo
        $this->titulo = $this->Text();
        $this->titulo->size = '30';
        $this->titulo->maxlength = $this->_model->getColParam('titulo', 'maxlength');
        $this->titulo->label = $this->_model->getColParam('titulo', 'label');        
        $this->titulo->error_class = 'error';
        $this->titulo->focus_class = 'focus';
        $this->titulo->help = $this->_model->getColParam('titulo', 'help');
        $this->titulo->validators->Required(translateAdmin('O campo <b>{{campo}}</b> &eacute; de preenchimento obrigat&oacute;rio.', $this->titulo->label));
        
        // titulo_site
        $this->titulo_site = $this->Text();
        $this->titulo_site->size = '30';
        $this->titulo_site->maxlength = $this->_model->getColParam('titulo_site', 'maxlength');
        $this->titulo_site->label = $this->_model->getColParam('titulo_site', 'label');        
        $this->titulo_site->error_class = 'error';
        $this->titulo_site->focus_class = 'focus';
        $this->titulo_site->help = $this->_model->getColParam('titulo_site', 'help');
        
        if ($this->_model->colExists('popup')){
            // popup
            $this->popup = $this->Checkbox();
            $this->popup->label = $this->_model->getColParam('popup', 'label');
            $this->popup->error_class = 'error';
            $this->popup->focus_class = 'focus';
            if ($this->_model->getColParam('popup', 'default') && $this->_model->getColParam('popup', 'default') == '1') {
                $this->popup->value = '1';
            }
            $this->popup->help = $this->_model->getColParam('popup', 'help');
        }
        
        // redireccionar
        $this->redireccionar = $this->Text();
        $this->redireccionar->size = '30';
        $this->redireccionar->maxlength = $this->_model->getColParam('redireccionar', 'maxlength');
        $this->redireccionar->label = $this->_model->getColParam('redireccionar', 'label');
        $this->redireccionar->error_class = 'error';
        $this->redireccionar->focus_class = 'focus';
        $this->redireccionar->help = $this->_model->getColParam('redireccionar', 'help');
        $colName = 'redireccionar';
        $foreignModelName = get_class($this->_model);
        $this->{$colName . '_tafel'} = $this->Button();
        $this->{$colName . '_tafel'}->label = '<span>' . translateAdmin("Alterar {{campo}}", strip_tags($this->{$colName}->label)) . '</span>';
        $this->{$colName . '_tafel'}->setAttrib('onclick', 'Modalbox.show("' . str_replace('/admin', '', goweb::link('/index/treeSelect/')) . '?model=' . $foreignModelName . '&col=' . $colName . '&link=' . str_replace('/admin', '', goweb::link('/cms/view/id/{{id}}')) . '", {title: "' . strip_tags($this->{$colName}->label) . '", evalScripts: true});');
        $this->{$colName . '_tafel'}->setAttrib('class', 'submitBtn');
        $this->{$colName . '_tafel'}->setAttrib('escape', false);
        goweb::loadJavascript('/admin/media/js/prototype.js');
        goweb::loadJavascript('/admin/media/js/scriptaculous/scriptaculous.js');
        goweb::loadJavascript('/admin/media/js/scriptaculous/effects.js');
        goweb::loadJavascript('/admin/media/js/modalbox.js');
        goweb::loadCss('/admin/media/css/modalbox.css');
        Goweb::loadCss('/admin/media/js/tafelTree/css/tree.css');
        Goweb::loadJavascript('/admin/media/js/tafelTree/Tree-optimized.js');
        
        // canal
        $this->canal = $this->Select();
        $this->canal->options = $this->_getChannelViews();
        $this->canal->label = $this->_model->getColParam('canal', 'label');
        $this->canal->error_class = 'error';
        $this->canal->focus_class = 'focus';
        if ($this->_model->isLoaded()) {
            $this->canal->setValue($this->_model->canal);
        } else {
            $this->canal->setValue('base.tpl');
        }
        $this->canal->help = $this->_model->getCol('canal')->getParam('help');

        // homepage
        $this->homepage = $this->Checkbox();
        $this->homepage->label = $this->_model->getColParam('homepage', 'label');
        $this->homepage->error_class = 'error';
        $this->homepage->focus_class = 'focus';
        if ($this->_model->getColParam('homepage', 'default') && $this->_model->getColParam('homepage', 'default') == '1') {
            $this->homepage->value = '1';
        }
        $this->homepage->help = $this->_model->getCol('homepage')->getParam('help');
        
        // texto
        $this->texto = $this->Rte();
        $this->texto->theme = $this->_model->getColParam('texto', 'theme');
        $this->texto->css = $this->_model->getColParam('texto', 'css');
        $this->texto->width = '100%';
        $this->texto->height = '500px';
        $this->texto->help = $this->_model->getColParam('texto', 'help');

        // menu
        $this->menu = $this->Checkbox();
        $this->menu->label = $this->_model->getColParam('menu', 'label');
        $this->menu->error_class = 'error';
        $this->menu->focus_class = 'focus';
        if ($this->_model->getColParam('menu', 'default') && $this->_model->getColParam('menu', 'default') == '1') {
            $this->menu->value = '1';
        }
        $this->menu->setAttrib('onclick', 'showHidePopUp();');
        $this->menu->help = $this->_model->getColParam('menu', 'help');

        // semlink
        $this->semlink = $this->Checkbox();
        $this->semlink->label = $this->_model->getColParam('semlink', 'label');
        $this->semlink->error_class = 'error';
        $this->semlink->focus_class = 'focus';
        if ($this->_model->getColParam('semlink', 'default') && $this->_model->getColParam('semlink', 'default') == '1') {
            $this->semlink->value = '1';
        }
        $this->semlink->help = $this->_model->getColParam('semlink', 'help');

        // privado
        $this->privado = $this->Checkbox();
        $this->privado->label = $this->_model->getColParam('privado', 'label');
        $this->privado->error_class = 'error';
        $this->privado->focus_class = 'focus';
        if ($this->_model->getColParam('privado', 'default') && $this->_model->getColParam('privado', 'default') == '1') {
            $this->privado->value = '1';
        }
        $this->privado->setAttrib('onclick', 'showHidePerfis();');
        $this->privado->help = $this->_model->getColParam('privado', 'help');

        // keywords
        $this->keywords = $this->Textarea();
        $this->keywords->label = $this->_model->getColParam('keywords', 'label');
        //$this->keywords->size = $this->_model->getColParam('keywords', 'maxlength');
        $this->keywords->help = $this->_model->getColParam('keywords', 'help');
        $this->keywords->cols = $this->_model->getColParam('keywords', 'cols');
        $this->keywords->rows = $this->_model->getColParam('keywords', 'rows');
        
        $this->url = $this->Text();
        $this->url->size = '30';
        $this->url->maxlength = $this->_model->getColParam('url', 'maxlength');
        $this->url->label = $this->_model->getColParam('url', 'label');        
        $this->url->error_class = 'error';
        $this->url->focus_class = 'focus';
        $this->url->help = $this->_model->getColParam('url', 'help');
        //$this->url->validators->Url(translateAdmin('O campo <b>{{campo}}</b> n&atilde;o &eacute; um URL v&aacute;lido.', $this->url->label));
        if ($this->_model->colExists('sem_url')){
            // sem_url
            $this->sem_url = $this->Checkbox();
            $this->sem_url->label = $this->_model->getColParam('sem_url', 'label');
            $this->sem_url->error_class = 'error';
            $this->sem_url->focus_class = 'focus';
            if ($this->_model->getColParam('sem_url', 'default') && $this->_model->getColParam('sem_url', 'default') == '1') {
                $this->sem_url->value = '1';
            }
            $this->sem_url->help = $this->_model->getColParam('sem_url', 'help');
        }

        // perfis
        $this->perfis = $this->Select();        
        $this->perfis->label = translateAdmin('Perfis com acesso:');
        $this->perfis->multiple = true;
        $this->perfis->size = '5';
        $this->perfis->options = $perfis;
        $this->perfis->error_class = 'error';
        $this->perfis->focus_class = 'focus';
        
        // activo
        $this->activo = $this->Checkbox();
        $this->activo->label = $this->_model->getColParam('activo', 'label');
        $this->activo->error_class = 'error';
        $this->activo->focus_class = 'focus';
        if ($this->_model->getColParam('activo', 'default') && $this->_model->getColParam('activo', 'default') == '1') {
            $this->activo->value = '1';
        }
        $this->activo->help = $this->_model->getColParam('activo', 'help');
        
        // submit
        $this->submit = $this->Submit();
        $this->submit->value = translateAdmin('Gravar');
        $this->submit->class = 'form_submit';
        $this->submit_and_new = $this->Submit();
        $this->submit_and_new->value = translateAdmin('Gravar e adicionar novo');
        $this->submit_and_new->class = 'form_submit_and_new';
        $this->submit_and_continue = $this->Submit();
        $this->submit_and_continue->value = translateAdmin('Gravar e continuar a editar');
        $this->submit_and_continue->class = 'form_submit_and_continue';
    }

    /**
     * Metodo auxiliar que retorna o canal da view
     *
     * @return string
    */
    protected function _getChannelViews() {
        $channels = array();
        if (is_dir(VIEWS_PATH)) {            
            if ($handle = opendir(VIEWS_PATH)) {
                while (($file = readdir($handle)) !== false) {
                    if (is_file(VIEWS_PATH . DIRECTORY_SEPARATOR . $file)) {
                        $channels[$file] = $this->_formatViewName($file);
                    }
                }
                closedir($handle);
            }
        }
        return $channels;
    }

    /**
     * Criar arvore
     *
     * @param Goweb_Db_Model $model
     * @param array $nodesParams
     * @return Goweb_Js_Tree
     */
    protected function _getModelTree($model = 'Cms_Model_Pagina', $nodesParams = array('id'=> 'id', 'pid' => 'pai_id', 'name' => 'titulo'), $colName = null) {
        
        if (is_string($model)) $model = goweb::getModelInstance($model, 'db', false);

        // valida se foram passados os campos necesserio para o node
        if (!array_key_exists('id', $nodesParams)) {
            throw new Goweb_Exception("O campo  'id' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('pid', $nodesParams)) {
            throw new Goweb_Exception("O campo  'pid' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('name', $nodesParams)) {
            throw new Goweb_Exception("O campo  'name' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }

        $idCol = $nodesParams['id'];
        $pidCol = $nodesParams['pid'];
        $nameCol = $nodesParams['name'];
        $model->loadForeigns(false);
        Goweb::loadClass('Goweb_Tree');
        $tree = new Goweb_Tree($idCol, $pidCol);
        if ($model->colExists('ordem')) $model->order('ordem'); // ordena as paginas pelo campo ordem da bd
        
        $cols = array($idCol, $pidCol, $nameCol, 'redireccionar');
        foreach ($cols as $key => $col){
            if (!$model->colExists($col)) unset($cols[$key]);
        }
        $rowset = $model->fetchAll($cols);
        $link = '';
        if (!is_null($colName)){
            $link = "$(\"" . $colName . "\").value=\"{{id}}\"; Modalbox.hide(); return false;";
        }

        if ($rowset) {
            foreach ($rowset as $row) {
                $titulo = $row->{$nameCol};
                if (!is_null($colName)){
                    $titulo = "<a href='' onclick='" . $link . "'>" . $titulo . "</a>";
                    $titulo = str_replace('{{id}}', $row->{$idCol}, $titulo);
                }
                $node = array($idCol => $row->{$idCol},
                $pidCol => $row->{$pidCol},
                $nameCol => $titulo);

                // adiciona o node
                $tree->addElement($node);
            }
        }

        // retorna o Goweb_Js_Tree
        return $tree;
    }
    
    /**
     * Metodo auxiliar para formatacao do nome da view
     *
     * @param string
     *
     * @return string
    */
    protected function _formatViewName($unformatted) {
        $unformatted = substr($unformatted, 0, strlen($unformatted) - 4);
        $unformatted = str_replace(array('-', '_', '.'), ' ', strtolower($unformatted));
        $unformatted = preg_replace('[^a-z0-9 ]', '', $unformatted);
        return ucwords($unformatted);
    }
}