<?php

namespace App\Controllers;
use App\Models\UsuarioModel;
use App\Models\SedeModel;    
use App\Models\RolModel;    


class Usuario extends BaseController
{

   private $sede;
   private $usuario;
   protected $reglas;
   protected $roles;
   protected $sesion;

    public function __construct()
    {
        $this->sede = new SedeModel();
        $this->usuario = new UsuarioModel();
        $this->roles = new RolModel();
		$this->sesion = session();

        helper(['form']);

			$this->reglas = [

				'id_usuario' =>[
					'rules' => 'required|is_unique[usuario.id_usuario]',
					'errors' => [
						'required' => 'El campo {field} es obligatorio.',
						'is_unique' => 'El campo Usuario ya existe.'
						]
			],
				'clave' =>[
					'rules' => 'required',
					'errors' => [
						'required' => 'El campo password es obligatorio.'
						]
			],
				'confirmar' =>[
					'rules' => 'required|matches[clave]',
					'errors' => [
						'required' => 'El campo {field} es obligatorio.',
						'matches' => 'Las contraseñas no coinciden.'
						]
			],
				'nombres' =>[
					'rules' => 'required',
					'errors' => [
						'required' => 'El campo {field} es obligatorio.'
						]
			]
		 ];
		 	$this->reglasLogin = [
				'usuario' =>[
					'rules' => 'required',
					'errors' => [
						'required' => 'El campo {field} es obligatorio.'
						]
			],
				'clave' =>[
					'rules' => 'required',
					'errors' => [
						'required' => 'El campo {field} es obligatorio.'
						]
			]
				];
    }
    
    public function index()
    {
		if($this->sesion->get('nivel')==1){
        $sede = $this->sede->findAll();
        $rol = $this->roles->findAll();
        $data = ['sede' => $sede,'roles'=>$rol];
        return view('template/header').
         view('main/usuario', $data);
    }
	else
		return redirect()->to(base_url());
        
    
	}
   



public function registrar()
		{

			if ($this->request->getMethod() == "POST" && $this->validate($this->reglas)) {

				$this->usuario->save([
					
				'id_usuario' 	=> UppercaseWords($this->request->getPost('id_usuario')),
                'nombres'    	=> UppercaseWords($this->request->getPost('nombres')),
                'password'   	=> password_hash($this->request->getPost('clave'), PASSWORD_DEFAULT),
				'nivel'   		=> $this->request->getPost('roles'),
                'id_sede'    	=> $this->request->getPost('sede')]);



				return redirect()->to(base_url() . 'admin/usuarios')
                 ->with('success', 'Usuario registrado correctamente');

				 

				
			} else {
                
            /*return redirect()->to(base_url() . 'usuario')
                 ->with('errors', $this->validator);*/

				 $sede = $this->sede->findAll();
				 $roles = $this->roles->findAll();
        		$data = [	'sede' => $sede,
							'roles'=>$roles,
							'error'=>'No se pudo agregar Usuario',
                			'validation'=>$this->validator];

        return 	view('template/header').
         		view('main/usuario', $data);

			}

		}

			public function valida()
		{
			if ($this->request->getMethod() == "POST" && $this->validate($this->reglasLogin)){
					$usuario = UppercaseWords($this->request->getPost('usuario'));
					$password = $this->request->getPost('clave');

					$datosUsuario = $this->usuario->where('id_usuario', $usuario)->first();
					if ($datosUsuario != null) {
						if (password_verify($password, $datosUsuario['password'])) {
							$datosSesion = [
								'id_usuario' 	=> $datosUsuario['id_usuario'],
								'nombres' 		=> $datosUsuario['nombres'],
								'id_sede' 		=> $datosUsuario['id_sede'],
								'nivel' 		=> $datosUsuario['nivel'],
								'activo' 		=> 1
							];
							$this->sesion = session();
							$this->sesion->set($datosSesion);
							return redirect()->to(base_url());
							}else{
							$data['error'] = "Las contraseñas no coinciden";
							echo view('main/login',$data);
						}	
					} else {
						$data['error'] = "El usuario no existe";
						echo view('main/login', $data);
					}
					
			}else{
				$data=['validation' => $this->validator];
				echo view('main/login',$data);
			}
		}
}