<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Carbon;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use Exception;

class LoginController extends Controller{
    private $responseController;
    private $encryptionController;
    private $functionsController;
    private $secretKey = "ydl27x22cNsNY0z6o3Fr6XZoUvsX0QMZx6MaiwN+KCnM6APS4Xbb7GDfudOYD5uD/r8TzQElh4d4HIal5Os0XA==";
    private $publicKey = "zOgD0uF22+xg37nTmA+bg/6/E80BJYeHeByGpeTrNFw=";

    public function __construct(){
        $this->responseController = new ResponseController();
        $this->encryptionController = new EncryptionController();
        $this->functionsController = new FunctionsController;
    }

    public function login(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email',
            'password' => 'required|string',
            'linea' => 'required|integer|max: 2',
            'lugarConexion' => "required|json"
        ]);

        if($validator->fails()){
            return $this->responseController->makeResponse(
                true,
                "Se encontraron uno o más errores.",
                $this->responseController->makeErrors(
                    $validator->errors()->messages()
                ),
                401
            );
        }

        $login = $request->all();
        $usr = DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $login['email'])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, "El correo electrónico no está registrado.", [], 404);
        }else if($usr->USUA_ESTA != 'Activo'){
            $statusStr = strtolower($usr->USUA_ESTA);
            return $this->responseController->makeResponse(true, "El usuario se encuentra $statusStr, por favor contacte al administrador para solucionarlo.", [], 401);
        }
        
        $now = Carbon::now('America/Mexico_city');
        $nowStr = $now->toDateTimeString();

        $contra = $login['password'];
        $contra = $this->encryptionController->decrypt($contra);
        if(!$contra){
            return $this->responseController->makeResponse(true, 'La contraseña no fue encriptada correctamente.', [], 400);
        }
        $usrContra = $usr->USUA_CONT;
        if(!Hash::check($contra, $usrContra)){
            $attempts = $usr->USUA_ININ + 1;
            $status = $attempts >= 10 ? 'Inactivo' : 'Activo';

            DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $usr->USUA_IDUS)->update([
                "USUA_ININ" => $attempts,
                "USUA_ESTA" => $status
            ]);

            return $this->responseController->makeResponse(true, "La contraseña es incorrecta, intento $attempts de 10.", [], 401);
        }

        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $usr->USUA_IDUS)->update([
            "USUA_ININ" => 0,
            "USUA_ESTA" => 'Activo'
        ]);

        $iat = $now->timestamp;
        $cad = $now->addDay()->timestamp;
        $ipv = $request->ip();
        
        try{
            $ulco = DB::table('S002V01TBIAC')->insertGetId([
                'BIAC_NULI' => $login['linea'],
                'BIAC_IDUS' => $usr->USUA_IDUS,
                'BIAC_DIIP' => $ipv,
                'BIAC_LUCO' => $login['lugarConexion'],
                'BIAC_FECO' => $nowStr
            ]);
            DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $login['email'])->update(['USUA_ULCO' => $ulco]);
        }catch(PDOException $e){
            return $this->responseController->makeResponse(true, "Hubo un error al intentar actualizar la última conexión.", [], 500);
        }

        //Antes de crear el token revisamos los permisos de su perfil
        $profile = DB::table('S002V01TPERF')->where('PERF_IDPE', '=', $usr->USUA_PERF)->get()->first();
        $permissions = $this->encryptionController->encrypt($profile->PERF_PERM);

        $payload = [
            "iss" => $login['email'],
            "aud" => "dominio.syp.mx",
            "iat" => $iat,
            "cad" => $cad
        ];

        $token = JWT::encode($payload, $this->secretKey, 'EdDSA');

        //Antes de realizar el return obtenemos todas las acciones realizadas en la base de datos
        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $usr->USUA_IDUS, $nowStr, $login['linea']);

        return $this->responseController->makeResponse(false, "EXITO.", [
            "IDUSUARIO" => $this->encryptionController->encrypt($usr->USUA_IDUS),
            "NOMBREUSUARIO" => $this->encryptionController->encrypt($usr->USUA_NOMB),
            "CORREO" => $this->encryptionController->encrypt($usr->USUA_COEL),
            "PERMISOS" => $permissions,
            "TOKEN" => $token,
        ]);
    }

    public function verifyToken(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'token' => 'required|string',
        ]);

        if($validator->fails()){
            return $this->responseController->makeResponse(
                true,
                "Se encontraron uno o más errores.",
                $this->responseController->makeErrors(
                    $validator->errors()->messages()
                ),
                401
            );
        }

        $tokenInfo = $request->all();
        try{
            $decoded = JWT::decode($tokenInfo['token'], new Key($this->publicKey, 'EdDSA'));
        }catch(Exception $e){
            return $this->responseController->makeResponse(false, "Token inválido", [
                "validToken" => false
            ]);
        }

        $usr = DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $decoded->iss)->first();
        if(is_null($usr)){
            return $this->responseController->makeResponse(false, "El usuario que generó el token no está registrado en la base.", [
                "validToken" => false
            ]);
        }

        if($decoded->aud != "dominio.syp.mx"){
            return $this->responseController->makeResponse(false, "El token enviado fue generado en un sitio diferente.", [
                "validToken" => false
            ]);
        }

        $now = Carbon::now('America/Mexico_city')->timestamp;
        if($now > $decoded->cad){
            return $this->responseController->makeResponse(false, "Token expirado.", [
                "validToken" => false
            ]);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $usr->USUA_IDUS, $nowStr, 1);
        return $this->responseController->makeResponse(false, "Token válido.", [
            "validToken" => true
        ]);
    }

    public function createPasword(Request $request){
        $pass = $request->only('pass');
        $uuid = $this->functionsController->uuidv5('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'jose.b@ittec.mx');
        return $this->responseController->makeResponse(false, $uuid, []);
    }
}
