<?php
/*
 * Dynmic_menu.php
 */
class Dynamic_menu {
    // para CodeIgniter Super Global Referencias o variables globales
    private $ci;
    private $class_parent = 'class="waves-effect active"';
    private $class_last = '';

    function __construct() {
      // get a reference to CodeIgniter.
      $this->ci =& get_instance();
    }
     /**
     * build_menu($table, $type)
     * @param    string    the MySQL database table name.
     * @param    string    the type of menu to display.
     * @return    string    $html_out using CodeIgniter achor tags.
     */
    function build_menu() {
      $menu = array();
      $controller = $this->ci->router->fetch_class();
      $method = $this->ci->router->fetch_method();
      $usuario = $this->ci->session->userdata('usuario');
      $usuarios = $this->ci->db->where('id', $usuario)->get('usuario')->row();
      $perfil = $this->ci->session->userdata('perfil');
      $perfiles = $this->ci->db->where('id', $perfil)->get('perfil')->row();
      $perfilmenus = $this->ci->db->where('perfil', $perfil)->order_by("posicion", "asc")->get('perfilmenu')->result();
      // now we will build the dynamic menus.
      $html_out  = '';
      $html_out .= '<ul class="nav navbar-nav">';
      // me despliega del query los rows de la base de datos que deseo utilizar
      foreach ($perfilmenus as $data) {
        $id = $data->id;
        $perfil = $data->perfil;
        $menu = $data->menu;
        $parent_id = $data->parent_id;
        $is_parent = $data->is_parent;
        $menus = $this->ci->db->where('id', $menu)->get('menu')->row();
        $title = $menus->nombre;
        $url = $menus->url;
        $icon = $menus->icono;
        // are we allowed to see this menu?
        if ($parent_id == 0) {
          if ($is_parent == TRUE) {
            // CodeIgniter's anchor(uri segments, text, attributes) tag.
            $html_out .= '<li class="dropdown">';
            $html_out .= '<a href="#" class="dropdown-toggle flat-box" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">';
            $html_out .= '<i class="'.$icon.'"></i><span class="menu-text">'.$title.'</span><span class="caret"></span>';
            $html_out .= $this->get_childs($id);
            $html_out .= '</li>';
          } else {
            $html_out .= '<li class="flat-box">'.anchor($url, '<i class="'.$icon.'"></i><span class="menu-text">'.$title.'</span>', 'name="'.$title.'" id="'.$id.'"').'</li>';
          }
        }
        // print_r($id);
      }
      // loop through and build all the child submenus.
      $html_out .= '</ul>';
      return $html_out;
    }
     /**
     * get_childs($menu, $parent_id) - SEE Above Method.
     * Description:
     * Builds all child submenus using a recurse method call.
     * @param    mixed    $id
     * @param    string    $id usuario
     * @return    mixed    $html_out if has subcats else FALSE
     */
    function get_childs($id) {
        $has_subcats = FALSE;
        $controller = $this->ci->router->fetch_class();
        $method = $this->ci->router->fetch_method();
        $perfil = $this->ci->session->userdata('perfil');
        $html_out  = '';
        // query q me ejecuta el submenu filtrando por usuario y para buscar el submenu segun el id que traigo
        $perfilmenus = $this->ci->db->where('perfil', $perfil)->where('parent_id', $id)->order_by("posicion", "asc")->get('perfilmenu')->result();
        $html_out .= '<ul class="dropdown-menu">';
         foreach ($perfilmenus as $data) {
           $id = $data->id;
           $perfil = $data->perfil;
           $menu = $data->menu;
           $parent_id = $data->parent_id;
           $is_parent = $data->is_parent;
           $menus = $this->ci->db->where('id', $menu)->get('menu')->row();
           $title = $menus->nombre;
           $url = $menus->url;
           $icon = $menus->icono;
           $has_subcats = TRUE;
           $html_out .= '<li class="flat-box">'.anchor($url, '<span class="menu-text">'.$title.'</span>', 'name="'.$title.'" id="'.$id.'"').'</li>';
        }
        $html_out .= '</ul>';
        return ($has_subcats) ? $html_out : FALSE;
    }

    function get_childs_adminlte3($id, &$is_any_active = false) {
        $has_subcats = FALSE;
        $is_any_active = false;
        $perfil = $this->ci->session->userdata('perfil');
        $html_out  = '';
        $perfilmenus = $this->ci->db->select('perfilmenu.*, menu.posicion as menu_pos')
            ->from('perfilmenu')
            ->join('menu', 'perfilmenu.menu = menu.id')
            ->where('perfilmenu.perfil', $perfil)
            ->where('perfilmenu.parent_id', $id)
            ->where('menu.estado', 0)
            ->order_by('menu.posicion', 'asc')
            ->get()->result();
        
        $html_out .= '<ul class="nav nav-treeview">';
        foreach ($perfilmenus as $data) {
           $menu_id = $data->menu;
           $menus = $this->ci->db->where('id', $menu_id)->get('menu')->row();
           if (!$menus) continue;
           
           $title = $menus->nombre;
           $url = $menus->url;
           
           $icon = $menus->icono;
           if (!$icon || $icon == 'far fa-circle' || $icon == 'fas fa-circle' || $icon == 'fa fa-circle' || trim($icon) == 'fas' || trim($icon) == 'fa') {
               $title_low = mb_strtolower($title);
               if (stripos($title_low, 'lista') !== false) $icon = 'fas fa-list';
               elseif (stripos($title_low, 'categoria') !== false) $icon = 'fas fa-tags';
               elseif (stripos($title_low, 'perfil') !== false) $icon = 'fas fa-id-badge';
               elseif (stripos($title_low, 'proveedor') !== false) $icon = 'fas fa-truck';
               elseif (stripos($title_low, 'compra') !== false) $icon = 'fas fa-cart-arrow-down';
               elseif (stripos($title_low, 'ingreso') !== false) $icon = 'fas fa-arrow-circle-down';
               elseif (stripos($title_low, 'egreso') !== false) $icon = 'fas fa-arrow-circle-up';
               elseif (stripos($title_low, 'sistema') !== false || stripos($title_low, 'configur') !== false) $icon = 'fas fa-tools';
               elseif (stripos($title_low, 'menu') !== false) $icon = 'fas fa-sitemap';
               elseif (stripos($title_low, 'reporte') !== false) $icon = 'fas fa-chart-bar';
               else $icon = 'fas fa-dot-circle';
           }
           
           $has_subcats = TRUE;
           
           $current_uri = trim($this->ci->uri->uri_string(), '/');
           $menu_url = trim($url, '/');
           $active = ($current_uri == $menu_url) ? 'active' : '';
           
           if ($active) {
               $is_any_active = true;
           }
           
           $html_out .= '<li class="nav-item">';
           $html_out .= '<a href="'.base_url().$url.'" class="nav-link '.$active.'">';
           $html_out .= '<i class="nav-icon '.$icon.'"></i>';
           $html_out .= '<p>'.$title.'</p>';
           $html_out .= '</a>';
           $html_out .= '</li>';
        }
        $html_out .= '</ul>';
        return ($has_subcats) ? $html_out : FALSE;
    }

    function build_menu_adminlte3() {
      $perfil = $this->ci->session->userdata('perfil');
      $perfilmenus = $this->ci->db->select('perfilmenu.*, menu.posicion as menu_pos')
          ->from('perfilmenu')
          ->join('menu', 'perfilmenu.menu = menu.id')
          ->where('perfilmenu.perfil', $perfil)
          ->where('perfilmenu.parent_id', 0)
          ->where('menu.estado', 0)
          ->order_by('menu.posicion', 'asc')
          ->get()->result();
      
      $html_out  = '';
      $html_out .= '<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">';
      
      foreach ($perfilmenus as $data) {
        $id = $data->id;
        $menu_id = $data->menu;
        $is_parent = $data->is_parent;
        $menus = $this->ci->db->where('id', $menu_id)->get('menu')->row();
        if (!$menus) continue;
        $title = $menus->nombre;
        $url = $menus->url;
        
        // Limpiar y normalizar el icono de la base de datos
        $icon = $menus->icono;
        
        // Si el icono es de FontAwesome 4 (fa fa-xxx), convertir a FontAwesome 5 (fas fa-xxx)
        if ($icon && strpos($icon, 'fa ') === 0) {
            $icon = str_replace('fa ', 'fas ', $icon);
        }

        // Si no tiene icono, es genérico o circular, asignar uno representativo
        if (!$icon || $icon == 'fas fa-th' || $icon == 'fas fa-circle' || $icon == 'fas fa-dot-circle' || trim($icon) == 'fas' || trim($icon) == 'fa' || $icon == 'fa fa-th') {
            $title_low = mb_strtolower($title);
            if (stripos($title_low, 'venta') !== false || stripos($title_low, 'tpv') !== false) $icon = 'fas fa-cash-register';
            elseif (stripos($title_low, 'producto') !== false) $icon = 'fas fa-drumstick-bite';
            elseif (stripos($title_low, 'usuario') !== false || stripos($title_low, 'cliente') !== false) $icon = 'fas fa-users';
            elseif (stripos($title_low, 'reporte') !== false) $icon = 'fas fa-chart-bar';
            elseif (stripos($title_low, 'configur') !== false || stripos($title_low, 'sistema') !== false || stripos($title_low, 'ajuste') !== false) $icon = 'fas fa-tools';
            elseif (stripos($title_low, 'almacen') !== false || stripos($title_low, 'inventario') !== false) $icon = 'fas fa-boxes';
            elseif (stripos($title_low, 'caja') !== false) $icon = 'fas fa-money-bill-wave';
            elseif (stripos($title_low, 'cocina') !== false) $icon = 'fas fa-utensils';
            elseif (stripos($title_low, 'operacion') !== false) $icon = 'fas fa-tasks';
            else $icon = 'fas fa-th-large';
        }
        
        if ($is_parent == TRUE) {
            $is_child_active = false;
            $childs_html = $this->get_childs_adminlte3($id, $is_child_active);
            
            $menu_open = $is_child_active ? 'menu-open' : '';
            $link_active = $is_child_active ? 'active' : '';

            $html_out .= '<li class="nav-item has-treeview '.$menu_open.'">';
            $html_out .= '<a href="#" class="nav-link '.$link_active.'">';
            $html_out .= '<i class="nav-icon '.$icon.'"></i>';
            $html_out .= '<p>'.$title.'<i class="right fas fa-angle-left"></i></p>';
            $html_out .= '</a>';
            $html_out .= $childs_html;
            $html_out .= '</li>';
        } else {
            $current_uri = trim($this->ci->uri->uri_string(), '/');
            $menu_url = trim($url, '/');
            $active = ($current_uri == $menu_url) ? 'active' : '';

            $html_out .= '<li class="nav-item">';
            $html_out .= '<a href="'.base_url().$url.'" class="nav-link '.$active.'">';
            $html_out .= '<i class="nav-icon '.$icon.'"></i>';
            $html_out .= '<p>'.$title.'</p>';
            $html_out .= '</a>';
            $html_out .= '</li>';
        }
      }
      $html_out .= '</ul>';
      return $html_out;
    }

}
