<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Menus extends Admin_Controller {

    public function __construct()
    {
        parent::__construct();

		$this->load->model('menus/menus_model');
        $this->lang->load('menus/menus');

        /* Title Page :: Common */
        $this->page_title->push(lang('menu_menus'));
        $this->data['pagetitle'] = $this->page_title->show();
        $_SESSION['id_modulo'] = 'MENUS';


        /* Breadcrumbs :: Common */
        $this->breadcrumbs->unshift(1, lang('menu_menus'), 'menus/menus');
    }
    
    
	public function index()
	{
       if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
        {
            redirect('auth/login', 'refresh');
        }
        else
        {
            /* Breadcrumbs */
            $this->data['breadcrumb'] = $this->breadcrumbs->show();
            $this->data['menus'] = $this->menus_model->menus()->result();

            /* Load Template */
            $this->template->admin_render('menus/index', $this->data);
        }
    }

    function data(){
        $permissions = permissions_list();
      $perm_parr = array();
      foreach($permissions as $row){
        $perm_parr[$row->parent_id][] = $row;
      }
      $this->output->set_output('[' . $this->loop_parent($perm_parr, 0, 0, 0, '') . ']');
    }

     function loop_parent($perm_parr, $parent_id, $curloop, $curid, $html){
    if(isset($perm_parr[$parent_id]) && count($perm_parr[$parent_id])>0){
      
          foreach($perm_parr[$parent_id] as $row){
              if(isset($perm_parr[$row->id]) && count($perm_parr[$row->id])>0){
                $html .= "{id:" . $row->id . ",name:'" . $row->permName . "', permKey:'" . $row->permKey . "', children:[";
                $html = $this->loop_parent($perm_parr, $row->id, $curloop + 1, $curid, $html) . ']},';
                
              }else{
                  $html .= "{id:" . $row->id . ",name:'" . $row->permName . "', permKey:'" . $row->permKey . "'},";
              }
          }                               
    }else{
        // $html .= ']},';
    }
    return $html;
    }     



    public function create()
    {
        if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
        {
            redirect('auth', 'refresh');
        }

        /* Breadcrumbs */
        $this->breadcrumbs->unshift(2, lang('menu_geocolonias'), 'geocolonias/create');
        $this->data['breadcrumb'] = $this->breadcrumbs->show();

        /* Validate form input */
        $this->form_validation->set_rules('nombre_menu', 'lang:create_Menu_validation_name_label', 'required');

        if ($this->form_validation->run() == TRUE)
        {
            $data['id_menupadre']           = $this->input->post('id_menupadre');
            $data['nombre_menu']                = $this->input->post('nombre_menu');   
            $data['menupos']                    = $this->input->post('menupos');  
            $data['columna']                    = $this->input->post('columna'); 
            $data['nivel']                      = $this->input->post('nivel');    
            $data['habilitado']                 = $this->input->post('concepto_habilitado'); 
            $data['id_group']                   = $this->input->post('groups'); 
            $data['id_vista']                   = $this->input->post('vistas');
            
            $new_vista_id                       = $this->menus_model->create_menu($data);

            if ($new_vista_id)
            {
                $this->session->set_flashdata('message', $this->ion_auth->messages());
                redirect('menus/menus', 'refresh');
            }else{
                $this->session->set_flashdata('message', $this->ion_auth->errors());
                redirect('menus/menus/create');

            }
        }
        else
        {
            $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

            $this->data['nombre_menu'] = array(
                'name'  => 'nombre_menu',
                'id'    => 'nombre_menu',
                'type'  => 'text',
                'class' => 'form-control',
                'value' => $this->form_validation->set_value('nombre_menu')
            );

           $this->data['menupos'] = array(
               'name'  => 'menupos',
               'id'    => 'menupos',
               'type'  => 'number',
               'class' => 'form-control',
               'value' => $this->form_validation->set_value('menupos')
           );


            $this->data['columna'] = array(
                'name'  => 'columna',
                'id'    => 'columna',
                'type'  => 'text',
                'class' => 'form-control',
                'value' => $this->form_validation->set_value('columna')
            );

            $this->data['nivel'] = array(
                'name'  => 'nivel',
                'id'    => 'nivel',
                'type'  => 'text',
                'class' => 'form-control',
                'value' => $this->form_validation->set_value('nivel')
            );

            //id_menupadre
            $padres  = $this->menus_model->menu('menus_jerarquia')->result_array();
            //inserta en un array asociativo para poder utilizarlo en el form_dropdown
            foreach ($padres as $pad) {
                if (intval($pad['id_menupadre']) == -1) {
                    $padress[0] = 'SIN PADRE';
                }else{
                    $padress[$pad['id']] = $pad['id'].' - '.$pad['nombre_menu'];
                }
                
            }
            $this->data['id_menupadre'] = $padress;

            
            $this->data['ddl_habilitado'] = $this->menus_model->v_habilitado()->result();
            $this->data['ddl_groups'] = $this->menus_model->groups()->result();
            $this->data['ddl_vistas'] = $this->menus_model->vistas()->result();
            $this->data['ddl_menupos'] = $this->menus_model->menus()->result();

            
            /* Load Template */
            $this->template->admin_render('menus/create', $this->data);
        }

    }


    public function edit($id)
    {
        /* Breadcrumbs */
        $this->breadcrumbs->unshift(2, lang('menu_menus_edit'), 'menus/edit');
        $this->data['breadcrumb'] = $this->breadcrumbs->show();

        /* Variables */

        $menus  = $this->menus_model->menu('menus', array('id' => $id))->row();
        
     
            /* Validación form input */
        $this->form_validation->set_rules('nombre_menu', 'lang:Menu_nombre_required', 'required');
      
        if (isset($_POST) && ! empty($_POST))
        {
            if ($this->form_validation->run() == TRUE)
            {
                    $data['nombre_menu']                = $this->input->post('nombre_menu');   
                    $data['menupos']                    = $this->input->post('menupos');  
                    $data['columna']                    = $this->input->post('columna'); 
                    $data['nivel']                      = $this->input->post('nivel');    
                    $data['habilitado']                 = $this->input->post('concepto_habilitado');
                    $data['id_menupadre']               = $this->input->post('id_menupadre');
                    $data['id_group']                   = $this->input->post('id_group'); 
                    $data['id_vista']                   = $this->input->post('id_vista'); 
                    
                $menu_update = $this->menus_model->update_menu($id, $data);

                if ($menu_update)
                {
                    $this->session->set_flashdata('message', $this->lang->line('edit_group_saved'));
                    redirect('menus/menus', 'refresh');
                }
                else
                {
                    $this->session->set_flashdata('message', $this->ion_auth->errors());
                }
                               
            }
        }

        //id_menupadre
        $padres  = $this->menus_model->menu('menus_jerarquia')->result_array();
        //inserta en un array asociativo para poder utilizarlo en el form_dropdown
        foreach ($padres as $pad) {
            if (intval($pad['id_menupadre']) == -1) {
                $padress[0] = 'SIN PADRE';
            }else{
                $padress[$pad['id']] = $pad['id'].' - '.$pad['nombre_menu'];
            }
            
        }
        $this->data['id_menupadre'] = $padress;
        $this->data['id_menupadre_sel'] = $menus->id_menupadre;

        //show_error($menus->id_menupadre);

        //habilitado
        $habilitado = $this->ion_auth_model->traer_concepto('HABILITADO','concepto')->result_array();
        //inserta en un array asociativo para poder utilizarlo en el form_dropdown
        foreach ($habilitado as $habi) {
            $habilitados[$habi['concepto']] = $habi['concepto'].' - '.$habi['nombre'];
        }
        $this->data['habilitado'] = $habilitados;
        $this->data['habilitado_sel'] = $menus->habilitado;

         //groups
        $grupos  = $this->menus_model->menu('groups')->result_array();
        //inserta en un array asociativo para poder utilizarlo en el form_dropdown
        foreach ($grupos as $grp) {
            $gruposs[$grp['id']] = $grp['id'].' - '.$grp['name'];
        }
        $this->data['id_group'] = $gruposs;
        $this->data['id_group_sel'] = $menus->id_group;

        //vistas
        //$id_group = $this->ion_auth_model->traer_concepto('HABILITADO','concepto')->result_array();
        $vistas  = $this->menus_model->menu('vistas')->result_array();
        //inserta en un array asociativo para poder utilizarlo en el form_dropdown
        foreach ($vistas as $vit) {
            $vistass[$vit['id']] = $vit['id'].' - '.$vit['nombre_vista'];
        }
        $this->data['id_vista'] = $vistass;
        $this->data['id_vista_sel'] = $menus->id_vista;


        /* Load Template */
        $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
        $this->data['menus']   = $menus;
    
           //$this->data['id_menupadre'] = array(
           //    'name'  => 'id_menupadre',
           //    'id'    => 'id_menupadre',
           //    'type'  => 'text',
           //    'class' => 'form-control',
           //    'value' => $this->form_validation->set_value('menus_id_menupadre', $menus->id_menupadre)
           //);
            $this->data['nombre_menu'] = array(
                'name'  => 'nombre_menu',
                'id'    => 'nombre_menu',
                'type'  => 'text',
                'class' => 'form-control',
                'value' => $this->form_validation->set_value('nombre_menu', $menus->nombre_menu)
            );

           $this->data['menupos'] = array(
               'name'  => 'menupos',
               'id'    => 'menupos',
               'type'  => 'number',
               'class' => 'form-control',
               'value' => $this->form_validation->set_value('menupos', $menus->menupos)
           );

            $this->data['columna'] = array(
                'name'  => 'columna',
                'id'    => 'columna',
                'type'  => 'text',
                'class' => 'form-control',
                'value' => $this->form_validation->set_value('columna', $menus->columna)
            );

            $this->data['nivel'] = array(
                'name'  => 'nivel',
                'id'    => 'nivel',
                'type'  => 'text',
                'class' => 'form-control',
                'value' => $this->form_validation->set_value('nivel', $menus->nivel)
            );

        $this->data['ddl_habilitado'] = $this->menus_model->v_habilitado()->result();
        $this->data['ddl_groups'] = $this->menus_model->groups()->result();
        $this->data['ddl_vistas'] = $this->menus_model->vistas()->result();
        $this->data['ddl_menupos'] = $this->menus_model->menus()->result();
        
        $this->template->admin_render('menus/edit', $this->data);
    }
 

    public function v_habilitado()
    {
        $this->response = $this->db->get($this->tables['v_habilitado']);

        return $this;
    }

    public function groups()
    {
        $this->response = $this->db->get($this->tables['groupsvistas']);

        return $this;
    }

    public function vistas()
    {
        $this->response = $this->db->get($this->tables['vistas']);

        return $this;
    }


    function delete($id){

    $vista_delete = $this->menus_model->delete_menu($id);

    if ($vista_delete)
    {
        $this->session->set_flashdata('message', $this->lang->line('edit_group_saved'));
        redirect('menus/menus');
    }
        else
        {
            $this->session->set_flashdata('message', $this->ion_auth->errors());
        }
    
    }


    //Estructura de árbol

   /* function data(){
        $permissions = permissions_list();
          $perm_parr = array();
          foreach($permissions as $row){
            $perm_parr[$row->parent_id][] = $row;
          }
          $this->output->set_output('[' . $this->loop_parent($perm_parr, 0, 0, 0, '') . ']');
        }
        
      function loop_parent($perm_parr, $parent_id, $curloop, $curid, $html){
        if(isset($perm_parr[$parent_id]) && count($perm_parr[$parent_id])>0){
          
              foreach($perm_parr[$parent_id] as $row){
                  if(isset($perm_parr[$row->id]) && count($perm_parr[$row->id])>0){
                    $html .= "{id:" . $row->id . ",name:'" . $row->permName . "', permKey:'" . $row->permKey . "', children:[";
                    $html = $this->loop_parent($perm_parr, $row->id, $curloop + 1, $curid, $html) . ']},';
                    
                  }else{
                      $html .= "{id:" . $row->id . ",name:'" . $row->permName . "', permKey:'" . $row->permKey . "'},";
                  }
              }                               
        }else{
            // $html .= ']},';
        }
        return $html;
    }     */
  
    function add(){
      //  check_permission('admin-add-permission');
        $id_menupadre = intval($this->input->get('id_menupadre'));
       // $this->template_data['parent_id'] = $parent_id;
        
       $this->load->view('menus/create');
    }
    

    
  /*  function edit(){
        check_permission('admin-edit-permission');
        $id = intval($this->input->get('id'));
        
        $this->db->where('id', $id);
        $info = $this->db->get('permissions')->row();
        $this->template_data['info'] = $info;
        
        $this->load->view('permissions_edit', $this->template_data);
    } */
    
  /*  function save(){
        $id = intval($this->input->post('id'));
        $this->form_validation->set_rules('permName', '权限名称', 'trim|required');
        $this->form_validation->set_rules('permKey', '权限KEY', 'trim|required');
        if($this->form_validation->run() === FALSE){
            json_response(array('success' => FALSE, 'msg' => validation_errors()));
        }else{
            if($id === 0){
                check_permission('admin-add-permission');
                $this->db->trans_begin();
                $data = array(
                    'parent_id' => intval($this->input->post('parent_id')),
                    'permName' => trim($this->input->post('permName')),
                    'permKey' => trim($this->input->post('permKey'))
                );
                $this->db->insert('permissions', $data);
                
                $new_perm_id = $this->db->insert_id();
                // 添加新权限总后台帐号自动授权
                $data1 = array(
                    'roleID' => 5,
                    'permID' => $new_perm_id,
                    'value' => 1
                );
                $this->db->insert('role_perms', $data1);
                // 更新权限缓存
                cxp_update_cache();
                $this->db->trans_complete();
                
                json_response(array('success' => TRUE, 'msg' => 'Add Permission Success'));
            }else{
                check_permission('admin-edit-permission');
                $this->db->trans_begin();
                $data = array(
                    'parent_id' => intval($this->input->post('parent_id')),
                    'permName' => trim($this->input->post('permName')),
                    'permKey' => trim($this->input->post('permKey'))
                );
                $this->db->where('id', $id);
                $this->db->update('permissions', $data);
                
                cxp_update_cache();
                $this->db->trans_complete();
                
                json_response(array('success' => TRUE, 'msg' => 'Edit Permission SUccess'));
            }
            
        }       
    }
    */
  
}



