<?php
namespace Hwapx\Admin\Controller\Admin;

use HwapX\Core\Library\ModuleManager;
use HwapX\Core\Library\Template;
use HwapX\Core\Library\DB\SQL\Mapper;

class Admin
{
    public $f3 = null;

    protected $module = null;

    private $beforeRouteHook = array();
    private $afterRouteHook  = array();

    /**
     * @param $f3
     */
    public function __construct($f3)
    {
        //if($f3->exists('COOKIE.admin'))
        //  $f3->set('SESSION.admin', $f3->get('COOKIE.admin'));

        $this->f3 = $f3;

        $f3->set('_sidebar', $this->_sidebar());

        foreach (ModuleManager::instance()->roles() as $module => $roles) {
            $f3->set('roles.'.$module, $roles);
        }

        if (!$f3->exists('SESSION.admin')) {
            $f3->reroute('@admin_login');
        } else {
            static::_user($f3->get('SESSION.admin.id'));
        }

        $this->module = ModuleManager::instance()->moduleOf($this);
    }

    /**
     * @return mixed
     */
    protected function _sidebar()
    {
        $sidebar = array();

        foreach (ModuleManager::instance()->modules as $ns => $module) {
            $class = "$ns\Module";

            if (defined($class.'::sidebar') || defined($class.'::SIDEBAR') || isset($class::$sidebar)) {
                $role_ns = str_replace('\\', '.', strtolower($ns)).'.';

                $menus = defined($class.'::sidebar') ? constant($class.'::sidebar') : 
                                                       defined($class.'::SIDEBAR') ? constant($class.'::SIDEBAR') :
                                                                                    $class::$sidebar;

                foreach ($menus as &$sub) {
                    foreach ($sub as &$menu) {
                        if (is_array($menu)) {
                            if (isset($menu['role']) && !strpos($menu['role'], '.')) {
                                $menu['role'] = $role_ns.$menu['role'];
                            }
                        }
                    }
                }


                $sidebar[] = $menus;
            }
        }


        $result = call_user_func_array('array_merge_recursive', $sidebar);

        function ikcount($arr)
        {
            $count = 0;


            foreach ($arr as $key => $value) {
                if (is_int($key)) {
                    $count++;
                }
            }


            return $count;
        }


        usort($result, function ($e1, $e2) {
            $c1 = ikcount($e1);
            $c2 = ikcount($e2);

            if(($c1 === 0 || $c2 === 0) && $c1 !== $c2) {
                return $c1 === 0 ? -1 : 1;
            }

            return strcasecmp($e1['label'], $e2['label']);
        });

        return $result;
    }

    /*public function beforeRoute($f3) {
        if(is_callable($f3)) {
            $this->beforeRouteHook[] = $f3;
            return;
        }

        foreach ($this->beforeRouteHook as $key => $hook) {
            call_user_func_array($hook, array($f3));
        }
    }

    public function afterRoute($f3) {
        if(is_callable($f3)) {
            $this->afterRouteHook[] = $f3;
            return;
        }

        foreach ($this->afterRouteHook as $key => $hook) {
            call_user_func_array($hook, array($f3));
        }
    }*/

    public static function _user($id) {
        $f3 = \F3::instance();

        $db = $f3->get('db');

        $f3->clear('SESSION.admin');

        $user = new Mapper($db, 'hwapx_user');
        $user->load(array('id = ?', $id));

        if(!$user->dry()) {
            if($user->session_id != md5($f3->get('IP').$f3->get('AGENT'))) {
                flash('warning', 'Você entrou em outro local.');
                $f3->reroute('@admin_login');
                return;
            }

            $user->last_activity = date('Y-m-d H:i:s');
            $user->save();

            $user->copyTo('SESSION.admin');
            $f3->clear('SESSION.admin.password');
            $f3->set('SESSION.admin.firstname', explode(' ', $user->name)[0]);

            $group = new Mapper($db, 'hwapx_group');
            $group->load(array('id = ?', $user->group_id));
            $group->copyTo('SESSION.admin.group');

            $f3->set('SESSION.admin.group.roles', explode(';', $f3->get('SESSION.admin.group.roles')));
            $f3->copy('SESSION.admin', 'admin');
        }
    }
}
