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

include_once GROCERY_CRUD;

class Modulos extends Grocery{
		
	public function __construct()
	{
		parent::__construct();
		$this->load->model('modulos_model');
		/*if($this->session->userdata('perfil') > 2){
    	    redirect('auth/Acesso_restrito');
		}*/
	}
	
	public function index()
	{
		try{
			$this->ini_method();
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	
	public function modulo()
	{				
		try{			
			$this->ini_method();
			/* This is only for the autocompletion */
			$crud = new grocery_CRUD();
			
			$crud->unset_jquery();

			$crud->set_theme('bootstrap');
			$crud->set_table('sys_modules');
			$crud->set_subject('Modulo');
			
			$crud->columns('id_module','name','icon','active','visible','type');
		
		    $crud->fields(array('name','nickname','icon','visible','active','type','class','method','priority'));	
			$crud->add_fields(array('name','nickname','icon','local','visible','active','type','class','method','priority'));
				
			$this->valida_acoes($crud);		
			
			$crud->display_as('id_module','ID');
			$crud->display_as('name','Módulo');
			$crud->display_as('nickname','Apelido');
			$crud->display_as('priority','Posição');
			$crud->display_as('visible', 'Visível');	
			$crud->display_as('active', 'Status');	
			$crud->display_as('type', 'Tipo');
			
			$crud->callback_field('local',array($this,'_callback_local'));
			$crud->callback_field('type',array($this,'_callback_type'));
			$crud->callback_field('visible',array($this,'_callback_visible'));
			$crud->callback_column('visible',array($this,'_callback_column_visible'));
			$crud->callback_column('type',array($this,'_callback_column_type'));
			
			$crud->callback_before_insert(array($this,'modulo_before_insert'));
			$crud->callback_before_delete(array($this,'modulo_before_delete'));
			
			$crud->set_relation_n_n('acoes', 'sys_module_action', 'sys_actions', 'id_module', 'id_action', 'action');
			
			$output = $crud->render();
			
			Assets::add_module_js('sistema','modulo');
			
			$this->_example_output($output);
			
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	
	public function modulo_before_insert($post_array)
    {
        $module = strtolower($post_array['nickname']);
        $local = ($post_array['local'] == 1) ? APPPATH : BUPATH;
        
        if(!empty($module))
        {
            @mkdir($local."/modules/".$module, 0700);
            @mkdir($local."/modules/".$module."/assets", 0700);
            @mkdir($local."/modules/".$module."/assets/css", 0700);
            @mkdir($local."/modules/".$module."/assets/js", 0700);
            @mkdir($local."/modules/".$module."/assets/img", 0700);
            @mkdir($local."/modules/".$module."/config", 0700);
            @mkdir($local."/modules/".$module."/controllers", 0700);
            @mkdir($local."/modules/".$module."/helpers", 0700);
            @mkdir($local."/modules/".$module."/language/portuguese", 0700, TRUE);
            @mkdir($local."/modules/".$module."/libraries", 0700);
            @mkdir($local."/modules/".$module."/models", 0700);
            @mkdir($local."/modules/".$module."/views", 0700);
        }
        unset($post_array['local']);
        return $post_array;
    }
	
	public function modulo_before_delete($primary_key)
    {
        $secoes = $this->modulos_model->list_sections_by_module($primary_key);
        if($secoes != NULL)
        {
            foreach($secoes as $secao)
            {
                $this->secao_before_delete($secao->id_section);
            }
        }
        $this->modulos_model->delete_section_by_module($primary_key);
        return true;
    }
	
	public function secao()
	{
		try{
			$this->ini_method();
			
			$crud = new grocery_CRUD();
	
			$crud->set_theme('bootstrap');
			$crud->set_table('sys_module_sections');
			$crud->set_subject('Seção');
			$state = $crud->getState();
	
			$this->valida_acoes($crud);
			
			$crud->columns('id_section','id_module','name','type','class','method','visible');
			
			if($state == 'edit')
			{
			    $crud->fields('id_module', 'location', 'name', 'icon', 'type', 'class', 'method', 'visible', 'active', 'priority', 'acoes');    
			}
			else
			{
			    $crud->fields('id_module', 'module', 'location', 'name', 'icon', 'type', 'class', 'method', 'arquivo', 'visible', 'active', 'priority', 'acoes');
			    $crud->set_rules('arquivo', 'Criar Arquivo', 'callback_check_file_exists');
			    $crud->callback_field('arquivo',array($this,'_callback_arquivo'));
			    $crud->field_type('module', 'hidden');
			    $crud->display_as('arquivo', 'Criar Arquivo');
			}
	
			$crud->display_as('id_section','ID');
			$crud->display_as('id_module','Módulo');
			$crud->display_as('name','Seção');
			$crud->display_as('priority','Posição');
			$crud->display_as('location','Área');
			$crud->display_as('visible','Visível');
			$crud->display_as('icon', 'Ícone');
			$crud->display_as('active', 'Status');	
			$crud->display_as('type', 'Tipo');
			$crud->display_as('acoes', 'Ações');
			$crud->field_type('priority', 'hidden');
			$crud->set_relation('location', 'sys_module_location', 'location');
			$crud->set_relation('id_module', 'sys_modules', 'name');			
			$crud->callback_field('visible',array($this,'_callback_visible'));	
			$crud->callback_column('type',array($this,'_callback_column_type'));
			$crud->callback_field('type',array($this,'_callback_type'));
				
			$crud->set_relation_n_n('acoes', 'sys_section_action', 'sys_actions', 'id_section', 'id_action', 'action');
				
			//$crud->callback_before_delete(array($this,'before_delete_subsecao'));
			
			$crud->callback_before_insert(array($this,'secao_before_insert'));
			$crud->callback_before_update(array($this,'secao_before_update'));
	        $crud->callback_before_delete(array($this,'secao_before_delete'));
			
			$output = $crud->render();
			
			Assets::add_module_js('sistema','secao');
	
			$this->_example_output($output);
				
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	
	public function check_file_exists($str)
    {
        if ($str == 1)
        {
            $module = $this->input->post('module');
            $class = $this->input->post('class');
            
            $path = 'modules/'.strtolower($module).'/controllers/'.ucfirst($class).'.php';
            
            if(file_exists(APPPATH.$path) || file_exists(BUPATH.$path))
            {
                $this->form_validation->set_message('check_file_exists', 'Não foi possível criar o arquivo, classe já existe!');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
        else
        {
            return TRUE;
        }
    }
	
	function secao_before_insert($post_array) 
	{
	    if($post_array['arquivo'] == 1)
	    {
	        $this->create_section($post_array);
	    }
        unset($post_array['module']);
        unset($post_array['arquivo']);
        
        return $post_array;
    }
    
    private function create_section($post_array)
    {
        $module = strtolower($post_array['module']);
        $class = ucfirst($post_array['class']);
        $method = ($post_array['method'] == '') ? 'index' : $post_array['method'];
        $extends = ($post_array['location'] == 1) ? 'Builder_Controller' : 'Admin_Controller';
        
        if(file_exists(APPPATH.'modules/'.$module))
        {
            $path = APPPATH.'modules/'.$module.'/controllers/'.$class.'.php';     
        }
        elseif(file_exists(BUPATH.'modules/'.$module))
        {
            $path = BUPATH.'modules/'.$module.'/controllers/'.$class.'.php';
        }
	    $file = fopen($path, "w");
        $txt = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n\nclass {$class} extends {$extends}\n{\n";
        $txt .= "\tpublic function __construct() \n\t{\n\t\tparent::__construct();\n\t}\n\n";
        $txt .= "\tpublic function {$method}() \n\t{\n\n\t}\n}";
        
        fwrite($file, $txt);
        fclose($file);
    }
	
    function secao_before_update($post_array, $primary_key) 
    {
        $acoes = $this->modulos_model->list_all_actions();
        $acoes_delete = array();
        foreach($acoes as $acao)
        {
            if(!in_array($acao->id_action, $post_array['acoes'])) 
            {
                $acoes_delete[] = $acao->id_action;
            }
        }
        
        $teste = $this->modulos_model->delete_action_rel_perfil_by_id('id_section',$primary_key, $acoes_delete);
        return $post_array;
    }
    
    public function secao_before_delete($primary_key)
    {
        $subsecoes = $this->modulos_model->list_subsections_by_section($primary_key);
        if($subsecoes != NULL)
        {
            foreach($subsecoes as $subsecao)
            {
                $this->subsecao_before_delete($subsecao->id_subsection);
            }
        }
        
        $this->modulos_model->delete_subsection_by_section($primary_key);
        $this->modulos_model->delete_section_rel_perfil($primary_key);
        $this->modulos_model->delete_section_section_action($primary_key);
        
        return true;
    }
	
	public function subsecao()
	{ /*Nunca estive aqui by robygol*/
		try{
			$this->ini_method();
				
			$crud = new grocery_CRUD();
	
			$crud->set_theme('bootstrap');
			$crud->set_table('sys_module_subsections');
			//$crud->set_model('subsecao_crud_model');
			
			$crud->set_subject('Subseção');
	
			$this->valida_acoes($crud);
	
			$crud->columns('id_subsection','id_module','id_section','name','class','method','visible');
	
			$crud->display_as('id_subsection','ID');
			$crud->display_as('id_module','Módulo');
			$crud->display_as('id_section','Seção');
			$crud->display_as('name','Subseção');
			$crud->display_as('priority','Posição');
			$crud->display_as('visible','Visível');
			$crud->display_as('icon', 'Ícone');
			$crud->display_as('active', 'Status');
			$crud->display_as('type', 'Tipo');
			$crud->display_as('acoes', 'Ações');
			$crud->field_type('priority', 'hidden');
			$crud->set_relation('id_module', 'sys_modules', 'name');
			$crud->set_relation('id_section', 'view_module_sections', 'name');
			$crud->callback_field('visible',array($this,'_callback_visible'));
			$crud->callback_column('type',array($this,'_callback_column_type'));
			$crud->callback_field('type',array($this,'_callback_type'));
			
			$crud->set_primary_key('id_section', 'view_module_sections');
	
			$crud->set_relation_n_n('acoes', 'sys_subsection_action', 'sys_actions', 'id_subsection', 'id_action', 'action');
	
			//$crud->callback_before_delete(array($this,'before_delete_subsecao'));
	        
	        $crud->callback_before_update(array($this,'subsecao_before_update'));
	        $crud->callback_before_delete(array($this,'subsecao_before_delete'));
	        
			$output = $crud->render();
				
			Assets::add_module_js('sistema','subsecao.js');
	
			$this->_example_output($output);
	
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	
	function subsecao_before_update($post_array, $primary_key) {
        //--------------------------------------------------------------------------------------------------------------------------------
        /*echo "<pre>";
        var_dump($post_array['acoes']);
        echo "</pre>";*/
        
        $acoes = $this->modulos_model->list_all_actions();
        $acoes_delete = array();
        foreach($acoes as $acao)
        {
            if(!in_array($acao->id_action, $post_array['acoes'])) 
            {
                $acoes_delete[] = $acao->id_action;
            }
        }
        
        $teste = $this->modulos_model->delete_action_rel_perfil_by_id('id_subsection',$primary_key, $acoes_delete);
        
       return $post_array;
    }
    
    public function subsecao_before_delete($primary_key)
    {
    	$this->modulos_model->delete_subsection_rel_perfil($primary_key);
        $this->modulos_model->delete_subsection_subsection_action($primary_key);
        
        return true;
    }
    
	public function before_delete_subsecao($id_subsecao)
	{
    	$this->load->model('perfil','perfil_model');
    	$return = $this->perfil_model->excluir_subsecao_relacional($id_subsecao);
    	
    	return $return;
	}
	
	public function _callback_column_icon($value, $row)
	{
		return "<i class='".$value."'></i>";
	}
	
	public function _callback_column_visible($value, $row)
	{
		if($value == 1) return 'Sim';
		return 'Não';
	}
	
	public function _callback_column_type($value, $row)
	{
		if($value == 1) return 'Único';
		return 'Múltiplo';
	}
	
	public function _callback_local($value = '', $primary_key = NULL)
	{ 
		if($value === NULL) $value = 1;
		
		return $this->callback_radio($value,'local',1,2,'Application','Builder');
	}
	
	public function _callback_type($value = '', $primary_key = NULL)
	{ 
		if($value === NULL) $value = 1;
		
		return $this->callback_radio($value,'type',1,2,'Único','Múltiplo');
	}
	
	public function _callback_visible($value = '', $primary_key = NULL)
	{
		if($value === NULL) $value = 1;
		
		return $this->callback_radio($value,'visible',1,2,'Sim','Não');
	}
	
	public function _callback_arquivo($value = '', $primary_key = NULL)
	{
		if($value === NULL) $value = 2;
		
		return $this->callback_radio($value,'arquivo',1,2,'Sim','Não');
	}
	
	public function acao()
	{
		try{			
			$this->ini_method();
			/* This is only for the autocompletion */
			$crud = new grocery_CRUD();
			
	        $this->valida_acoes($crud);
	        
			$crud->set_theme('bootstrap');
			$crud->set_table('sys_actions');
			$crud->set_subject('Ação');
	        $crud->columns('id_action','action');
	        $crud->callback_before_delete(array($this,'acao_before_delete'));
 
            $output = $crud->render();
	
			$this->_example_output($output);
	
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	
	public function acao_before_delete($primary_key)
    {
    	$this->modulos_model->delete_action_rel_perfil($primary_key);
        $this->modulos_model->delete_action_subsection_action($primary_key);
        $this->modulos_model->delete_action_section_action($primary_key);
        
        return true;
    }
    
	public function consulta_secoes_ajax()
	{
		if($this->input->post() == TRUE)
		{
			$id_module = $this->input->post('id_module');
	
			$result = $this->modulos_model->list_sections_by_module($id_module);
			if(!empty($result))
			{
				$data['show'] = true;
				$data['html'] = "<select id='field-id_section' name='id_section' class='chosen-select' data-placeholder='Selecione uma Seção' style='width: 300px;'>";
				$data['html'] .= "<option value=''></option>";
				foreach($result as $value)
				{
					$data['html'] .= "<option value='$value->id_section' >$value->name</option>";
				}
	
				$data['html'] .= "</select>";
			}
			else
			{
				$data['show'] = false;
				$data['html'] = "<input type='text' name='id_section' value='Não há seção cadastrada para o módulo selecionado.' readonly='readonly'> ";
			}
			echo json_encode($data);
		}
	}
	
}