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

class Usuarios extends Grocery{
	
	protected $crud;
	function __construct()
	{
		parent::__construct();
	}
	
	function index()
	{			
		try{
		    $this->ini_method();
		    
			$crud = new grocery_CRUD();

			$this->valida_acoes($crud);
			
			$crud->set_theme('bootstrap');
			$crud->set_table('sys_users');
			$crud->set_subject('Usuário do Painel');
			$crud->unset_read();
			$crud->unset_print();
			$crud->unset_export();
			
			$perfil = $this->session->userdata('perfil');
			$user_id = $this->session->userdata('user_id');
			$stateInfo = $crud->getStateInfo();
			$state = $crud->getState();
			
			if(!($perfil == 1 || $perfil == 2))
			{
			   /* $crud->where('sys_users.perfil != ','2');
			    if (isset($stateInfo->primary_key) && $this->get_perfil_user($stateInfo->primary_key) == 2)
					header("Location: javascript:history.back(1)");*/
				if (!isset($stateInfo->primary_key) || $stateInfo->primary_key != $user_id)
				{
					redirect('sistema/usuarios/index/edit/'.$user_id);
				}
				$crud->unset_back_to_list();
			}
			if($perfil != 1)
			{
				$crud->where('sys_users.perfil != ','1');
				if (isset($stateInfo->primary_key) && $this->get_perfil_user($stateInfo->primary_key) == 1)
					header("Location: javascript:history.back(1)");
			} 
			
			/*
			* Somente para o modulo Cadastro classes cliente pf, pj e colaborador
			if($state == 'add')
			{
				$id_rel_pf = (int) $this->uri->segment(5);
				if ($id_rel_pf == null)
				{	
				    header("Location: javascript:history.back(1)");
				}
				$crud->field_type('id_rel_pf', 'hidden',$id_rel_pf);
			}*/
			
			if($state == 'insert_validation')
			{			
				$crud->set_rules('username', 'Username', 'trim|required|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|callback_username_check');
			}
			
			Assets::add_module_js('sistema',array(
				'usuario.js'
		    ));
			
			$this->config_perfil_edit($crud);
			
		
			$this->display_usuarios($crud);
			
			$output = $crud->render();
			
			$this->_example_output($output);
			
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	
	private function config_perfil_edit($crud)
	{
		$perfil = $this->session->userdata('perfil');
		$user_id = $this->session->userdata('user_id');
		$state = $crud->getState();
		$stateInfo = $crud->getStateInfo();
		
		if ($state == 'edit' ||  $state == 'update' || $state == 'update_validation' )
		{
			$perfil_da_pk = $this->get_perfil_user($stateInfo->primary_key);
			
			return $crud->fields('perfil','nome','username','password','passconf','email');
				
			/*if ($stateInfo->primary_key == $user_id || $perfil_da_pk == $perfil)
			{
				return $crud->fields('nome','username','password_before','password','passconf','email')
							->callback_add_field('password_before',array($this,'formata_passconf1'))
							->callback_edit_field('password_before',array($this,'formata_password_b'))
							->set_rules('password_before', 'Senha Antiga', 'trim|required|callback_valida_senha');
			}
			else
			{
				return $crud->fields('perfil','nome','username','password','passconf','email');
			}*/
		}
		else
		{
			return $crud->fields('perfil','nome','username','password','passconf','email');//,'id_rel_pf'
		}
	}
	
	private function display_usuarios($crud)
	{
	    $this->crud = $crud;
		return $crud->set_rules('email', '"e-mail"',array('required','valid_email','trim',array('test_email',
                        		function($str)
                        		{
                        		    $stateInfo = $this->crud->getStateInfo();
                                    $user = @$this->db->where('email',trim($str))->where('id !=',$stateInfo->primary_key)->get('sys_users')->row();
                                    if($user != null){
                                        $this->form_validation->set_message('test_email', '"'.$str.'" já está sendo utilizado por outro usuário.');
                                          return FALSE;
                                    }
                                    return TRUE;
                                }
                            )
                        )
                    )		
                    ->set_rules('password', 'Senha', 'trim|required|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']')
					->set_rules('passconf', 'Confirmar Senha', 'trim|required|matches[password]')
					->set_relation('perfil', 'sys_perfil', 'perfil')
					->display_as('password_before','Senha Antiga')
					->display_as('username','Login')
					->display_as('password','Senha')
					->display_as('passconf','Confirmar Senha')
					->display_as('email','E-mail')
					->columns('perfil','nome','username', 'email')
					->callback_add_field('username',array($this,'formata_username1'))
					->callback_add_field('password',array($this,'formata_password1'))
					->callback_add_field('passconf',array($this,'formata_passconf1'))
					->callback_add_field('perfil',array($this,'formata_perfil_edit'))
					->callback_edit_field('username',array($this,'formata_username'))
					->callback_edit_field('password',array($this,'formata_password'))
					->callback_edit_field('passconf',array($this,'formata_passconf'))
					->callback_edit_field('perfil',array($this,'formata_perfil_edit'))
					->callback_before_delete(array($this,'callback_before_delete'))
					->callback_before_update(array($this,'callback_before_update'))
					->callback_before_insert(array($this,'callback_before_insert'));
	}
	
	public function callback_before_delete($primary_key)
    {
        $perfil = $this->session->userdata('perfil');
		$user_id = $this->session->userdata('user_id');
        $perfil_da_pk = $this->get_perfil_user($primary_key);
        
        if($user_id == $primary_key)
            return false;
           
        if($perfil > 1 && $perfil_da_pk <= 2)
            return false;
        
        return true;
    }
	
	
	public function valida_senha($str)
	{	
		$this->load->model('usuario_model');
		$user_id = $this->session->userdata('user_id');
			
		$password = $this->usuario_model->get_user_by_id($user_id)->password;
			
		$hasher = new PasswordHash(
				$this->config->item('phpass_hash_strength', 'tank_auth'),
				$this->config->item('phpass_hash_portable', 'tank_auth'));
	
		if ($hasher->CheckPassword($str, $password))
		{
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('valida_senha', 'SENHA INVALIDA!');
			return FALSE;
		}
	}
	
	private function get_perfil_user($id_user)
	{
		$this->load->model('usuario_model');
		$perfil = $this->usuario_model->get_perfil($id_user);
		if ($perfil != NULL)
			return $perfil->perfil;
		return NULL;
	}
	
	function formata_password_b($value, $primary_key)
	{
		return '<input class="form-control" type="password" maxlength="20" value="" name="password_before">';
	}
	
	// INSERIR
	
	function formata_username1()
	{			 
	    return '<input class="form-control" type="text" maxlength="50" value="" name="username" >';
	}
	
	function formata_password1()
	{
	    return '<input class="form-control" type="password" maxlength="20" value="" name="password" >';
	}
	
	function formata_passconf1()
	{
	    return '<input class="form-control" type="password" maxlength="20" value="" name="passconf" >';
	}
	
	/*function formata_perfil()
	{
		$retorno  = '<select class="form-control" id="field-perfil" name="perfil" class="chosen-select" data-placeholder="Selecione um Perfil"><option value="2">Administrador</option></select>';
		$retorno .= '<link type="text/css" rel="stylesheet" href="'.base_url().'assets/grocery_crud/css/jquery_plugins/chosen/chosen.css">';
		$retorno .= '<script src="'.base_url().'assets/grocery_crud/js/jquery_plugins/jquery.chosen.min.js" charset="utf-8"></script>';
		$retorno .= '<script src="'.base_url().'assets/grocery_crud/js/jquery_plugins/config/jquery.chosen.config.js" charset="utf-8"></script>';
		 
		return $retorno;
	}*/
	
	function formata_perfil_edit($value, $primary_key)
	{
		$perfil = $this->session->userdata('perfil');
		$this->load->model('usuario_model');
		$options = $this->usuario_model->listar_perfis();
		$perfil_da_pk = $this->get_perfil_user($primary_key);
		if($perfil == 2)
		{
		    unset($options[0]);
		}
		
		if(!($perfil == 1 || $perfil == 2))
		{
			foreach ($options as $key=>$option)
			{
				if ($option->id_perfil != $perfil_da_pk)
					unset($options[$key]);
			}
		}
	
		$retorno  = '<select class="form-control chosen-select" id="field-perfil" name="perfil"  data-placeholder="Selecione um Perfil">';
			foreach ($options as $option)			
			{
				if ($option->id_perfil == $perfil_da_pk)
					$retorno .= '<option value="'.$option->id_perfil.'" selected >'.$option->perfil.'</option>';
				else
					$retorno .= '<option value="'.$option->id_perfil.'"  >'.$option->perfil.'</option>';
			}
		$retorno .=	'</select>';
		//$retorno .= '<link type="text/css" rel="stylesheet" href="'.base_url().'assets/grocery_crud/css/jquery_plugins/chosen/chosen.css">';
		//$retorno .= '<script src="'.base_url().'assets/grocery_crud/js/jquery_plugins/jquery.chosen.min.js" charset="utf-8"></script>';
		//$retorno .= '<script src="'.base_url().'assets/grocery_crud/js/jquery_plugins/config/jquery.chosen.config.js" charset="utf-8"></script>';
		return $retorno;
	}
	
	function username_check($username)
	{
		$this->load->model ( 'usuario_model', 'usuario' );
		
		$query_result = $this->usuario->valida_username( $username );
		
		
		if ($query_result === FALSE)
		{
			$this->form_validation->set_message('username_check', 'O login '.$username.' já existe, por favor escolha outro login.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}		
	}
	
	function callback_before_insert($post_array)
	{	    
    	// Hash password using phpass
		$hasher = new PasswordHash(
				$this->config->item('phpass_hash_strength', 'tank_auth'),
				$this->config->item('phpass_hash_portable', 'tank_auth'));
		$post_array['password'] = $hasher->HashPassword($post_array['password']);
	    	    
	    unset($post_array['passconf']);	    

	    if($this->session->perfil != 1 && $post_array['perfil'] == 1)
	    {
	        $post_array['perfil'] = null;
	        //break;
	    }
	    if($this->session->perfil > 2 && $post_array['perfil'] <= 2)
	    {
	        $post_array['perfil'] = null;
	        //break;
	    }
	    
	    return $post_array;
	}
	
	// ALTERAR

	function formata_username($value, $primary_key)
	{
	    return '<input class="form-control" type="text" maxlength="50" value="'.$value.'" name="username" readonly="readonly" >';
	}
	
	function formata_password($value, $primary_key)
	{
	    return '<input class="form-control" type="password" maxlength="20" value="xxxxxx" name="password" onBlur="password_blur(this)" onFocus="password_focus(this)" >';
	}
	
	function formata_passconf($value, $primary_key)
	{
	    return '<input class="form-control" type="password" maxlength="20" value="xxxxxx" name="passconf" onBlur="password_blur(this)" onFocus="password_focus(this)" >';
	}
	
	function callback_before_update($post_array)
	{
		
		if($post_array['password'] == "xxxxxx" )
	    {
	        unset($post_array['password']);
	    }
	    else
	    {	    
	    	// Hash password using phpass
			$hasher = new PasswordHash(
					$this->config->item('phpass_hash_strength', 'tank_auth'),
					$this->config->item('phpass_hash_portable', 'tank_auth'));
			$post_array['password'] = $hasher->HashPassword($post_array['password']);
	    
	    }	    
	    if($this->session->perfil != 1 && isset($post_array['perfil']) && $post_array['perfil'] == 1)
	    {
	        $post_array['perfil'] = null;
	    }
	    if($this->session->perfil > 2 && isset($post_array['perfil']) && $post_array['perfil'] <= 2)
	    {
	        $post_array['perfil'] = null;
	    }
	    
	    unset($post_array['passconf']);
	    unset($post_array['password_before']);
	    unset($post_array['username']);
	    
	    return $post_array;
	}
	
	function meus_dados()
	{			
		try{
		    $this->ini_method('index',NULL,TRUE);
		    
			$crud = new grocery_CRUD();

			//$this->valida_acoes($crud);
			
			$crud->set_theme('bootstrap');
			$crud->set_table('sys_users');
			$crud->set_subject('Usuário do Painel');
			$crud->unset_read();
			$crud->unset_print();
			$crud->unset_export();
			$crud->unset_delete();
			$crud->unset_read();
			
			$perfil = $this->session->userdata('perfil');
			$user_id = $this->session->userdata('user_id');
			$stateInfo = $crud->getStateInfo();
			$state = $crud->getState();
			
			if (!($state == 'edit' ||  $state == 'update' || $state == 'update_validation' ))
		    {
		        redirect('sistema/usuarios/meus_dados/edit/'.$user_id);
		    }
			if (!isset($stateInfo->primary_key) || $stateInfo->primary_key != $user_id )
			{
				redirect('sistema/usuarios/meus_dados/edit/'.$user_id);
			}
		    $crud->unset_back_to_list();
			
			if($perfil != 1)
			{
				$crud->where('sys_users.perfil != ','1');
				if (isset($stateInfo->primary_key) && $this->get_perfil_user($stateInfo->primary_key) == 1)
					header("Location: javascript:history.back(1)");
			}
			
			if($state == 'insert_validation')
			{			
				$crud->set_rules('username', 'Username', 'trim|required|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|callback_username_check');
			}
			
			Assets::add_module_js('sistema',array(
				'usuario.js'
		    ));
			
			$this->config_perfil_edit($crud);
			
			$this->display_usuarios($crud);
			
			$output = $crud->render();
			
			$this->_example_output($output);
			
		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}
	
}