<?php

namespace App\Http\Controllers;

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

class UsersProfilesController extends Controller{
    private $responseController;
    private $encryptionController;
    private $functionsController;

    public function __construct(){
        $this->responseController = new ResponseController();
        $this->encryptionController = new EncryptionController();
        $this->functionsController = new FunctionsController();
    }
    
    public function getUsers($idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }
        
        $users = DB::table('S002V01TUSUA')
        ->join('S002V01TPERF', 'USUA_PERF', '=', 'PERF_IDPE')
        ->leftJoin('S002V01TBIAC', 'USUA_ULCO', '=', 'BIAC_IDCO')
        ->select(
            'USUA_IDUS as IDUSUARIO',
            'USUA_NOMB as NOMBRE',
            'USUA_APPA as APEPAT',
            'USUA_APMA as APEMAT',
            'USUA_COEL as EMAIL',
            'PERF_NOPE as PERFIL',
            'USUA_ESTA as ESTATUS',
            'BIAC_FECO as ULCON'
        )->get()->all();
        
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $actions = DB::getQueryLog();

        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", $users);
    }

    public function getUser($id, $idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $id = $this->encryptionController->decrypt($id);
        if(!$id){
            return $this->responseController->makeResponse(true, "El id del usuario no está encriptado correctamente.", [], 400);
        }

        $user = DB::table('S002V01TUSUA')->select(
            'USUA_IDUS AS IDUSUARIO',
            'USUA_NOMB AS NOMBRE',
            'USUA_APPA AS APEPAT',
            'USUA_APMA AS APEMAT',
            'USUA_COEL AS EMAIL',
            'USUA_PERF AS PERFIL',
            'USUA_ESTA AS ESTATUS',
        )->where('USUA_IDUS', '=', $id)->get()->first();

        if(is_null($user)){
            return $this->responseController->makeResponse(true, "El usuario consultado no existe.", [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $actions = DB::getQueryLog();

        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", $user);
    }

    public function getProfiles($idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }
        
        $profiles = DB::table('S002V01TPERF')->select(
            'PERF_IDPE as IDPERFIL',
            'PERF_NOPE as NOMBREPERFIL',
            'PERF_ESTA as ESTATUS',
            'PERF_PERM as PERMISOS'
        )->get();

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $actions = DB::getQueryLog();
        
        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", $profiles);
    }

    public function getProfile($id, $idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $id = $this->encryptionController->decrypt($id);
        if(!$id){
            return $this->responseController->makeResponse(true, "El ID del perfil no está encriptado correctamente.", [], 401);
        }

        $profile = DB::table('S002V01TPERF')->select(
            'PERF_IDPE AS IDPERFIL',
            'PERF_NOPE AS NOMBREPERFIL',
            'PERF_ESTA AS ESTATUS',
            'PERF_PERM AS PERMISOS',
        )->where('PERF_IDPE', '=', $id)->first();

        if(is_null($profile)){
            return $this->responseController->makeResponse(true, "El perfil consultado no existe.", [], 404);
        }

        $profileInfo = json_decode($profile->PERMISOS, true);
        $permissions = [];
        //Se obtienen todos los modulos
        $modules = DB::table('S002V01TMODU')->get()->all();
        //se consultan los submodulos de cada modulo
        foreach($modules as $module){
            $submodules = DB::table('S002V01TSUBM')->where('SUBM_IDMO', '=', $module->MODU_IDMO)->get()->all();
            $permissionsPerSubmodule = [];
            foreach($submodules as $submodule){
                //Se consultan los menus
                $menus = DB::table('S002V01TMENU')->where([
                    ['MENU_IDMO', '=', $module->MODU_IDMO],
                    ['MENU_IDSM', '=', $submodule->SUBM_IDSM],
                ])->get()->all();

                $permissionsPerMenu = [];
                foreach($menus as $menu){
                    $permissionsPerMenu[] = [
                        'id' => $menu->MENU_IDME,
                        'name' => $menu-> MENU_NOMB,
                        'enabled' => 'N'
                    ];
                }

                $permissionsPerSubmodule[] = [
                    'id' => $submodule->SUBM_IDSM,
                    'name' => $submodule->SUBM_NOMB,
                    'enabled' => 'N',
                    'children' => $permissionsPerMenu,
                ];
            }

            $permissions[] = [
                'id' => $module->MODU_IDMO,
                'name' => $module->MODU_NOMO,
                'enabled' => 'N',
                'children' => $permissionsPerSubmodule
            ];
        }

        $permissionsF['permissions'] = $permissions;
        foreach($permissions as $k=>$v){
            if(array_key_exists($k, $profileInfo['permissions'])){
                $permissionsF['permissions'][$k] = $profileInfo['permissions'][$k];

                foreach($v['children'] as $k0=>$v0){
                    if(array_key_exists($k0, $profileInfo['permissions'][$k]['children'])){
                        $permissionsF['permissions'][$k]['children'][$k0] = $profileInfo['permissions'][$k]['children'][$k0];

                        foreach($v0['children'] as $k1=>$v1){
                            if(array_key_exists($k1, $profileInfo['permissions'][$k]['children'][$k0]['children'])){
                                $permissionsF['permissions'][$k]['children'][$k0]['children'][$k1] = $profileInfo['permissions'][$k]['children'][$k0]['children'][$k1];
                            }else{
                                $permissionsF['permissions'][$k]['children'][$k0]['children'][$k1] = $v1;
                            }
                        }
                    }else{
                        $permissionsF['permissions'][$k]['children'][$k0] = $v0;
                    }
                }
            }
        }

        $profile->PERMISOS = $permissionsF;
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $actions = DB::getQueryLog();
        
        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", $profile);
    }

    public function updateUser(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|string',
            'name' => 'required|string|max:50',
            'fApe' => 'required|string|max:50',
            'email' => 'required|string|email',
            'perf' => 'required|integer',
            'id_user' => 'required|string',
            'linea' => 'required|integer'
        ]);

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

        $user = $request->all();
        $idUser = $this->encryptionController->decrypt($user['id']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que desea modificar no está encriptado correctamente.", [], 400);
        }

        $idUserMod = $this->encryptionController->decrypt($user['id_user']);
        if(!$idUserMod){
            return $this->responseController->makeResponse(true, "El id del usuario que modifica no está encriptado correctamente.", [], 400);
        }

        if($idUser == $idUserMod){
            return $this->responseController->makeResponse(true, "El usuario no puede modificar su propio registro.", [], 401);
        }

        $now = Carbon::now('America/Mexico_city')->toDateTimeString();
        $correos = DB::table('S002V01TUSUA')->where([
            ['USUA_COEL', '=', $user['email']],
            ['USUA_IDUS', '!=', $idUser]
        ])->get()->all();

        if(count($correos) > 0){
            return $this->responseController->makeResponse(true, "El nuevo correo electrónico ya está registrado en la base.", [], 401);
        }

        $perfil = DB::table('S002V01TPERF')->where('PERF_IDPE', '=', $user['perf'])->get()->first();
        if(is_null($perfil)){
            return $this->responseController->makeResponse(true, "El perfil asignado no existe.", [], 404);
        }

        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->update([
            'USUA_NOMB' => $user['name'],
            'USUA_APPA' => $user['fApe'],
            'USUA_APMA' => array_key_exists('sApe', $user) ? $user['sApe'] : null,
            'USUA_COEL' => $user['email'],
            'USUA_PERF' => $user['perf'],
            'USUA_USMO' => $idUserMod,
            'USUA_FEMO' => $now
        ]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUserMod, $now, $user['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

    public function createUser(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'name' => 'required|string|max:50',
            'fApe' => 'required|string|max:50',
            'perf' => 'required|integer',
            'email' => 'required|string|email',
            'password' => 'required|string|min:8|confirmed',
        ]);

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

        $user = $request->all();
        $idusre = $this->encryptionController->decrypt($user['id_user']);

        if(!$idusre){
            return $this->responseController->makeResponse(true, "El ID del usuario que registra no está encriptado correctamente.", [], 400);
        }

        $usre = DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idusre)->get()->first();
        if(is_null($usre)){
            return $this->responseController->makeResponse(true, "El usuario que realiza el registro no existe.", [], 404);
        }else if($usre->USUA_ESTA == 'Eliminado'){
            return $this->responseController->makeResponse(true, "El usuario que realiza el registro está eliminado.", [], 401);
        }else if($usre->USUA_ESTA == 'Inactivo'){
            return $this->responseController->makeResponse(true, "El usuario que realiza el registro está boloqueado.", [], 401);
        }

        $email = DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $user['email'])->get()->first();
        if(!is_null($email)){
            return $this->responseController->makeResponse(true, "El correo electrónico ya se encuentra registrado.", [], 401);
        }

        $now = Carbon::now('America/Mexico_city')->toDateTimeString();
        $idUser = $this->functionsController->uuidv5('1546058f-5a25-4334-85ae-e68f2a44bbaf', $user['email'] . $now);
        $idExist = false;

        do{
            $exist = DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->get()->first();
            if(!is_null($exist)){
                $idExist = true;
                $now = Carbon::now('America/Mexico_city')->toDateTimeString();
                $idUser = $this->functionsController->uuidv5('1546058f-5a25-4334-85ae-e68f2a44bbaf', $user['email'] . $now);
            }else{
                $idExist = false;
            }
        }while($idExist);

        $perf = DB::table('S002V01TPERF')->where('PERF_IDPE', '=', $user['perf'])->get()->first();
        if(is_null($perf)){
            return $this->responseController->makeResponse(true, "El perfil asignado no existe.", [], 404);
        }

        $passEnc = Hash::make($user['password']);

        DB::table('S002V01TUSUA')->insert([
            'USUA_NULI' => $user['linea'],
            'USUA_IDUS' => $idUser,
            'USUA_NOMB' => $user['name'],
            'USUA_APPA' => $user['fApe'],
            'USUA_APMA' => array_keys($user, 'sApe') ? $user['sApe'] : null,
            'USUA_PERF' => $user['perf'],
            'USUA_CONT' => $passEnc,
            'USUA_COEL' => $user['email'],
            'USUA_USRE' => $idusre,
            'USUA_FERE' => $now,
        ]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idusre, $now, $user['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Registro correcto.");
    }

    public function blockUser(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|string',
            'estatus' => 'required|in:Activo,Inactivo',
            'id_user' => 'required|string',
            'linea' => 'required|integer'
        ]);

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

        $user = $request->all();
        $idUser = $this->encryptionController->decrypt($user['id']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que desea modificar no está encriptado correctamente.", [], 400);
        }

        $idUserMod = $this->encryptionController->decrypt($user['id_user']);
        if(!$idUserMod){
            return $this->responseController->makeResponse(true, "El id del usuario que modifica no está encriptado correctamente.", [], 400);
        }

        if($idUser == $idUserMod){
            return $this->responseController->makeResponse(true, "El usuario no puede modificarse a sí mismo", [], 400);
        }

        $now = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->update([
            'USUA_ESTA' => $user['estatus'],
            'USUA_USMO' => $idUserMod,
            'USUA_FEMO' => $now
        ]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUserMod, $now, $user['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

    public function updatePass(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|string',
            'password' => 'required|string|min:8|confirmed',
            'id_user' => 'required|string',
            'linea' => 'required|integer'
        ]);

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

        $user = $request->all();
        $idUser = $this->encryptionController->decrypt($user['id']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que desea modificar no está encriptado correctamente.", [], 400);
        }

        $idUserMod = $this->encryptionController->decrypt($user['id_user']);
        if(!$idUserMod){
            return $this->responseController->makeResponse(true, "El id del usuario que modifica no está encriptado correctamente.", [], 400);
        }

        if($idUser == $idUserMod){
            return $this->responseController->makeResponse(true, "El usuario no puede modificarse a sí mismo.", [], 401);
        }

        $usr = DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->get()->first();
        if(!$usr){
            return $this->responseController->makeResponse(true, "El usuario consultado no existe.", [], 404);
        }

        $lastPass = $usr->USUA_CONT;
        if(Hash::check($user['password'], $lastPass)){
            return $this->responseController->makeResponse(true, "La contraseña nueva es igual a la anterior.", [], 401);
        }

        $newPass = Hash::make($user['password']);
        $now = Carbon::now('America/Mexico_city')->toDateTimeString();

        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->update([
            'USUA_CONT' => $newPass,
            'USUA_USMO' => $idUserMod,
            'USUA_FEMO' => $now
        ]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUserMod, $now, $user['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

    public function deleteUser(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|string',
            'id_user' => 'required|string',
            'linea' => 'required|integer'
        ]);

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

        $user = $request->all();
        $idUser = $this->encryptionController->decrypt($user['id']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que desea eliminar no está encriptado correctamente", [], 400);
        }

        $idUserMod = $this->encryptionController->decrypt($user['id_user']);
        if(!$idUserMod){
            return $this->responseController->makeResponse(true, "El id del usuario que elimina no está encriptado correctamente", [], 400);
        }

        if($idUser == $idUserMod){
            return $this->responseController->makeResponse(true, "El usuario no puede eliminarse a sí mismo", [], 401);
        }

        $now = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->update([
            'USUA_ESTA' => 'Eliminado',
            'USUA_USMO' => $idUserMod,
            'USUA_FEMO' => $now
        ]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUserMod, $now, $user['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

    public function getModules($idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }
        
        $modules = DB::table('S002V01TMODU')->select(
            'MODU_IDMO as IDMODULO',
            'MODU_NOMO as NOMBREMODULO'
        )->get();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        
        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", $modules);
    }

    public function getSubmodules($module, $idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $module = $this->encryptionController->decrypt($module);
        if(!$module){
            return $this->responseController->makeResponse(true, "El módulo no está encriptado correctamente", [], 400);
        }

        $submodules = DB::table('S002V01TSUBM')->select(
            'SUBM_IDSM as IDSUBMODULO',
            'SUBM_NOMB as NOMBRESUBMODULO',
            'SUBM_ICON AS ICONOSUBMODULO'
        )->where('SUBM_IDMO', '=', $module)->get();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", $submodules);
    }

    public function getMenus($module, $submodule, $idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $module = $this->encryptionController->decrypt($module);
        $submodule = $this->encryptionController->decrypt($submodule);

        if(!$module){
            return $this->responseController->makeResponse(true, "El módulo no está encriptado correctamente", [], 400);
        }else if(!$submodule){
            return $this->responseController->makeResponse(true, "El submódulo no está encriptado correctamente", [], 400);
        }

        $menus = DB::table('S002V01TMENU')->select(
            'MENU_IDME AS IDMENU',
            'MENU_NOMB AS NOMBREMENU' 
        )->where([
            ['MENU_IDMO', '=', $module],
            ['MENU_IDSM', '=', $submodule]
        ])->get();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", $menus);
    }

    public function buildInitialPermissions($idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->decrypt($idUser);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $permissions = [];
        //Se obtienen todos los modulos
        $modules = DB::table('S002V01TMODU')->get()->all();
        //se consultan los submodulos de cada modulo
        foreach($modules as $module){
            $submodules = DB::table('S002V01TSUBM')->where('SUBM_IDMO', '=', $module->MODU_IDMO)->get()->all();
            $permissionsPerSubmodule = [];
            foreach($submodules as $submodule){
                //Se consultan los menus
                $menus = DB::table('S002V01TMENU')->where([
                    ['MENU_IDMO', '=', $module->MODU_IDMO],
                    ['MENU_IDSM', '=', $submodule->SUBM_IDSM],
                ])->get()->all();

                $permissionsPerMenu = [];
                foreach($menus as $menu){
                    $permissionsPerMenu[] = [
                        'id' => $menu->MENU_IDME,
                        'name' => $menu-> MENU_NOMB,
                        'enabled' => 'N'
                    ];
                }

                $permissionsPerSubmodule[] = [
                    'id' => $submodule->SUBM_IDSM,
                    'name' => $submodule->SUBM_NOMB,
                    'enabled' => 'N',
                    'children' => $permissionsPerMenu,
                ];
            }

            $permissions[] = [
                'id' => $module->MODU_IDMO,
                'name' => $module->MODU_NOMO,
                'enabled' => 'N',
                'children' => $permissionsPerSubmodule
            ];
        }

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

        $this->functionsController->registerActivity($actions, $idUser, $nowStr, $line);
        return $this->responseController->makeresponse(false, "EXITO", ['permissions' => $permissions]);
    }

    public function updateProfile(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
            'permissions' => 'required|json',
            'name' => 'required|string|max:50',
            'id_user' => 'required|string',
            'linea' => 'required|integer'
        ]);

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

        $info = $request->all();
        $now = Carbon::now('America/Mexico_city')->toDateTimeString();
        $idUser = $this->encryptionController->decrypt($info['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que modifica no está encriptado correctamente", [], 401);
        }

        DB::table('S002V01TPERF')->where('PERF_IDPE', $info['id'])->update([
            'PERF_PERM' => $info['permissions'],
            'PERF_NOPE' => $info['name'],
            'PERF_USMO' => $idUser,
            'PERF_FEMO' => $now
        ]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUser, $now, $info['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

    public function deleteProfile(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
            'id_user' => 'required|string',
            'linea' => 'required|integer'
        ]);

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

        $profile = $request->all();
        $now = Carbon::now('America/Mexico_city')->toDateTimeString();
        $idUser = $this->encryptionController->decrypt($profile['id_user']);

        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que elimina no está encriptado correctamente", [], 401);
        }

        $users = DB::table('S002V01TUSUA')->where('USUA_PERF', '=', $profile['id'])->get()->all();
        if(count($users) > 0){
            return $this->responseController->makeResponse(true, "El perfil seleccionado no se puede eliminar porque hay usuarios asociados a él.", [], 401);
        }
        
        DB::table('S002V01TPERF')->where('PERF_IDPE', $profile['id'])->update([
            'PERF_ESTA' => 'Eliminado',
            'PERF_USMO' => $idUser,
            'PERF_FEMO' => $now
        ]);

        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUser, $now, $profile['linea']);
        return $this->responseController->makeResponse(false, "EXITO: Eliminación correcta.");
    }

    public function createProfile(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'name' => 'required|string|min:8|max:50',
            'permissions' => 'required|json'
        ]);

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

        $profile = $request->all();
        $now = Carbon::now('America/Mexico_city')->toDateTimeString();
        $idUser = $this->encryptionController->decrypt($profile['id_user']);

        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El perfil no está encriptado correctamente.', [], 401);
        }

        DB::table('S002V01TPERF')->insert([
            'PERF_NULI' => $profile['linea'],
            'PERF_NOPE' => $profile['name'],
            'PERF_PERM' => $profile['permissions'],
            'PERF_USRE' => $idUser,
            'PERF_FERE' => $now,
        ]);
        
        $actions = DB::getQueryLog();
        $this->functionsController->registerActivity($actions, $idUser, $now, $profile['linea']);
        return $this->responseController->makeResponse(false, 'EXITO');
    }
}
