<?php

class admin_menu_model extends CI_Model
{

    protected $items = array();

    /**
     * Get menu items from DB
     * @return array
     */
    public function get_menu_items()
    {
        if (empty($this->items)) {
            $data = $this->db->
                            select('am.id_admin_menu, am.name as translate, am.page, am.image, am.parent_id, am.view_order, acl_resource, acl_action')->
                            where('am.active', TRUE)->
                            order_by('am.parent_id, view_order, translate', 'ASC')->
                            get('admin_menu am')->result_array();

            // Get parents
            $parents = array_filter($data, function($v) {

                return empty($v['parent_id']);
            });
            
            // Load languages
            $this->load->library('gettext_language');
            foreach ($parents as $litem) {
                foreach (array_keys($this->config->item('modules_locations')) as $v) {
                    $this->gettext_language->load($v . $litem['acl_resource'] . '/language/' . $this->config->item('language') . '.po');
                }
            }

            // Get children
            $acl = $this->rt_user;
            foreach ($parents as $parent) {
                $id = $parent['id_admin_menu'];
                $children = array_filter($data, function($v) use ($id, $acl) {

                    return ($v['parent_id'] == $id && $acl->isAllowed($v['acl_resource'], $v['acl_action']));
                });
                $parent['children'] = (!empty($children)) ? $children : NULL;
                // Remove parents with one child
                if (!is_null($parent['children']) && count($parent['children']) == 1 && $parent['acl_resource'] !== 'system') {
                    $child = reset($parent['children']);
                    $parent['page'] = $child['page'];
                    $parent['children'] = NULL;
                }
                if (!empty($children) || !empty($parent['page'])) {
                    $this->items[] = $parent;
                }
            }
        }

        return $this->items;
    }

    public function getFirstElementPage($pages = array())
    {
        if (empty($pages)) {
            $pages = $this->get_menu_items();
        }
        foreach ($pages as $item) {
            if (!empty($item['page'])) {

                return $item['page'];
            }
            if (!empty($item['children'])) {
                $childPage = $this->getFirstElementPage($item['children']);
            }
            if (!empty($childPage)) {

                return $childPage;
            }
        }

        return '';
    }

}
