<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    require_once "funciones/misFunciones.php";
    
    class login extends CI_Controller
    {
        var $ci;
        
        public function __construct()
        {
            parent::__construct();
            
            $this->output->set_header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
            $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
            $this->output->set_header('Pragma: no-cache');
            $this->output->set_header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            
            $this->load->model('login_model');
            $this->load->library(array('session','form_validation'));
            $this->load->helper(array('url','form', 'email', 'security'));
            
            $this->load->database('default');
            
            $this->ci =& get_instance();
            $this->config->set_item('language', 'spanish');
        }
        
        public function index()
        {
            $data = $output = integraEstilos();
            switch ($this->session->userdata('perfil')) {
                case '':
                    $data['token'] = $this->token();
                    $objeto = $this->ci->load->view('login_view', $data, TRUE);
                    $data = array('output' => $objeto);
                    $data['titulo'] = 'Login con roles de usuario en codeigniter';
                    
                    $data = integraEstilos($data, 'Login de usuario');
                    
                    $this->load->view('plantillaSinMenuContainer12',$data);
                    break;
                case 'administrador':
                    redirect(base_url().'Main');
                    break;
                case 'user':
                    $data['token'] = $this->token();
                    $objeto = $this->ci->load->view('login_view', $data, TRUE);
                    
                    $data = array('output' => $objeto);
                    $data['titulo'] = 'Login con roles de usuario en codeigniter';
                    $data = integraEstilos($data, 'Login de usuario');
                    
                    $this->load->view('plantillaSinMenuContainer12',$data);
                    break;
                default:
                    $data['token'] = $this->token();
                    $objeto = $this->ci->load->view('login_view', $data, TRUE);
                    
                    $data = array('output' => $objeto);
                    $data['titulo'] = 'Login con roles de usuario en codeigniter';
                    $data = integraEstilos($data, 'Login de usuario');
                    
                    $this->load->view('plantillaSinMenuContainer12',$data);
                    break;
            }
        }
        
        public function new_user()
        {
            if($this->input->post('token') && $this->input->post('token') == $this->session->userdata('token'))
            {
                $this->form_validation->set_rules('correo', 'correo electrónico', 'required|trim|min_length[2]|max_length[150]|valid_email');
                $this->form_validation->set_rules('password', 'password', 'required|trim|min_length[5]|max_length[150]|xss_clean');
                //$this->form_validation->set_rules('correo', 'nombre de usuario', '|xss_clean');
                
                //lanzamos mensajes de error si es que los hay
                
                if($this->form_validation->run() == FALSE)
                {
                    $this->index();
                }else
                {
                    $username = $this->input->post('correo');
                    $password = md5($this->input->post('password'));
                    $check_user = $this->login_model->login_user($username,$password);
                    if($check_user == TRUE)
                    {
                        if ($check_user->supervisor == 1)
                        {
                            $data = array(
                                          'is_logued_in' 	=> 		TRUE,
                                          'id_usuario' 	=> 		$check_user->id,
                                          'perfil'		=>     ($check_user->supervisor == 1?'administrador':'user'),
                                          'correo' 		=> 		$check_user->correo,
                                          //Para chat
                                          'username'    => $check_user->nombre,
                                          'user_id'     => $check_user->id
                                          );
                            $this->session->set_userdata($data);
                            $this->index();
                        }
                        else
                        {
                            $this->session->set_flashdata('notyError','El usuario no tiene derechos suficientes para ingresar al sitio');
                            $this->index();
                            //redirect(base_url().'login');
                        }
                    }
                    else
                    {
                        $this->session->set_flashdata('notyError','La combinación correo-contraseña parece no ser válida.');
                        $this->index();
                    }
                }
            }else{
                $this->index();
            }
        }
        
        public function token()
        {
            $token = md5(uniqid(rand(),true));
            $this->session->set_userdata('token',$token);
            return $token;
        }
        
        public function logout_ci()
        {
            $this->session->sess_destroy();
            $data = array(
                          'is_logued_in' 	=> 		TRUE,
                          'id_usuario' 	=> 		'',
                          'perfil'		=>		'',
                          'correo' 		=> 	''
                          );
            $this->session->set_userdata($data);
            redirect(base_url().'login');
            //$this->index();
        }
    }
