<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\AuthModel;


class Auth extends BaseController
{
    //public string $key = '4d8b6e02f5a8d2a83c1e2bc3ff7a3aa7';
                //echo '<pre>';
                //print_r($username.'_si');
                //echo '</pre>';                

    public function login()
    {
        if ($this->request->getMethod() === 'POST') {
            
            $username = $this->request->getPost('cuentalogin');
            $password = $this->request->getPost('clave');
            $this->AuthModel = new AuthModel();
            $resultadoLogin = $this->AuthModel->buscarUsuarioUsuario('admin');
            
            /*
            echo "<PRE> Username original: $username<br>";
            echo "Username original: $username<br>";
            echo "Coduser limpio: $password<br>";
            */
    
        	if (filter_var($username, FILTER_VALIDATE_EMAIL))
            {
            	$email = filter_var($username, FILTER_SANITIZE_EMAIL);
                $this->UserModel = new UserModel();
            	$resultadoLogin = $this->AuthModel->buscarUsuarioMail($email);
        	}else{
            	$coduser = preg_replace("/[^a-zA-Z0-9.-]/", "", $username);
                $this->AuthModel = new AuthModel();
            	$resultadoLogin = $this->AuthModel->buscarUsuarioUsuario($coduser);
                /*
                echo('<PRE>');
                echo($coduser);
                echo($password);
                echo('</PRE>');
                */
            }
            
            //ESte codigo comentado es para obtener  el passwprd desencriptado de un usuario
            //app/Config/Encryption.php
            //$encrypter = \Config\Services::encrypter();
    		//$claveDB = $encrypter->decrypt(hex2bin($password));
    		//$clave = $this->request->getPost("clave");

        	if($resultadoLogin){
            	$encrypter = \Config\Services::encrypter();
        		$claveDB = $encrypter->decrypt(hex2bin($resultadoLogin->password_hash));
        		$clave = $this->request->getPost("clave");
            	//echo($claveDB);
            	//echo($clave);
                //echo('</PRE>');
        		if($clave == $claveDB){
                    /*
                	$data = [
                    	"nombreUsuario" => $resultadoLogin->nombre.' '.$resultadoLogin->apellido,
                    	"emailUsuario" => $resultadoLogin->email,
                        "logged_in" => true,
                        "username" => $username,
                        "group_id" => 1
                    	//"fotoUsuario" => $resultadoLogin->foto
                	];
                	*/		
                    $db = \Config\Database::connect();
                    $query = $db->query("SELECT pg_backend_pid() AS pid");
                    $row = $query->getRow();
                    $pgBackendPid = $row->pid;
                    
                    $ip = $this->request->getIPAddress();
                    $userAgent = $this->request->getUserAgent();

                    $data = [
                        'user_id'       => $resultadoLogin->id, // de tu sistema
                        'username'      => $username,
                        'login_time'    => date('Y-m-d H:i:s'),
                        'ip_address'    => $ip,
                        'user_agent'    => $userAgent,
                        'sesion'        => $pgBackendPid,
                        'success'       => true,
                    	'nombreUsuario' => $resultadoLogin->nombre.' '.$resultadoLogin->apellido,
                    	'emailUsuario'  => $resultadoLogin->email,
                        'logged_in'     => true,
                        'group_id'      => 1
                    	//"fotoUsuario" => $resultadoLogin->foto
                    ];
                    
                    
                   $login_attempts = [
                        'user_id'       => $resultadoLogin->id, // de tu sistema
                        'username'      => $username,
                        'login_time'    => date('Y-m-d H:i:s'),
                        'ip_address'    => $ip,
                        'user_agent'    => $userAgent,
                        'sesion'        => $pgBackendPid,
                        'success'       => true,
                    ];
                    
                    session()->set($data);
                    
                    $db->table('audit.login_attempts')->insert($login_attempts);                    
                    
                    
                	return redirect()->to('dashboard');
                }else{
                	$data = ['tipo' => 'danger', 'mensaje' => 'Clave incorrecta!'];
                	return view('auth/login',$data);
                }
            }else{
            	$data = ['tipo' => 'danger', 'mensaje' => 'Usuario incorrecto o inactivo!'];
            	return view('auth/login',$data);
            } 

            return redirect()->back()->with('error', 'Usuario o contraseña incorrectos.');
        }
        return view('auth/login');
    }
    
    

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login');
    }
    
   	public function cerrarSesion(){
    	session()->destroy();
    	//return redirect()->to(base_url());
    	return redirect()->to('/login');
    }


    public function obtenerClaveEncriptada()
    {
        //Codigo para obtener una clave para poder acctualizar la tabla de usuarios
		$encrypter = \Config\Services::encrypter();
    	$clave = bin2hex($encrypter->encrypt('Sigapas2025bo'));
        echo $clave;    
    } 
    
    
    
}