<?php

Goweb::loadClass('Goweb_Controller_Action_Admin');

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

    /**
     * Titulo do Modulo
     * @var string
     */
    protected $_title;

    /**
     * Controller do Modulo
     * @var string
     */
    protected $_controller = 'dashboard';

    /**
     * Seccoes do Modulo
     * @var array
     */
    protected $_sections;

    /**
     * Mensagem de Erro
     * @var string
     */
    protected $_error = null;

    /**
     * Mensagem de Sucesso
     * @var string
     */
    protected $_message = null;
    
    /**
     * Objecto Sistema_Model_Modulo
     * @var Sistema_Model_Modulo
     */
    protected $_moduloModel = null;

    /**
     * Construtor da classe
     */
    public function init() {
        parent::init();
        if (!$this->_session) $this->_session = Goweb::registry('session');
        $this->_title = translateAdmin('Dashboard');
        $this->_sections = array(array('title'   => translateAdmin('Dashboard'),
                                       'section' => 'dashboard',
                                       'link'    => '/dashboard/list/'));

        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->sections = $this->_sections;
        $this->_moduleConfig = false;
        if (file_exists(CACHE_PATH .'/dashboard.ini')){
            $this->_moduleConfig = new Zend_Config_Ini(CACHE_PATH .'/dashboard.ini', 'production', true);
        }
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db', false);
        
    }
    
    /**
     * Metodo chamado quando nenhuma action &eacute; fornecida
     */
    public function dashboardAction() {
        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/portal/portal.js');
        goweb::loadCss('/admin/media/js/portal/portal.css');
        goweb::loadCss('/admin/media/js/portal/newsportal/style.css');
        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');
        $this->view->section_title = translateAdmin('Dashboard');
        $this->view->output = $this->view->render('dashboard.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Noticias website goweb
     *
     */
    public function gowebRssAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (!goweb::isOnline()){ $this->_helper->viewRenderer->setNoRender(); return false;}
        $this->view->contentId = $this->_request->getActionName();
        $this->view->tituloDashboard = translateAdmin('Not&iacute;cias Goweb');
        $id = 0;
        $cache = Zend_Registry::get('cache');
        Goweb::loadClass('Zend_Feed_Rss');
        $gowebFeed = "http://www.goweb.pt/noticias/rss/?lang=" . $this->_session->lang;
        if(!$feed = $cache->load('rss_' .md5($gowebFeed))) {
            $feed = Zend_Feed::import($gowebFeed);
            $cache->save($feed, 'rss_' . md5($gowebFeed));
        }
        $i = 0;
        $rss = array();
        foreach ($feed->items as $item) {
            $rss[$i]['title']       = $item->title();
            $rss[$i]['link']        = $item->link();
            $i++;
        }
        $this->view->rss = $rss;
    }
    
    /**
     * Noticias website goweb
     *
     */
    public function twitterAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (!goweb::isOnline()){ $this->_helper->viewRenderer->setNoRender(); return false;}
        $this->view->contentId = $this->_request->getActionName();
        $this->view->tituloDashboard = translateAdmin('Twitter Goweb');
        $id = 0;
        $cache = Zend_Registry::get('cache');
        Goweb::loadClass('Zend_Feed_Rss');
        $gowebFeed = "http://twitter.com/statuses/user_timeline/24928512.rss";
        if(!$feed = $cache->load('rss_' .md5($gowebFeed))) {
            try {
                $feed = Zend_Feed::import($gowebFeed);
                $cache->save($feed, 'rss_' . md5($gowebFeed));
            } catch (Exception $e) {
                $this->view->rss = array();
                $this->_helper->viewRenderer->setRender('gowebRss');
                return true;
            }
        }
        $i = 0;
        $rss = array();
        foreach ($feed->items as $item) {
            $rss[$i]['title']       = $item->title();
            $rss[$i]['link']        = $item->link();
            $i++;
        }
        $this->view->rss = $rss;
        $this->_helper->viewRenderer->setRender('gowebRss');
    }
    
    /**
     * Novas submissoes do modulo de formularios
     *
     */
    public function formAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (($this->_moduloModel->findBy('nome', 'Form') && !$this->_moduloModel->menu) || !goweb::isReadable('Form_Model_Form', APPLICATION_PATH)){
            $this->_helper->viewRenderer->setNoRender();
            return;
        }
        $this->view->contentId = $this->_request->getActionName();

        goweb::loadClass('Zend_Date');
        $date = new Zend_Date();
        $date->sub('15', Zend_Date::DAY);
        $lastDate = $date->get('YYYY-MM-dd HH:mm:ss');
        $formModel = Goweb::getModelInstance('Form_Model_Form', 'db', false);
        $formModel->where('actualizado > ?', $lastDate);
        $formModel->order(array('-actualizado', '-submissoes', 'id'));
        $formModel->limit(100);

        $forms = $formModel->fetchAll(array('id', 'titulo', 'submissoes'));
        $this->view->forms = array();
        if ($forms){
            Goweb::loadModel('Form_Model_Barebone');
            foreach ($forms as $form){
                if ($form->submissoes == 0) continue;
                $model = new Form_Model_Barebone($formModel->getAdapter(), false);
                
                $model->setup($form->id);
                if (!isset($this->view->forms[$form->id])){
                    $this->view->forms[$form->id] = array();
                    $this->view->forms[$form->id]['form'] = $form->toArray();
                    $this->view->forms[$form->id]['list'] = '/form/list_submissoes/form_id/' . $form->id;
                    $this->view->forms[$form->id]['edit'] = '/form/edit_submissao/form_id/' . $form->id . '/id/';
                    $this->view->forms[$form->id]['labels'] = $model->getColsLabelsWithAliases();
                    $this->view->forms[$form->id]['submissoes']  = array();
                }
                $model->where('actualizado > ?', $lastDate);
                $model->order(array('-actualizado', 'id'));
                $model->limit(100);
                $this->view->forms[$form->id]['submissoes'][] = $model->fetchAll();
                
            }
        }
    }

    
    /**
     * Novas encomendas do site
     *
     */
    public function lojaAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (($this->_moduloModel->findBy('nome', 'Loja') && !$this->_moduloModel->menu) || !goweb::isReadable('Loja_Model_Encomenda', APPLICATION_PATH)){
            $this->_helper->viewRenderer->setNoRender();
            return;
        }
        $this->view->contentId = $this->_request->getActionName();
        goweb::loadClass('Zend_Date');
        $date = new Zend_Date();
        $date->sub('45', Zend_Date::DAY);
        $lastDate = $date->get('YYYY-MM-dd HH:mm:ss');
        $encomendaModel = Goweb::getModelInstance('Loja_Model_Encomenda', 'db', false);
        $encomendaModel->where('criado > ?', $lastDate);
        $encomendaModel->order(array('-criado', 'id'));
        $encomendaModel->limit(100);
        $this->view->lojaList = '/loja/editEncomenda/section/encomenda/id/';
        $this->view->encomendas = $encomendaModel->fetchAll(array('id', 'nome', 'valor'));
    }

    /**
     * Novos Utilizadores
     *
     */
    public function utilizadoresAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (($this->_moduloModel->findBy('nome', 'Utilizadores') && !$this->_moduloModel->menu) || !goweb::isReadable('Utilizadores_Model_Utilizador', APPLICATION_PATH)){
            $this->_helper->viewRenderer->setNoRender();
            return;
        }
        $this->view->contentId = $this->_request->getActionName();
        goweb::loadClass('Zend_Date');
        $date = new Zend_Date();
        $date->sub('100', Zend_Date::DAY);
        $lastDate = $date->get('YYYY-MM-dd HH:mm:ss');
        $utilizadorModel = Goweb::getModelInstance('Utilizadores_Model_Utilizador', 'db', false);
        $utilizadorModel->where('criado > ?', $lastDate);
        $utilizadorModel->order(array('-criado', 'id'));
        $utilizadorModel->limit(100);
        $this->view->utilizadoresList = '/utilizadores/edit/section/utilizadores/id/';
        $this->view->utilizadores = $utilizadorModel->fetchAll();
    }

    /**
     * Inqueritos
     *
     */
    public function inqueritosAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (($this->_moduloModel->findBy('nome', 'Inqueritos') && !$this->_moduloModel->menu) || !goweb::isReadable('Inqueritos_Model_Respostas', APPLICATION_PATH)){
            $this->_helper->viewRenderer->setNoRender();
            return;
        }
        $this->view->contentId = $this->_request->getActionName();
        $inqueritoModel = Goweb::getModelInstance('Inqueritos_Model_Respostas', 'db');
        $inqueritoModel->order(array('inquerito_id', 'criado', 'id'));
        $inqueritoModel->limit(100);
        $this->view->inqueritosList = '/inqueritos/list_respostas/section/respostas/id/';
        $inqueritos = $inqueritoModel->fetchAll(array('id', 'titulo', 'inquerito_id', 'votos'));
        $this->view->inqueritos = array();
        if ($inqueritos){
            foreach($inqueritos as $inquerito){
                if (!isset($this->view->inqueritos[$inquerito->inquerito_id])){
                    $this->view->inqueritos[$inquerito->inquerito_id] = array('titulo' => $inquerito->inquerito->titulo);
                    $this->view->inqueritos[$inquerito->inquerito_id]['respostas'] = array();
                    $this->view->inqueritos[$inquerito->inquerito_id]['total'] = 0;
                }
                $this->view->inqueritos[$inquerito->inquerito_id]['respostas'][$inquerito->id] = array('titulo' => $inquerito->titulo,
                                                                                         			   'votos'  => $inquerito->votos);
                $this->view->inqueritos[$inquerito->inquerito_id]['total'] += $inquerito->votos;
            }
        }
    }
    
    /**
     * Newsletter
     *
     */
    public function newsletterAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (($this->_moduloModel->findBy('nome', 'Newsletter') && !$this->_moduloModel->menu) || !goweb::isReadable('Newsletter_Model_InscritoCategoria', APPLICATION_PATH)){
            $this->_helper->viewRenderer->setNoRender();
            return;
        }
        $this->view->contentId = $this->_request->getActionName();
        $newsletterModel = Goweb::getModelInstance('Newsletter_Model_InscritoCategoria', 'db');
        goweb::loadClass('Zend_Date');
        $date = new Zend_Date();
        $date->sub('12', Zend_Date::DAY);
        $lastDate = $date->get('YYYY-MM-dd HH:mm:ss');
        $newsletterModel->where($newsletterModel->getTablename() . '.criado > ?', $lastDate);
        $newsletterModel->order(array('categoria_id', 'inscrito_id', 'id'));
        $this->view->newslettersList = '/newsletters/list_respostas/section/respostas/id/';
        $newsletterModel->limit(100);
        $newsletters = $newsletterModel->fetchAll();
        $this->view->categorias = array();
        $this->view->newsletters = array();
        if ($newsletters){
            foreach($newsletters as $newsletter){
                if (!isset($this->view->categorias[$newsletter->categoria_id])){
                    $this->view->categorias[$newsletter->categoria_id] = $newsletter->categoria->toArray();
                }
                if (!isset($this->view->newsletters[$newsletter->categoria_id])){
                    $this->view->newsletters[$newsletter->categoria_id] = array();
                }
                $this->view->newsletters[$newsletter->categoria_id][] = array('nome' => $newsletter->inscrito->nome, 
                                                                              'email' => $newsletter->inscrito->email);
            }
        }
    }
    
    /**
     * Visitas
     *
     */
    public function visitasAction(){
        if ($this->_directRequest) $this->_forward('dashboard');
        if (($this->_moduloModel->findBy('nome', 'Visitas') && !$this->_moduloModel->menu) || !goweb::isReadable('Visitas_Model_Visita', APPLICATION_PATH)){
            $this->_helper->viewRenderer->setNoRender();
            return;
        }
        $this->view->contentId = $this->_request->getActionName();
        $visitasModel = Goweb::getModelInstance('Visitas_Model_Visita', 'db');
        $visitasModel->where('activo = 0');
        $this->view->labels = $visitasModel->getColsLabelsWithAliases();
        $this->view->cols = $visitasModel->getColsNames();
        $visitasModel->limit(100);
        $this->view->visitas = $visitasModel->fetchAll();
    }
    
    public function configAction(){

        $actionName = $this->getFrontController()->getDispatcher()->formatActionName($this->_getParam('actionName'));
        if (!method_exists($this, $actionName)){
            return $this->_helper->viewRenderer->setNoRender();
        }
        
        
    }
    
    public function statsAction(){
        if (!goweb::isRegistered('db_stats')){
            require_once(WWW_PATH . '/admin/stats/global.php');
            require_once(WWW_PATH . '/admin/stats/' . LANGPATH . $cfg['langFile']);
            $this->view->db = $db;
            $this->view->text = $text;
            goweb::register('db_stats', $this->view->db);
            goweb::register('stats_text', $text);
        } else {
            $this->view->db = goweb::registry('db_stats');
            $this->view->text = goweb::registry('stats_text');
            
        }
        $this->view->contentId = $this->_request->getActionName();
        switch ($this->_getParam('type')) {
        	case 'month':
        	    $this->view->contentId .= '_month';
        	    $this->view->statsTitulo = 'Estat&iacute;sticas por m&ecirc;s';
        	    $this->view->statsUrl = '/admin/stats/by_mth.php';
        	break;
        	
        	case 'screen':
        	    $this->view->contentId .= '_screen';
        	    $this->view->statsTitulo = 'Estat&iacute;sticas por ecr&acirc;';
        	    $this->view->statsUrl = '/admin/stats/sys_screen.php';
        	break;
        	
        	case 'os':
        	    $this->view->contentId .= '_os';
        	    $this->view->statsTitulo = 'Estat&iacute;sticas por Sistema Operativo';
        	    $this->view->statsUrl = '/admin/stats/sys_os.php';
        	break;
        	
        	case 'country':
        	    $this->view->contentId .= '_country';
        	    $this->view->statsTitulo = 'Estat&iacute;sticas por Pa&iacute;s';
        	    $this->view->statsUrl = '/admin/stats/by_country.php';
        	break;
        	
        	case 'hour':
        	    $this->view->contentId .= '_hour';
        	    $this->view->statsTitulo = 'Estat&iacute;sticas por Hora';
        	    $this->view->statsUrl = '/admin/stats/by_hour.php';
        	break;
        	
        	case 'engine':
        	    $this->view->contentId .= '_engine';
        	    $this->view->statsTitulo = 'Estat&iacute;sticas por Motor de pesquisa';
        	    $this->view->statsUrl = '/admin/stats/ref_engine.php';
        	break;
        	
        	
        	
        	
        	
        	
        	
        	default:
        	    $this->view->statsTitulo = 'Estat&iacute;sticas por p&aacute;gina';
        	    $this->view->contentId .= '_page';
        	    $this->view->statsUrl = '/admin/stats/by_page.php';
    	    break;
        }
        
    }

    /**
     * Este Metodo &eacute; executado quando a action fornecida n&atilde;o
     * &eacute; encontrada
     */
    public function __call($action, $arguments) {
        $this->_forward('dashboard');
    }
    public function indexAction(){
        $this->_forward('dashboard');
    }
}