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

class Users extends Admin_Controller {

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

        /* Load :: Common */
        $this->lang->load('admin/users');

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

        /* Breadcrumbs :: Common */
        $this->breadcrumbs->unshift(1, lang('menu_users'), 'admin/users');
    }


	public function index()
	{
	// $_SESSION['inicio'] ++;
	// unset($_SESSION['csrfkey']);
	//	$_SESSION['ingresa_get_csrf_nonce']		= 0; 
	//	$_SESSION['ingresa_valid_csrf_nonce']	= 0; 
	//	$_SESSION['ingresa_set_flashdata']		= 0; 
	//	$_SESSION['ingresa_set_userdata']		= 0; 
	//	$_SESSION['mark_as_flash']				= 0;  
        if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
        {
            redirect('auth/login', 'refresh');
        }
        else
        {
            /* Breadcrumbs */
            $this->data['breadcrumb'] = $this->breadcrumbs->show();

            /* Get all users */
            $this->data['users'] = $this->ion_auth->users()->result();
            foreach ($this->data['users'] as $k => $user)
            {
                $this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
            }

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


	public function create()
	{
        /* Breadcrumbs */
        $this->breadcrumbs->unshift(2, lang('menu_users_create'), 'admin/users/create');
        $this->data['breadcrumb'] = $this->breadcrumbs->show();

        /* Variables */
		$tables = $this->config->item('tables', 'ion_auth');

		/* Validate form input */
		$this->form_validation->set_rules('nick', 				'lang:nick', 					'required');
		$this->form_validation->set_rules('first_name', 		'lang:users_firstname', 		'required');
		$this->form_validation->set_rules('last_name', 			'lang:users_lastname', 			'required');
		$this->form_validation->set_rules('email', 				'lang:users_email', 			'required|valid_email|is_unique['.$tables['users'].'.email]');
		$this->form_validation->set_rules('phone', 				'lang:users_phone', 			'required');
		$this->form_validation->set_rules('company', 			'lang:users_company', 			'required');
		$this->form_validation->set_rules('password', 			'lang:users_password', 			'required|min_length[' . 
					$this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . 
					$this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]'
				);
		$this->form_validation->set_rules('password_confirm', 	'lang:users_password_confirm', 	'required');

		if ($this->form_validation->run() == TRUE)
		{
			$nick 		= $this->input->post('nick');
			$email    	= strtolower($this->input->post('email'));
			$password 	= $this->input->post('password');

			$additional_data = array( 
				'email' 		=> $this->input->post('email'		),
				'first_name' 	=> $this->input->post('first_name'	),
				'last_name'  	=> $this->input->post('last_name'	),
				'company'    	=> $this->input->post('company'		),
				'phone'      	=> $this->input->post('phone'		) 
			);
		}

		if ($this->form_validation->run() == TRUE && $this->ion_auth->register($nick, $password, $additional_data))
		{
            $this->session->set_flashdata('message', $this->ion_auth->messages());
			redirect('admin/users', 'refresh');
		}
		else
		{
            $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
            //$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue'))
			$this->data['key1'] = array(
				'class' => 'form-control',
				'value' => $this->input->post($this->session->flashdata('csrfkey')),
			);
			$this->data['key2'] = array(
				'class' => 'form-control',
				'value' => $this->session->flashdata('csrfvalue'),
			);

			$this->data['nick'] = array(
				'name'  => 'nick',
				'id'    => 'nick',
				'type'  => 'text',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('nick'),
			);
			$this->data['first_name'] = array(
				'name'  => 'first_name',
				'id'    => 'first_name',
				'type'  => 'text',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('first_name'),
			);
			$this->data['last_name'] = array(
				'name'  => 'last_name',
				'id'    => 'last_name',
				'type'  => 'text',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('last_name'),
			);
			$this->data['email'] = array(
				'name'  => 'email',
				'id'    => 'email',
				'type'  => 'email',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('email'),
			);
			$this->data['company'] = array(
				'name'  => 'company',
				'id'    => 'company',
				'type'  => 'text',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('company'),
			);
			$this->data['phone'] = array(
				'name'  => 'phone',
				'id'    => 'phone',
				'type'  => 'tel',
                'pattern' => '^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('phone'),
			);
			$this->data['password'] = array(
				'name'  => 'password',
				'id'    => 'password',
				'type'  => 'password',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('password'),
			);
			$this->data['password_confirm'] = array(
				'name'  => 'password_confirm',
				'id'    => 'password_confirm',
				'type'  => 'password',
                'class' => 'form-control',
				'value' => $this->form_validation->set_value('password_confirm'),
			);

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


	public function delete()
	{
        /* Load Template */
		$this->template->admin_render('admin/users/delete', $this->data);
	}

	 /** Funcion edit
		 recibe el ID embebido en la funcion uri_string() **/
	public function edit($id)
	{
        $id = (int) $id;


		if ( ! $this->ion_auth->logged_in() OR ( ! $this->ion_auth->is_admin() && ! ($this->ion_auth->user()->row()->id == $id)))
		{
			redirect('auth', 'refresh');
		}

        /* Breadcrumbs */
        $this->breadcrumbs->unshift(2, lang('menu_users_edit'), 'admin/users/edit');
        $this->data['breadcrumb'] = $this->breadcrumbs->show();

        /* Data */
		$user          = $this->ion_auth->user($id)->row();
		$groups        = $this->ion_auth->groups()->result_array();
		$currentGroups = $this->ion_auth->get_users_groups($id)->result();

		/* Validate form input */
		$this->form_validation->set_rules('nick'		, 'lang:edit_user_validation_nick_label'		, 'required');
		$this->form_validation->set_rules('first_name'	, 'lang:edit_user_validation_fname_label'		, 'required');
		$this->form_validation->set_rules('last_name'	, 'lang:edit_user_validation_lname_label'		, 'required');
		$this->form_validation->set_rules('email'		, 'lang:edit_user_validation_email'				, 'required');
		$this->form_validation->set_rules('phone'		, 'lang:edit_user_validation_phone_label'		, 'required');
		$this->form_validation->set_rules('company'		, 'lang:edit_user_validation_company_label'		, 'required');

		

		/* Verificar si vienen datos por POST --------------------------------------------------------------------------------------*/
		if (isset($_POST) && ! empty($_POST))
		{
				 //$id = $this->input->post('id');
	 			/* Comprobar si tenemos una solicitud valida csrf */
 				
//	 		$aux = ' this->_valid_csrf_nonce '.$this->_valid_csrf_nonce().' - <br>session_bandera_csrf: '.$_SESSION['bandera_csrf'];
//	 		show_error( $aux );

			if ($this->_valid_csrf_nonce() === FALSE OR $id != $this->input->post('id'))
			{
				show_error($this->lang->line('error_csrf'));
			}

            if ($this->input->post('password'))
			{
				$this->form_validation->set_rules('password', 			
										$this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . 
										$this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . 
										$this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');

				$this->form_validation->set_rules('password_confirm',
										$this->lang->line('edit_user_validation_password_confirm_label'), 'required');
			}

			/* Validar que el formulario no tenga errores de requerimientos */
			if ($this->form_validation->run() == TRUE)
			{
				/* Cargar datos para ser enviados */
				$data = array( 
					'nick' 			=> $this->input->post('nick'),
					'first_name' 	=> $this->input->post('first_name'),
					'last_name'  	=> $this->input->post('last_name'),
					'email'  		=> $this->input->post('email'),
					'company'    	=> $this->input->post('company'),
					'phone'      	=> $this->input->post('phone'),
				);

				// Guarda la contraseña solo en caso de que tenga modificacion, sino, deja la contraseña anterior.
                if ($this->input->post('password'))
				{
					$data['password'] = $this->input->post('password');
				}

				/* Comprueba que el usuario este autorizado para el proceso */
                if ($this->ion_auth->is_admin())
				{
                    $groupData = $this->input->post('groups');

					if (isset($groupData) && !empty($groupData))
					{
						$this->ion_auth->remove_from_group('', $id);

						foreach ($groupData as $grp)
						{
							$this->ion_auth->add_to_group($grp, $id);
						}
					}
				}

				/* Aqui se procesa la actualizacion. */

 
				if($this->ion_auth->update($user->id, $data)) // Aqui se procesa la actualizacion. 
				{
					$this->session->set_flashdata('message', $this->ion_auth->messages());

					if ($this->ion_auth->is_admin())
					{
						redirect('admin/users', 'refresh');
					}
					else
					{
						redirect('admin', 'refresh');
					}
				}else{
					$this->session->set_flashdata('message', $this->ion_auth->errors());

				    if ($this->ion_auth->is_admin())
					{
						redirect('auth', 'refresh');
					}
					else
					{
						redirect('/', 'refresh');
					}
			    }
			} // fin form_validation
		}else{

//	 	 	$_SESSION['bandera_csrf'] = 0;

			$this->data['csrf'] 						= $this->_get_csrf_nonce();
			
//			$this->data['array_csrf'] 					= $this->_get_csrf_nonce();

			/*  Mostrar el formulario de edición de usuario. Validar CSRF */
//			$this->data['flashdata_mostrarkey'] 		= $this->session->flashdata('csrfkey');
//			$this->data['flashdata_mostrarkeyValue'] 	= $this->session->flashdata('csrfvalue');
 
		}
		
		/*  Establecer el mensaje de error de datos flash si hay uno */
		$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

		/* Pasar el usuario a la vista */
		$this->data['user']          = $user;
		$this->data['groups']        = $groups;
		$this->data['currentGroups'] = $currentGroups;

		/* 
		Propiedades de los inputs que se pasan por 
		$DATA al formulario en la vista view
		*/
		$this->data['nick'] 			= array(
			'name'  => 'nick',
			'id'    => 'nick',
			'type'  => 'text',
			'class' => 'form-control',
			'value' => $this->form_validation->set_value('nick', $user->nick));
		$this->data['first_name'] 		= array(
			'name'  => 'first_name',
			'id'    => 'first_name',
			'type'  => 'text',
			'class' => 'form-control',
			'value' => $this->form_validation->set_value('first_name', $user->first_name));
		$this->data['last_name'] 		= array(
			'name'  => 'last_name',
			'id'    => 'last_name',
			'type'  => 'text',
			'class' => 'form-control',
			'value' => $this->form_validation->set_value('last_name', $user->last_name));
		$this->data['company'] 			= array(
			'name'  => 'company',
			'id'    => 'company',
			'type'  => 'text',
			'class' => 'form-control',
			'value' => $this->form_validation->set_value('company', $user->company));
		$this->data['email'] 			= array(
			'name'  => 'email',
			'id'    => 'email',
			'type'  => 'text',
			'class' => 'form-control',
			'value' => $this->form_validation->set_value('email', $user->email));
		$this->data['phone'] 			= array(
			'name'  => 'phone',
			'id'    => 'phone',
            'type'  => 'tel',
            'pattern' => '^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$',
            'class' => 'form-control',
			'value' => $this->form_validation->set_value('phone', $user->phone));
		$this->data['password'] 		= array(
			'name' => 'password',
			'id'   => 'password',
            'class' => 'form-control',
			'type' => 'password');
		$this->data['password_confirm'] = array(
			'name' => 'password_confirm',
			'id'   => 'password_confirm',
            'class' => 'form-control',
			'type' => 'password');

        /* Cargar/dibujar la plantilla en pantalla a traves del metodo de admin_render */
		$this->template->admin_render('admin/users/edit', $this->data);
	}


	function activate($id, $code = FALSE)
	{
        $id = (int) $id;

		if ($code !== FALSE)
		{
            $activation = $this->ion_auth->activate($id, $code);
		}
		else if ($this->ion_auth->is_admin())
		{
			$activation = $this->ion_auth->activate($id);
		}

		if ($activation)
		{
            $this->session->set_flashdata('message', $this->ion_auth->messages());
			redirect('admin/users', 'refresh');
		}
		else
		{
			$this->session->set_flashdata('message', $this->ion_auth->errors());
			redirect('auth/forgot_password', 'refresh');
		}
	}


	public function deactivate($id = NULL)
	{
		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
		{
            return show_error('You must be an administrator to view this page.');
		}

        /* Breadcrumbs */
        $this->breadcrumbs->unshift(2, lang('menu_users_deactivate'), 'admin/users/deactivate');
        $this->data['breadcrumb'] = $this->breadcrumbs->show();

		/* Validate form input */
		$this->form_validation->set_rules('confirm', 'lang:deactivate_validation_confirm_label', 'required');
		$this->form_validation->set_rules('id', 'lang:deactivate_validation_user_id_label', 'required|alpha_numeric');

		$id = (int) $id;

		if ($this->form_validation->run() === FALSE)
		{
			$user = $this->ion_auth->user($id)->row();

            $this->data['csrf']       = $this->_get_csrf_nonce();
            $this->data['id']         = (int) $user->id;
            $this->data['firstname']  = ! empty($user->first_name) ? htmlspecialchars($user->first_name, ENT_QUOTES, 'UTF-8') : NULL;
            $this->data['lastname']   = ! empty($user->last_name) ? ' '.htmlspecialchars($user->last_name, ENT_QUOTES, 'UTF-8') : NULL;

            /* Load Template */
            $this->template->admin_render('admin/users/deactivate', $this->data);
		}
		else
		{
            if ($this->input->post('confirm') == 'yes')
			{
                if ($this->_valid_csrf_nonce() === FALSE OR $id != $this->input->post('id'))
				{
                    show_error($this->lang->line('error_csrf'));
				}

                if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
				{
					$this->ion_auth->deactivate($id);
				}
			}

			redirect('admin/users', 'refresh');
		}
	}


	public function profile($id)
	{
        /* Breadcrumbs */
        $this->breadcrumbs->unshift(2, lang('menu_users_profile'), 'admin/groups/profile');
        $this->data['breadcrumb'] = $this->breadcrumbs->show();

        /* Data */
        $id = (int) $id;

        $this->data['user_info'] = $this->ion_auth->user($id)->result();
        foreach ($this->data['user_info'] as $k => $user)
        {
            $this->data['user_info'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
        }

        /* Load Template */
		$this->template->admin_render('admin/users/profile', $this->data);
	}









	public function _get_csrf_nonce()
	{
// 		if ($_SESSION['bandera_csrf'] == 0 && !isset($_SESSION['csrfkey']))
// 		{
			$this->load->helper('string');
			$key   = random_string('alnum', 8);
			$value = random_string('alnum', 20);
			$this->session->set_flashdata('csrfkey', 	$key);
			$this->session->set_flashdata('csrfvalue', 	$value);

//			$_SESSION['csrfkey']		=	$key 	;
//			$_SESSION['csrfvalue']		=	$value	;
//
//			$_SESSION['bandera_csrf'] ++;
//			$_SESSION['ingresa_get_csrf_nonce']++; 

			return array($key => $value);
// 		}
// 		if (isset($_SESSION['csrfkey']) )
// 		{
// 	 		return array($_SESSION['csrfkey']=>$_SESSION['csrfvalue']);
// 		}else{
// 			return "super error";
// 		}

 	 	//return array(flashdata('csrfkey')=>flashdata('csrfvalue'));
	}







	public function _valid_csrf_nonce()
	{
//		$_SESSION['ingresa_valid_csrf_nonce']++;
// 				// return $this->input->post($this->session->flashdata('csrfkey'));
// 			 	$cad =	'$this->input->post($this->session->flashdata(csrfkey)): '.	$this->input->post($this->session->flashdata('csrfkey')).
// 						'<br> $this->_SESSION(csrfkey): '.							$_SESSION['csrfkey'] .
// 						'<br> $this->_SESSION(csrfvalue): '.						$_SESSION['csrfvalue'] .
// 						'<br> $this->session->flashdata(csrfkey): '.				$this->session->flashdata('csrfkey') .
// 						'<br> $this->session->flashdata(csrfvalue): '.				$this->session->flashdata('csrfvalue');
// 		$cad .= "<table>";
// 		    foreach ($_POST as $key => $value) {
// 		        $cad .= "<tr>";
// 		        $cad .= "<td>";
// 		        $cad .= $key;
// 		        $cad .= "</td>";
// 		        $cad .= "<td>";
// 		        $cad .= $value;
// 		        $cad .= "</td>";
// 		        $cad .= "</tr>";
// 		    }
// 		$cad .= "</table>";
//
//
//						$cad .=	  '<br> $_SESSION[bandera_csrf] '. 					$_SESSION['bandera_csrf'];					 
//						$cad .=	  '<br> $_SESSION[ingresa_get_csrf_nonce] '. 		$_SESSION['ingresa_get_csrf_nonce'];			 
//						$cad .=	  '<br> $_SESSION[ingresa_valid_csrf_nonce] '. 		$_SESSION['ingresa_valid_csrf_nonce'];		 
//					//	$cad .=	  '<br> $_SESSION[ingresa_set_flashdata] '. 		$_SESSION['ingresa_set_flashdata'];			 
//					//	$cad .=	  '<br> $_SESSION[ingresa_set_userdata] '. 			$_SESSION['ingresa_set_userdata'];			 
//					//	$cad .=	  '<br> $_SESSION[mark_as_flash] '. 				$_SESSION['mark_as_flash']	;				 
//						$cad .=	  '<br> $_SESSION[inicio] '. 						$_SESSION['inicio']	;				 

		
 			if (
 				$this->input->post($this->session->flashdata('csrfkey')) !== FALSE 
 			//	 && 
 			//	$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')
 				)
 			{



//			if (
//				$this->input->post($_SESSION['csrfkey']) !== FALSE  && 
//				$this->input->post($_SESSION['csrfkey']) == $_SESSION['csrfvalue'] 
//				)
//			{
				return TRUE;
				//return 'verdadero: '.$cad;
			}
			else
			{
				return FALSE;
				//return ' es falso: '.$cad;
			}

		//return " no entro en nada ". $cad;
	}
	 
}
