<?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;
    private $moduleCode = 'S002V01M02USPE';

    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->shortDec($idUser);

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 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'
        )->where('USUA_NULI', '=', $line)->get()->all();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $line,
            $this->moduleCode,
            'S002V01F01ADUS',
            'S002V01P01COUS',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los usuarios registrados.",
            $idUser,
            $nowStr,
            'S002V01S01GEUS'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);

        return $this->responseController->makeresponse(false, "EXITO", $users);
    }

    public function getUser($id, $idUser, $line){
        DB::enableQueryLog();
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuaio que realizó la solicitud no está encriptado correctamente', [], 400);
        }

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 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],
            ['USUA_NULI', '=', $line],
        ])->get()->first();

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

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        $nameCons = $this->functionsController->joinName($user->NOMBRE, $user->APEPAT, $user->APEMAT);

        $idac = $this->functionsController->registerActivity(
            $line,
            $this->moduleCode,
            'S002V01F01ADUS',
            'S002V01P01COUS',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó al usuario $nameCons (" . $user->IDUSUARIO . ").",
            $idUser,
            $nowStr,
            'S002V01S01GEUS'
        );

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

    public function getProfiles($idUser, $line){
        DB::enableQueryLog();

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }
        
        $profiles = DB::table('S002V01TPERF')->select(
            'PERF_IDPE as IDPERFIL',
            'PERF_NOPE as NOMBREPERFIL',
            'PERF_ESTA as ESTATUS',
            'PERF_PERM as PERMISOS',
            'PERF_FEMO as FECHAMODIFICACION',
            'PERF_FERE as FECHACREACION'
        )->orderBy('PERF_ESTA', 'asc')->orderBy('PERF_IDPE', 'asc')->get()->all();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $line,
            $this->moduleCode,
            'S002V01F01ADPE',
            'S002V01P01COPE',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los perfiles registrados.",
            $idUser,
            $nowStr,
            'S002V01S02GEPE'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);

        return $this->responseController->makeresponse(false, "EXITO", $profiles);
    }

    public function getProfile($id, $idUser, $line){
        DB::enableQueryLog();

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

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 400);
        }

        $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],
            ['PERF_NULI', '=', $line],
        ])->first();

        if(is_null($profile)){
            return $this->responseController->makeResponse(true, "El perfil consultado no existe.", [], 404);
        }
        
        $profilePermissions = json_decode($profile->PERMISOS, true);
        $permissions = [];
        $modules = DB::table('S002V01TMODU')->where('MODU_NULI', '=', $line)->get()->all();
        $moduleIndex = 0;
        foreach($modules as $module){
            $submodules = DB::table('S002V01TSUBM')->where([
                ['SUBM_IDMO', '=', $module->MODU_IDMO],
                ['SUBM_NULI', '=', $line]
            ])->get()->all();
            
            $permissionsPerSubmodule = [];
            $hasSubmodules = false;
            $submoduleIndex = 0;
            foreach($submodules as $submodule){
                $functions = DB::table('S002V01TFUNC')->where([
                    ['FUNC_IDMO', '=', $module->MODU_IDMO],
                    ['FUNC_IDSM', '=', $submodule->SUBM_IDSM],
                    ['FUNC_NULI', '=', $line],
                ])->get()->all();

                $permissionsPerFunction = [];
                $functionIndex = 0;
                foreach($functions as $function){
                    $screens = DB::table('S002V01TPANT')->where([
                        ['PANT_IDFU', '=', $function->FUNC_IDFU],
                        ['PANT_NULI', '=', $line],
                    ])->get()->all();

                    $permissionsPerScreen = [];
                    $screenIndex = 0;
                    foreach($screens as $screen){
                        $screenAccess = 0;
                        if(isset($profilePermissions['permissions'][$moduleIndex]['children'][$submoduleIndex]['children'][$functionIndex]['children'][$screenIndex]['access'])){
                            $screenAccess = $profilePermissions['permissions'][$moduleIndex]['children'][$submoduleIndex]['children'][$functionIndex]['children'][$screenIndex]['access'];
                        }
                        
                        $permissionsPerScreen[] = [
                            'id' => $screen->PANT_IDPA,
                            'name' => $screen->PANT_NOMB,
                            'access' => $screenAccess
                        ];
                        
                        $screenIndex++;
                    }

                    $functionAcces = 0;
                    if(isset($profilePermissions['permissions'][$moduleIndex]['children'][$submoduleIndex]['children'][$functionIndex]['access'])){
                        $functionAcces = $profilePermissions['permissions'][$moduleIndex]['children'][$submoduleIndex]['children'][$functionIndex]['access'];
                    }

                    $permissionsPerFunction[] = [
                        'id' => $function->FUNC_IDFU,
                        'name' => $function->FUNC_NOMB,
                        'access' => $functionAcces,
                        'children' => $permissionsPerScreen,
                    ];

                    $functionIndex++;
                }

                $submoduleAccess = 0;
                if(isset($profilePermissions['permissions'][$moduleIndex]['children'][$submoduleIndex]['access'])){
                    $submoduleAccess = $profilePermissions['permissions'][$moduleIndex]['children'][$submoduleIndex]['access'];
                }

                $permissionsPerSubmodule[] = [
                    'id' => $submodule->SUBM_IDSM,
                    'name' => $submodule->SUBM_NOMB,
                    'access' => $submoduleAccess,
                    'children' => $permissionsPerFunction,
                ];

                $hasSubmodules = true;
                $submoduleIndex++;
            }
            
            $functions = DB::table('S002V01TFUNC')->where([
                ['FUNC_IDMO', '=', $module->MODU_IDMO],
                ['FUNC_IDSM', '=', null],
                ['FUNC_NULI', '=', $line],
            ])->get()->all();
            
            $permissionsPerFunction = [];
            $functionIndex = 0;
            foreach($functions as $function){
                $screens = DB::table('S002V01TPANT')->where([
                    ['PANT_IDFU', '=', $function->FUNC_IDFU],
                    ['PANT_NULI', '=', $line],
                ])->get()->all();

                $permissionsPerScreen = [];
                $screenIndex = 0;
                foreach($screens as $screen){
                    $screenAccess = 0;
                    if(isset($profilePermissions['permissions'][$moduleIndex]['children'][$functionIndex]['children'][$screenIndex]['access'])){
                        $screenAccess = $profilePermissions['permissions'][$moduleIndex]['children'][$functionIndex]['children'][$screenIndex]['access'];
                    }

                    $permissionsPerScreen[] = [
                        'id' => $screen->PANT_IDPA,
                        'name' => $screen->PANT_NOMB,
                        'access' => $screenAccess
                    ];

                    $screenIndex++;
                }

                $functionAcces = 0;
                if(isset($profilePermissions['permissions'][$moduleIndex]['children'][$functionIndex]['access'])){
                    $functionAcces = $profilePermissions['permissions'][$moduleIndex]['children'][$functionIndex]['access'];
                }

                $permissionsPerFunction[] = [
                    'id' => $function->FUNC_IDFU,
                    'name' => $function->FUNC_NOMB,
                    'access' => $functionAcces,
                    'children' => $permissionsPerScreen,
                ];

                $functionIndex++;
            }

            $permissionsArr = [];
            foreach($permissionsPerSubmodule as $perm){ $permissionsArr[] = $perm; }
            foreach($permissionsPerFunction as $perm){ $permissionsArr[] = $perm; }

            $moduleAccess = $profilePermissions['permissions'][$moduleIndex]['access'];

            $permissions[] = [
                'id' => $module->MODU_IDMO,
                'name' => $module->MODU_NOMO,
                'access' => $moduleAccess,
                'children' => $permissionsArr,
            ];

            $moduleIndex++;
        }

        $profile->PERMISOS = ['permissions' => $permissions];
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $line,
            $this->moduleCode,
            'S002V01F01ADPE',
            'S002V01P01COPE',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el perfil " . $profile->NOMBREPERFIL . " (" . $profile->IDPERFIL . ").",
            $idUser,
            $nowStr,
            'S002V01S02GEPE'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $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);
        }

        $usrMod = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $user['linea']],
        ])->first();

        if(is_null($usrMod)){
            return $this->responseController->makeResponse(true, 'El usuario que desea modificar no exise.', [], 404);
        }

        $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);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUserMod],
            ['USUA_NULI', '=', $user['linea']],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realiza la solicitud no existe', [], 404);
        }

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

        $nowStr = 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],
            ['USUA_NULI', '=', $user['linea']]
        ])->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' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $user['linea'],
            $this->moduleCode,
            'S002V01F01ADUS',
            'S002V01P02RAUS',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó al usuario $nameMod (" . $usrMod->USUA_IDUS . ").",
            $idUser,
            $nowStr,
            'S002V01S01GEUS'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $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);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUsre],
            ['USUA_NULI', '=', $user['linea']]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }else if($usr->USUA_ESTA == 'Eliminado'){
            return $this->responseController->makeResponse(true, "El usuario que realiza el registro está eliminado.", [], 401);
        }else if($usr->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']],
            ['USUA_NULI', '=', $user['linea']]
        ])->get()->first();
        
        if(!is_null($email)){
            return $this->responseController->makeResponse(true, "El correo electrónico ya se encuentra registrado.", [], 401);
        }

        $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']);
        $apemat = isset($user['sApe']) ? $user['sApe'] : null;
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

        $idUser = DB::table('S002V01TUSUA')->insertGetId([
            'USUA_NULI' => $user['linea'],
            'USUA_NOMB' => $user['name'],
            'USUA_APPA' => $user['fApe'],
            'USUA_APMA' => $apemat,
            'USUA_PERF' => $user['perf'],
            'USUA_CONT' => $passEnc,
            'USUA_COEL' => $user['email'],
            'USUA_USRE' => $idUsre,
            'USUA_FERE' => $nowStr,
        ]);
            
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        $nameReg = $this->functionsController->joinName($user['name'], $user['fApe'], $apemat);

        $idac = $this->functionsController->registerActivity(
            $user['linea'],
            $this->moduleCode,
            'S002V01F01ADUS',
            'S002V01P02RAUS',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró al usuario $nameReg ($idUser).",
            $idUsre,
            $nowStr,
            'S002V01S01GEUS'
        );

        $this->functionsController->registerLog($actions, $idUsre, $nowStr, $idac, $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);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $user['linea']],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 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);
        }

        $usrMod = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUserMod],
            ['USUA_NULI', '=', $user['linea']],
        ])->first();

        if(is_null($usrMod)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 400);
        }

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

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
        $tipoAccion = $user['estatus'] == 'Activo' ? 'desbloqueó' : 'bloqueó';

        $idac = $this->functionsController->registerActivity(
            $user['linea'],
            $this->moduleCode,
            'S002V01F02BDAC',
            '-',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") $tipoAccion al usuario $nameMod (" . $usrMod->USUA_IDUS . ").",
            $idUser,
            $nowStr,
            'S002V01S01GEUS'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $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);
        }

        $usrMod = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $user['linea']],
        ])->first();

        if(is_null($usrMod)){
            return $this->responseController->makeResponse(true, 'El usuario que desea modificar no existe', [], 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', '=', $idUserMod],
            ['USUA_NULI', '=', $user['linea']],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 400);
        }

        $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']);
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

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

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        $namemMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $user['linea'],
            $this->moduleCode,
            'S002V01F01ADUS',
            'S002V01P01COUS',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los usuarios registrados.",
            $idUser,
            $nowStr,
            'S002V01S01GEUS'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $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);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $user['linea']]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $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);
        }

        $usrMod = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUserMod],
            ['USUA_NULI', '=', $user['linea']]
        ])->first();

        if(is_null($usrMod)){
            return $this->responseController->makeResponse(true, 'El usuario que desea eliminar no está registrado', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->update([
            'USUA_ESTA' => 'Eliminado',
            'USUA_USMO' => $idUserMod,
            'USUA_FEMO' => $nowStr
        ]);
            
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $user['linea'],
            $this->moduleCode,
            'S002V01F04ELUS',
            '-',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eleimnó al usuario $nameMod (" . $usrMod->USUA_IDUS . ").",
            $idUser,
            $nowStr,
            'S002V01S01GEUS'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $user['linea']);
        
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

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

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }
        
        $modules = DB::table('S002V01TMODU')->select(
            'MODU_IDMO as IDMODULO',
            'MODU_NOMO as NOMBREMODULO',
            'MODU_ICON as ICONOMODULO',
        )->where('MODU_NULI', '=', $line)->get()->all();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            '-',
            '-',
            '-',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los módulos del sistema.",
            $idUser,
            $nowStr
        );

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

    public function getMenus($idMod, $idSub, $idUser, $line){
        DB::enableQueryLog();

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $idMod = $this->encryptionController->shortDec($idMod);
        if(!$idMod){
            return $this->responseController->makeResponse(true, 'El ID del módulo no fue encriptado correctamente', [], 400);
        }
        var_dump($idMod);

        /*$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();

        return $this->responseController->makeresponse(false, "EXITO", $menus);*/
    }

    public function getMenu($idUser, $line){
        $idUser = $this->encryptionController->shortDec($idUser);

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

        $modules = DB::table('S002V01TMODU')->select(
            'MODU_IDMO as IDMODULO',
            'MODU_NOMO as NOMBREMODULO',
            'MODU_ICON as ICONOMODULO',
        )->get()->all();
        $mods = [];

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

            $menusMod = DB::table('S002V01TFUNC')->select(
                'FUNC_IDFU AS IDFUNCION',
                'FUNC_NOMB AS NOMBREFUNCION',
                'FUNC_ICON AS ICONOFUNCION'
            )->where([
                ['FUNC_IDMO', '=', $module->IDMODULO],
                ['FUNC_IDSM', '=', null]
            ])->get()->all();

            $module->SUBMODULES = [];
            foreach($submodules as $submodule){
                $menus = DB::table('S002V01TFUNC')->select(
                    'FUNC_IDFU AS IDFUNCION',
                    'FUNC_NOMB AS NOMBREFUNCION',
                    'FUNC_ICON AS ICONOFUNCION'
                )->where([
                    ['FUNC_IDMO', '=', $module->IDMODULO],
                    ['FUNC_IDSM', '=', $submodule->IDSUBMODULO]
                ])->get()->all();

                $menuInd = 0;
                foreach($menus as $funcion){
                    $pantallas = DB::table('S002V01TPANT')->select(
                        'PANT_IDPA AS IDPANTALLA',
                        'PANT_NOMB AS NOMBREPANTALLA'
                    )->where([
                        ['PANT_IDFU', '=', $funcion->IDFUNCION],
                        ['PANT_NULI', '=', $line]
                    ])->get()->all();

                    $menus[$menuInd]->PANTALLAS = $pantallas;
                    $menuInd++;
                }

                $submodule->FUNCIONES = [];
                foreach($menus as $menu){
                    $submodule->FUNCIONES[] = $menu;
                }

                $module->SUBMODULES[] = $submodule;
            }

            $menModInd = 0;
            foreach($menusMod as $funcion){
                $pantallas = DB::table('S002V01TPANT')->select(
                    'PANT_IDPA AS IDPANTALLA',
                    'PANT_NOMB AS NOMBREPANTALLA'
                )->where([
                    ['PANT_IDFU', '=', $funcion->IDFUNCION],
                    ['PANT_NULI', '=', $line]
                ])->get()->all();

                $menusMod[$menModInd]->PANTALLAS = $pantallas;
                $menModInd++;
            }

            $module->MENUS = $menusMod;
            $mods[] = $module;
        }

        return $this->responseController->makeResponse(false, "EXITO", $mods);
    }

    public function buildInitialPermissions($idUser, $line){
        DB::enableQueryLog();
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 400);
        }

        $permissions = [];
        //Se obtienen todos los modulos
        $modules = DB::table('S002V01TMODU')->where('MODU_NULI', '=', $line)->get()->all();
        //se consultan los submodulos de cada modulo
        foreach($modules as $module){
            $submodules = DB::table('S002V01TSUBM')->where([
                ['SUBM_IDMO', '=', $module->MODU_IDMO],
                ['SUBM_NULI', '=', $line]
            ])->get()->all();
            
            $permissionsPerSubmodule = [];
            $hasSubmodules = false;
            foreach($submodules as $submodule){
                //Se consultan las funciones
                $functions = DB::table('S002V01TFUNC')->where([
                    ['FUNC_IDMO', '=', $module->MODU_IDMO],
                    ['FUNC_IDSM', '=', $submodule->SUBM_IDSM],
                    ['FUNC_NULI', '=', $line],
                ])->get()->all();

                $permissionsPerFunction = [];
                foreach($functions as $function){
                    $screens = DB::table('S002V01TPANT')->where([
                        ['PANT_IDFU', '=', $function->FUNC_IDFU],
                        ['PANT_NULI', '=', $line],
                    ])->get()->all();

                    $permissionsPerScreen = [];
                    foreach($screens as $screen){
                        $permissionsPerScreen[] = [
                            'id' => $screen->PANT_IDPA,
                            'name' => $screen->PANT_NOMB,
                            'access' => 0
                        ];
                    }

                    $permissionsPerFunction[] = [
                        'id' => $function->FUNC_IDFU,
                        'name' => $function->FUNC_NOMB,
                        'access' => 0,
                        'children' => $permissionsPerScreen,
                    ];
                }

                $permissionsPerSubmodule[] = [
                    'id' => $submodule->SUBM_IDSM,
                    'name' => $submodule->SUBM_NOMB,
                    'access' => 0,
                    'children' => $permissionsPerFunction,
                ];

                $hasSubmodules = true;
            }
            
            //Se consultan las funciones
            $functions = DB::table('S002V01TFUNC')->where([
                ['FUNC_IDMO', '=', $module->MODU_IDMO],
                ['FUNC_IDSM', '=', null],
                ['FUNC_NULI', '=', $line],
            ])->get()->all();
            
            $permissionsPerFunction = [];
            foreach($functions as $function){
                $screens = DB::table('S002V01TPANT')->where([
                    ['PANT_IDFU', '=', $function->FUNC_IDFU],
                    ['PANT_NULI', '=', $line],
                ])->get()->all();

                $permissionsPerScreen = [];
                foreach($screens as $screen){
                    $permissionsPerScreen[] = [
                        'id' => $screen->PANT_IDPA,
                        'name' => $screen->PANT_NOMB,
                        'access' => 0
                    ];
                }

                $permissionsPerFunction[] = [
                    'id' => $function->FUNC_IDFU,
                    'name' => $function->FUNC_NOMB,
                    'access' => 0,
                    'children' => $permissionsPerScreen,
                ];
            }

            $permissionsArr = [];
            foreach($permissionsPerSubmodule as $perm){ $permissionsArr[] = $perm; }
            foreach($permissionsPerFunction as $perm){ $permissionsArr[] = $perm; }

            $permissions[] = [
                'id' => $module->MODU_IDMO,
                'name' => $module->MODU_NOMO,
                'access' => 0,
                'children' => $permissionsArr,
            ];
        }

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $line,
            $this->moduleCode,
            'S002V01F01ADPE',
            'S002V01P02REPE',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el arreglo de permisos iniciales.",
            $idUser,
            $nowStr,
            'S002V01S02GEPE'
        );

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

    public function updateProfile(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id' => 'required|string',
            '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();
        
        $idUser = $this->encryptionController->decrypt($info['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID del usuario que realizó la solicitud no fue encriptado correctamente", [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $info['linea']],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 404);
        }

        $idPerf = $this->encryptionController->decrypt($info['id']);
        if(!$idPerf){
            return $this->responseController->makeResponse(true, "El ID del perfil solicitado no fue encriptado correctamente", [], 400);
        }

        $perf = DB::table('S002V01TPERF')->where([
            ['PERF_IDPE', '=', $idPerf],
            ['PERF_NULI', '=', $info['linea']],
        ])->first();

        if(is_null($perf)){
            return $this->responseController->makeResponse(true, 'El perfil solicitado no existe', [], 400);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TPERF')->where([
            ['PERF_IDPE', '=', $idPerf],
            ['PERF_NULI', '=', $info['linea']],
        ])->update([
            'PERF_PERM' => $info['permissions'],
            'PERF_NOPE' => $info['name'],
            'PERF_USMO' => $idUser,
            'PERF_FEMO' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $info['linea'],
            $this->moduleCode,
            'S002V01F01ADPE',
            'S002V01P02REPE',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el perfil " . $perf->PERF_NOPE . "(" . $perf->PERF_NOPE . ").",
            $idUser,
            $nowStr,
            'S002V01S02GEPE'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $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|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
            );
        }

        $profile = $request->all();

        $idUser = $this->encryptionController->decrypt($profile['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID del usuario que solicitó la acción no está encriptado correctamente", [], 401);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $profile['linea']],
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no existe', [], 404);
        }
        
        $idProf = $this->encryptionController->decrypt($profile['id']);
        if(!$idProf){
            return $this->responseController->makeResponse(true, "El ID del perfil seleccionado no está encriptado correctamente", [], 401);
        }

        $perf = DB::table('S002V01TPERF')->where([
            ['PERF_IDPE', '=', $idProf],
            ['PERF_NULI', '=', $profile['linea']],
        ])->first();

        if(is_null($perf)){
            return $this->responseController->makeResponse(true, 'El perfil solicitado no existe', [], 404);
        }

        $users = DB::table('S002V01TUSUA')->where([
            ['USUA_PERF', '=', $idProf],
            ['USUA_NULI', '=', $profile['linea']]
        ])->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);
        }
        
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TPERF')->where([
            ['PERF_IDPE', '=', $idProf],
            ['PERF_NULI', '=', $profile['linea']],
        ])->update([
            'PERF_ESTA' => 'Eliminado',
            'PERF_USMO' => $idUser,
            'PERF_FEMO' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $profile['linea'],
            $this->moduleCode,
            'S002V01F01ADPE',
            '-',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el perfil " . $perf->PERF_NOPE . "($idProf).",
            $idUser,
            $nowStr,
            'S002V01S02GEPE'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $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();

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $profile['linea']]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la solicitud no está registrado', [], 404);
        }else if($usr->USUA_ESTA == 'Eliminado'){
            return $this->responseController->makeResponse(true, "El usuario que realiza el registro está eliminado.", [], 401);
        }else if($usr->USUA_ESTA == 'Inactivo'){
            return $this->responseController->makeResponse(true, "El usuario que realiza el registro está boloqueado.", [], 401);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $newPerf = DB::table('S002V01TPERF')->insertGetId([
            'PERF_NULI' => $profile['linea'],
            'PERF_NOPE' => $profile['name'],
            'PERF_PERM' => $profile['permissions'],
            'PERF_USRE' => $idUser,
            'PERF_FERE' => $nowStr
        ]);
            
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

        $idac = $this->functionsController->registerActivity(
            $profile['linea'],
            $this->moduleCode,
            'S002V01F01ADPE',
            'S002V01P02REPE',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró el perfil $profile[name] ($newPerf).",
            $idUser,
            $nowStr,
            'S002V01S02GEPE'
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $profile['linea']);
        return $this->responseController->makeResponse(false, 'EXITO');
    }

    public function getModule($idMod, $idUser, $line){
        DB::enableQueryLog();
        $idMod = $this->encryptionController->shortDec($idMod);

        if(!$idMod){
            return $this->responseController->makeResponse(true, 'El módulo solicitado no fue encriptado correctamente', [], 400);
        }
        
        $idUser = $this->encryptionController->shortDec($idUser);

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

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $module = DB::table('S002V01TMODU')->select(
            'MODU_IDMO as IDMODULO',
            'MODU_NOMO as NOMBREMODULO',
        )->where([
            ['MODU_NULI', '=', $line],
            ['MODU_IDMO', '=', $idMod]
        ])->first();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            '-',
            '-',
            '-',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el módulo " . $idMod . " del sistema.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        
        return $this->responseController->makeresponse(false, "EXITO", [
            'NOMBREMODULO' => is_null($module) ? '-' : $module->NOMBREMODULO
        ]);
    }

    public function getSubmodule($idMod, $idSub, $idUser, $line){
        DB::enableQueryLog();
        
        $idMod = $this->encryptionController->shortDec($idMod);
        if(!$idMod){
            return $this->responseController->makeResponse(true, 'El módulo no fue encriptado correctamente', [], 400);
        }
        
        $idSub = $this->encryptionController->shortDec($idSub);
        if(!$idSub){
            return $this->responseController->makeResponse(true, 'El submódulo no fue encriptado correctamente', [], 400);
        }
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El id del usuario que consulta no fue encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $submodule = DB::table('S002V01TSUBM')->select(
            'SUBM_IDSM as IDSUBMODULO',
            'SUBM_NOMB as NOMBRESUBMODULO',
        )->where([
            ['SUBM_NULI', '=', $line],
            ['SUBM_IDSM', '=', $idSub],
            ['SUBM_IDMO', '=', $idMod],
        ])->first();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            '-',
            '-',
            '-',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el submódulo " . $idSub . " del sistema.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);

        return $this->responseController->makeresponse(false, "EXITO", [
            'NOMBRESUBMODULO' => is_null($submodule) ? '-' : $submodule->NOMBRESUBMODULO
        ]);
    }

    public function getFunction($idMod, $idSub, $idFun, $idUser, $line){
        DB::enableQueryLog();
        
        $idMod = $this->encryptionController->shortDec($idMod);
        if(!$idMod){
            return $this->responseController->makeResponse(true, 'El módulo no fue encriptado correctamente', [], 400);
        }
        
        $idSub = $this->encryptionController->shortDec($idSub);
        if(!$idSub){
            return $this->responseController->makeResponse(true, 'El submódulo no fue encriptado correctamente', [], 400);
        }

        $idFun = $this->encryptionController->shortDec($idFun);
        if(!$idFun){
            return $this->responseController->makeResponse(true, 'La función no fue encriptada correctamente', [], 400);
        }
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El id del usuario que consulta no fue encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $function = DB::table('S002V01TFUNC')->select(
            'FUNC_IDFU as IDFUNCION',
            'FUNC_NOMB as NOMBREFUNCION',
        )->where([
            ['FUNC_NULI', '=', $line],
            ['FUNC_IDFU', '=', $idFun],
            ['FUNC_IDMO', '=', $idMod],
            ['FUNC_IDSM', '=', $idSub],
        ])->first();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            '-',
            '-',
            '-',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la función " . $idFun . " del sistema.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        
        return $this->responseController->makeresponse(false, "EXITO", [
            'NOMBREFUNCION' => is_null($function) ? '-' : $function->NOMBREFUNCION
        ]);
    }

    public function getScreen($idFun, $idPan, $idUser, $line){
        DB::enableQueryLog();

        $idFun = $this->encryptionController->shortDec($idFun);
        if(!$idFun){
            return $this->responseController->makeResponse(true, 'La función no fue encriptada correctamente', [], 400);
        }

        $idPan = $this->encryptionController->shortDec($idPan);
        if(!$idPan){
            return $this->responseController->makeResponse(true, 'La pantalla no fue encriptada correctamente', [], 400);
        }
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El id del usuario que consulta no fue encriptado correctamente', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $line]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }

        $screen = DB::table('S002V01TPANT')->select(
            'PANT_IDFU as IDPANTALLA',
            'PANT_NOMB as NOMBREPANTALLA',
        )->where([
            ['PANT_NULI', '=', $line],
            ['PANT_IDPA', '=', $idPan],
            ['PANT_IDFU', '=', $idFun],
        ])->first();

        $actions = DB::getQueryLog();
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            '-',
            '-',
            '-',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la pantalla " . $idPan . " del sistema.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        
        return $this->responseController->makeresponse(false, "EXITO", [
            'NOMBREPANTALLA' => is_null($screen) ? '-' : $screen->NOMBREPANTALLA
        ]);
    }
}
