<?php

namespace Hwapx\Admin;

include dirname(__FILE__).'/../core/helpers/xmlhelper.php';

use DB\SQL\Schema;

use Hwapx\Core\Library\Modulebase;
use Hwapx\Core\Library\Template;
use Hwapx\Core\Library\ModuleManager;
use Hwapx\Core\Library\DB\SQL\Mapper;

class Module extends Modulebase {
    public static $sidebar = array(
       'dashboard' => array(
            'label' => 'Dashboard',
            'icon' => 'dashboard',
            'route' => 'admin_dashboard',
            //, 'rule' => 'xxx'
            //array('icon' => 'fa-dashboard', 'label' => 'Dashboard', 'route' => 'admin_dashboard'/*, 'rule' => 'xxx'*/)
        ),/*
        'content' => array(
            'label' => 'Conteudo',
            'icon'  => 'archive',
            //array('icon' => 'fa-dashboard', 'label' => 'Conteudo', 'route' => 'xxxx', 'rule' => 'xxx')
        ),*/
        'management' => array(
            'label' => 'Administração',
            'icon'  => 'briefcase',
            array('icon' => 'user', 'label' => 'Usuários', 'route' => 'admin_users', 'role' => 'hwapx.admin.user_list'),
            array('icon' => 'tower', 'label' => 'Grupos', 'role' => 'hwapx.admin.group_list', 'route' => 'admin_group_list'),
        ),
        'system' => array(
            'label' => 'Sistema',
            'icon'  => 'cog',
            array('icon' => 'wrench', 'label' => 'Configurações', 'role' => 'hwapx.admin.settings', 'route' => 'admin_settings')
            //array('icon' => 'fa-dashboard', 'label' => 'Conteudo', 'route' => 'xxxx', 'rule' => 'xxx')
        ),
    );

    public static $roles = array(
        'settings'        => 'Configurações',

        'user_create'     => 'Criar Usuário',
        'user_edit'       => 'Editar Usuário',
        'user_remove'     => 'Remover Usuário',
        'user_list'       => 'Listar Usuários',

        'group_create'     => 'Criar Grupo',
        'group_edit'       => 'Editar Grupo',
        'group_remove'     => 'Remover Grupo',
        'group_list'       => 'Listar Grupos',
        'group_roles'      => 'Alterar permissões dos Grupos'
    );

    protected $f3;

    public function __construct($f3) {
        $this->f3     = $f3;
        $this->setupErrorHandler();
        Template::instance()->filter('role', '\Hwapx\Core\Library\ModuleManager::instance()->hasRole');
    }

    protected function setupErrorHandler() {
        $this->f3->set('ONERROR', function($f3) {
            error_log($f3->get('ERROR.text'));

            $logger = new \Log(date('Y-m-d').'_error.log');
            $logger->write(utf8_encode(strip_tags($f3->get('ERROR.text'))));
            
            $trace = trim($f3->get('ERROR.trace'));

            foreach(explode("\n", strip_tags($trace)) as $line) {
                if($line)
                    $logger->write('- '.html_entity_decode($line));
            }

            while (ob_get_level())
                ob_end_clean();

            $error = $f3->get('ERROR');

            if(!$f3->get('DEBUG')) {
                $error = array(
                    'status' => $error['status'],
                    'code'   => $error['code'],
                );
            }

            echo $f3->ajax() ? json_encode($error) : Template::instance()->render('hwapx/admin/admin/error.html');

            $code_re = $f3->get('settings.error.notify_codes');
            if($code_re && preg_match("/$code_re/", $f3->get('ERROR.code')))
                @$this->sendErrorNotification();
          }
        );
    }

    public function sendErrorNotification() {
        if(!function_exists('SMTPMessage') && !@include(dirname(__FILE__).'/../email/helpers/smtphelper.php')) return;
        $f3 = \F3::instance();

        $data = array(
            'server' => $_SERVER['SERVER_NAME'],
            'url'    => $f3->get('REALM'),
            'ip'     => $f3->get('IP'),
            'agent'  => $f3->get('AGENT'),
            'method' => $f3->get('VERB'),
            'query'  => $f3->get('QUERY'),
            'error'  => $f3->get('ERROR'),
            'cookie' => $f3->get('COOKIE'),
            'post'   => $f3->get('POST'),
            'get'    => $f3->get('GET'),
            'session'=> $f3->get('SESSION'),
            'files'  => $f3->get('FILES'),
            'headers'=> $f3->get('HEADERS'),
            'params' => $f3->get('PARAMS'),
            'ajax'   => $f3->get('AJAX') ? 'SIM' : 'NÃO',
            'time'   => date('Y-m-d H:i:s'),
            'admin'  => array(
                'id'    => $f3->get('SESSION.admin.id'),
                'name'  => $f3->get('SESSION.admin.name'),
                'email' => $f3->get('SESSION.admin.email'),
            ),
            'trace' => strip_tags(debug_backtrace())
        );

        $template = $f3->get('settings.error.email_template');
        
        return $template ? @SMTPMessage($template, $data) : null;
    }

    public function boot()
    {
        $db      = $this->f3->get('db');
        $setting = new Mapper($db, 'hwapx_setting');

        $settings = array();

        foreach ($setting->find(null, null, 2592000) as $s)
        {
            $this->f3->set("settings.{$s->id}", $s->value);
        }
    }

    public function install() {
        $db     = $this->f3->get('db');
        $schema = new Schema($db);
        $mapper = new Mapper($db, 'hwapx_setting');

        $mapper->id          = 'admin_color';
        $mapper->label       = 'Cor';
        $mapper->value       = 'blue';
        $mapper->field_order = 1;
        $mapper->group       = 'Admin';
        $mapper->type        = 'dropdown';
        $mapper->rules       = 'required|in=blue,black';
        $mapper->save();
        $mapper->reset();

        $mapper->id          = 'admin_layout_fixed';
        $mapper->label       = 'Layout Fixo';
        $mapper->value       = 'no';
        $mapper->field_order = 2;
        $mapper->group       = 'Admin';
        $mapper->type        = 'checkbox';
        $mapper->rules       = 'required';
        $mapper->save();
        $mapper->reset();

        $table = $schema->createTable('hwapx_group');
        $table->addColumn('active')->type_bool()->nullable(false);
        $table->addColumn('slug')->type_varchar()->nullable(false);
        $table->addColumn('description')->type_varchar(32)->nullable(false);
        $table->addColumn('roles')->type_text()->nullable(true);
        $table->addColumn('created_on')->type_datetime(true)->nullable(false);
        $table->addColumn('updated_on')->type_datetime()->nullable(true);
        $table->build();

        $mapper = new Mapper($db, 'hwapx_group');
        $mapper->description = 'Administrador';
        $mapper->slug        = 'administrator';
        $mapper->active      = true;
        $mapper->created_on  = date('Y-m-d H:i:s');
        $mapper->save();

        $mapper->reset();
        $mapper->description = 'Usuário';
        $mapper->slug        = 'user';
        $mapper->active      = true;
        $mapper->created_on  = date('Y-m-d H:i:s');
        $mapper->save();
    }

    public function uninstall() {
        $db     = $this->f3->get('db');
        $schema = new Schema($db);

        $db->exec('DELETE FROM hwapx_settings WHERE group=?', 'Admin');

        $schema->dropTable('hwapx_group');
    }
}