<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    require_once "webService/funciones.php";
    require_once "funciones/misFunciones.php";
    
    class Contrasena extends CI_Controller {
        
        public function __construct()
        {
            parent::__construct();
            
            //$this->set_js_lib($this->default_javascript_path.'../assets/grocery_crud/js/jquery_plugins/jquery.noty.js');
            
            $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->database();
            $this->load->helper('url');
            $this->load->library(array('session'));
            $this->load->helper(array('url'));
            $this->load->helper('security');
            
            $this->load->model('login_model');
            $this->load->library(array('session','form_validation'));
            
            $this->load->library('grocery_CRUD');
            
            
            $this->ci =& get_instance();
            $this->config->set_item('language', 'spanish');
        }
        
        public function index()
        {
            $this->_example_output((object)array('output' => ''));
        }
        
        public function _example_output($output = null, $titulo='', $view='contrasena.php')
        {
            $output = integraEstilos($output, $titulo);
            $objeto = $this->ci->load->view($view, $output, TRUE);
            
            $data = array('output' => $objeto);
            $data = integraEstilos($data, $titulo);
            
            $this->load->view('plantillaSinMenuContainer12',$data);            
        }
        
        function callback_after_upload($uploader_response,$field_info, $files_to_upload)
        {
            $this->load->library('image_moo');
            
            //Is only one file uploaded so it ok to use it with $uploader_response[0].
            $file_uploaded = $field_info->upload_path.'/'.$uploader_response[0]->name;
            
            $this->image_moo->load($file_uploaded)->resize(800,600)->save($file_uploaded,true);
            
            return true;
        }
        
        public function restableceContrasena()
        {
            $data['usuario'] = $this->input->get('usuario');
            $data['guid'] = $this->input->get('guid');
            $this->_example_output($data, 'Reestablecer contraseña');
        }

        public function solicitarContrasena()
        {
            $data['usuario'] = $this->input->get('usuario');
            $data['guid'] = $this->input->get('guid');
            $this->_example_output($data, 'Recuperar contraseña', 'solicitarContrasena.php');
        }

        public function solicitaContrasena()
        {
            $this->form_validation->set_rules('correo', 'correo electrónico', 'required|trim|min_length[2]|max_length[150]|valid_email');
            if ($this->form_validation->run() == FALSE)
            {
                $this->_example_output(null, 'Recuperar contraseña', 'solicitarContrasena.php');
            }
            else
            {
                $usuario = $this->input->post('correo');
                if ($this->login_model->existeLogin($usuario))
                {
                    $guid = $this->login_model->guid();
                    $guid = str_replace("{", "", $guid);
                    $guid = str_replace("}", "", $guid);
                    
                    $this->login_model->estableceGUID($usuario,$guid);
                    
                    //enviar correo con instrucciones.
                    $to      = $usuario;
                    $subject = 'Restablecer contraseña';
                    $message = 'Recientemente se ha solicitado restablecer la contraseña, si usted originó esta acción siga el siguiente enlace, caso contrario deseche este correo:<br /><br />' .
                    "<a href=\"". base_url(). "index.php/contrasena/restableceContrasena?usuario=$usuario&guid=$guid\">". base_url(). "index.php/contrasena/restableceContrasena?usuario=$usuario&guid=$guid</a>";
                    $headers = 'From: webmaster@no-reply.com' . "\r\n" .
                    'Reply-To: webmaster@no-reply.com' . "\r\n" .
                    'X-Mailer: PHP/' . phpversion() . "\r\n" .
                    'Content-Type: text/html; charset=UTF-8\r\n';
                    if (mail($to, $subject, $message, $headers))
                    {
                        //$this->session->set_flashdata('usuario_incorrecto',base_url(). "index.php/contrasena/restableceContrasena?usuario=$usuario&guid=$guid");
                        $this->session->set_flashdata('notySuccess','Se ha enviado a su correo un link para reestablecer su contraseña');
                        redirect(base_url().'login');
                        
                    }
                    else
                    {
                        $this->session->set_flashdata('notyError','El correo no ha podido ser enviado');
                        $this->_example_output(null, 'Recuperar contraseña', 'solicitarContrasena.php');
                    }
                }
                else
                {
                    $this->session->set_flashdata('notyError','El correo especificado no parece ser el de un usuario registrado');
                    $this->_example_output(null, 'Recuperar contraseña', 'solicitarContrasena.php');
                }
            }
        }
        
        
        
        public function nuevaContrasena()
        {
            $this->form_validation->set_rules('contrasena', 'Contraseña', 'required|trim|min_length[5]|max_length[150]|xss_clean');
            $this->form_validation->set_rules('recontrasena', 'Repetir contraseña', 'required|trim|min_length[5]|max_length[150]|xss_clean|matches[contrasena]');
            if ($this->form_validation->run() == FALSE)
            {
                $data['usuario'] = $this->input->post('usuario');
                $data['guid'] = $this->input->post('guid');
                $this->_example_output($data, 'Reestablecer contraseña');
            }
            else
            {
                $usuario = $this->input->post('usuario');
                $guid = $this->input->post('guid');
                $contrasena = md5($this->input->post('contrasena'));
                
                if ($this->login_model->permiteCambiarContrasena($usuario,$guid))
                {
                    $this->login_model->actualiza_login($usuario,$contrasena);
                    $this->session->set_flashdata('notySuccess','¡La contraseña se ha cambiado con éxito!');
                    redirect(base_url().'login');
                }
                else
                {
                    $this->session->set_flashdata('notyError','El correo para cambio de contraseña ha caducado u operación no autorizada');
                    $data['usuario'] = $this->input->post('usuario');
                    $data['guid'] = $this->input->post('guid');
                    $data['usuario'] = $this->input->post('usuario');
                    $data['guid'] = $this->input->post('guid');
                    $this->_example_output($data, 'Reestablecer contraseña');
                }
            }
        }
        
        
    }
