<?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;

use PhpOffice\PhpSpreadsheet\Reader\Exception as ExcelException;
use PhpOffice\PhpSpreadsheet\IOFactory;

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

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

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

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

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

        $lastConnections = DB::table('S002V01TUSUA')->leftJoin('S002V01TBIAC', 'USUA_ULCO', '=', 'BIAC_IDCO')->select(
            'USUA_IDUS AS IDUSUARIO',
            'BIAC_FECO AS ULCON'
        )->get()->all();

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

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

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

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

        $user = $request->all();

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

        $now = Carbon::now('America/Mexico_city');
        $nowStr = $now->toDateTimeString();
        $ipv = $request->ip();

        
        $idLastConn = DB::table('S002V01TBIAC')->insertGetId([
            'BIAC_NULI' => $user['linea'],
            'BIAC_IDUS' => $user['linea'],
            'BIAC_DIIP' => $ipv,
            'BIAC_LUCO' => $user['lugarConexion'],
            'BIAC_FECO' => $nowStr
        ]);

        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $idUser)->update(['USUA_ULCO' => $idLastConn]);

        $actions = DB::getQueryLog();
        return $this->responseController->makeResponse(false, "EXITO: Actualización correcta.");
    }

    public function getCatalogues($idUser, $line){
        DB::enableQueryLog();
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $catalogues = DB::table('S002V01TCATA')->select(
            'CATA_IDCA AS IDCATALOGO',
            'CATA_TICA AS TIPOCATALOGO',
            'CATA_VERS AS VERSION',
            'CATA_ARRE AS ADJUNTOS',
            'CATA_USRE AS USUARIOREGISTRO',
            'CATA_FERE AS FECHAREGISTRO',
        )->where([
            ['CATA_NULI', '=', $line],
            ['CATA_ESTA', '=', 'Activo']
        ])->get()->all();

        $cataloguesF = [];
        foreach($catalogues as $catalogue){
            $usrReg = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $catalogue->USUARIOREGISTRO],
            ])->first();

            $idReg = $catalogue->USUARIOREGISTRO;
            $catalogue->USUARIOREGISTRO = $this->functionsController->joinName(
                $usrReg->USUA_NOMB, 
                $usrReg->USUA_APPA, 
                $usrReg->USUA_APMA
            ) . " ($idReg)";

            $cataloguesF[] = $catalogue;
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F10AGCA',
            'S002V01P01HICA',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los catálogos registrados.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $cataloguesF);
    }

    public function registerCatalogue(Request $request){
        if(!$request->hasFile('xls')){
            return $this->responseController->makeResponse(true, "No se envió ningún archivo.", [], 400);
        }

        $validator = Validator::make($request->all(), [
            'type' => 'required|string',
            'linea' => 'required|integer',
            'id_user' => 'required|string'
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->shortDec($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que realizó la petición no fue encriptado correctamente", [], 400);
        }
        
        $allowedFiles = ["Colonias", "Códigos postales", "Estados", "Localidades", "Municipios"];
        if(!in_array($form['type'], $allowedFiles)){
            return $this->responseController->makeResponse(true, "El tipo de catálogo no está soportado.", [], 400);
        }

        $originalFileName = $request->file('xls')->getClientOriginalName();
        $tmpPath = $request->file('xls')->store('tempFiles');
        $path = str_replace("app\Http\Controllers", "storage\app\\$tmpPath", __DIR__);

        try{
            $ext = IOFactory::identify($path);
            $reader = IOFactory::createReader($ext);

            $spreadsheet = $reader->load($path);
        }catch(ExcelException $e){
            return $this->responseController->makeResponse(true, "El formato del árchivo enviado es inválido o está dañado", [], 400);
        }

        $worksheets = $spreadsheet->getSheetNames();
        unlink($path);
        if(!in_array('c_Colonia_1', $worksheets) && $form['type'] == 'Colonias'){
            return $this->responseController->makeResponse(true, "El archivo $originalFileName no tiene contiene la información requerida.", [], 400);
        }else if(!in_array('c_CodigoPostal_Parte_1', $worksheets) && $form['type'] == 'Códigos postales'){
            return $this->responseController->makeResponse(true, "El archivo $originalFileName no tiene contiene la información requerida.", [], 400);
        }else if(!in_array('c_Estado', $worksheets) && $form['type'] == 'Estados'){
            return $this->responseController->makeResponse(true, "El archivo $originalFileName no tiene contiene la información requerida.", [], 400);
        }else if(!in_array('c_Localidad', $worksheets) && $form['type'] == 'Localidades'){
            return $this->responseController->makeResponse(true, "El archivo $originalFileName no tiene contiene la información requerida.", [], 400);
        }else if(!in_array('c_Municipio', $worksheets) && $form['type'] == 'Municipios'){
            return $this->responseController->makeResponse(true, "El archivo $originalFileName no tiene contiene la información requerida.", [], 400);
        }

        $now = Carbon::now('America/Mexico_city')->toDateTimeLocalString();
        $fileID = $this->functionsController->uuidv5('1546058f-5a25-4334-85ae-e68f2a44bbaf', $now . $originalFileName);
        $finalPath = $request->file('xls')->storeAs('files/catalogues', $fileID . '-' .$originalFileName);
        $finalPath = str_replace("app\Http\Controllers", "storage\app\\$finalPath", __DIR__);

        $lastVersObj = DB::table('S002V01TCATA')->where('CATA_NOCA', '=', $form['type'])->orderBy('CATA_FERE', 'desc')->get()->first();
        $lastVers = 0;

        if(!is_null($lastVersObj)) $lastVers = intval($lastVersObj->CATA_VERS);
        $lastVers++;

        DB::table('S002V01TCATA')->insert([
            'CATA_NULI' => $form['linea'],
            'CATA_IDCA' => $fileID,
            'CATA_VERS' => $lastVers,
            'CATA_NOCA' => $form['type'],
            'CATA_UBIC' => $finalPath,
            'CATA_NOAR' => $originalFileName,
            'CATA_EXAR' => $ext,
            'CATA_USRE' => $idUser,
            'CATA_FERE' => $now
        ]);
        
        return $this->responseController->makeResponse(false, "EXITO");
    }

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

        $userInfo = DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $id)->get()->first();
        if(is_null($userInfo)){
            return $this->responseController->makeResponse(true, "El usuario que desea consultaro no existe.", [], 404);
        }

        $connections = DB::table('S002V01TBIAC')->select(
            'BIAC_IPV4 AS IP4',
            'BIAC_IPV6 AS IP6',
            'BIAC_FECO AS FECHA',
            'BIAC_LATI AS LATITUD',
            'BIAC_LONG AS LONGITUD',
            'BIAC_PREC AS PRECISION',
            'BIAC_CIUD AS CIUDAD',
            'BIAC_ESTA AS ESTADO',
            'BIAC_PAIS AS PAIS',
            'BIAC_DISP AS DISPOSITIVO',
            'BIAC_SIOP AS SITEMAOPERATIVO',
            'BIAC_VSOP AS VERSIONSO',
            'BIAC_NAVE AS NAVEGADOR',
        )->where('BIAC_IDUS', '=', $id)->orderBy('BIAC_FECO', 'desc')->get()->all();

        $responseArr = [
            'NOMBRE' => $userInfo->USUA_NOMB,
            'APPAT' => $userInfo->USUA_APPA,
            'APMAT' => $userInfo->USUA_APMA,
            'ULTCON' => $userInfo->USUA_ULCO,
            'HISTORIAL' => $connections
        ];

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

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

    public function getLastActions($idUser, $line){
        DB::enableQueryLog();
        $idUser = $this->encryptionController->shortDec($idUser);
        
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID el usuario que realizó la petición 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);
        }

        $lastActions = DB::table('S002V01TUSUA')->leftJoin('S002V01TACCI', 'USUA_ULAC', '=', 'ACCI_IDAC')->select(
            'USUA_IDUS AS IDUSUARIO',
            'USUA_NOMB AS NOMBRE',
            'USUA_APPA AS APEPAT',
            'USUA_APMA AS APEMAT',
            'ACCI_IDMO AS IDMODULO',
            'ACCI_IDSM AS IDSUBMODULO',
            'ACCI_IDFU AS IDFUNCION',
            'ACCI_IDPA AS IDPANTALLA',
            'ACCI_TIAC AS TIPOACCION',
            'ACCI_DESC AS DESCRIPCION',
            'ACCI_FEAC AS FECHAACCION',
        )->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,
            'S002V01M01ADSI',
            'S002V01F02SAUS',
            'S002V01P01MOAC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las últimas acciónes realizadas.",
            $idUser,
            $nowStr
        );

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

        return $this->responseController->makeResponse(false, 'EXITO', $lastActions);
    }

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $userInfo = DB::table('S002V01TUSUA')->select(
            'USUA_IDUS AS IDUSUARIO',
            'USUA_NOMB AS NOMBRE',
            'USUA_APPA AS APEPAT',
            'USUA_APMA AS APEMAT'
        )->where([
            ['USUA_IDUS', '=', $id],
            ['USUA_NULI', '=', $line],
        ])->get()->first();

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

        $actions = DB::table('S002V01TACCI')->select(
            'MODU_NOMO AS MODULO',
            'SUBM_NOMB AS SUBMODULO',
            'FUNC_NOMB AS FUNCION',
            'PANT_NOMB AS PANTALLA',
            'ACCI_TIAC AS TIPOACCION',
            'ACCI_DESC AS DESCRIPCION',
            'ACCI_FEAC AS FECHA',
        )->leftJoin('S002V01TMODU', 'ACCI_IDMO', '=', 'MODU_IDMO')
        ->leftJoin('S002V01TSUBM', 'ACCI_IDSM', '=', 'SUBM_IDSM')
        ->leftJoin('S002V01TPANT', 'ACCI_IDPA', '=', 'PANT_IDPA')
        ->leftJoin('S002V01TFUNC', 'ACCI_IDFU', '=', 'FUNC_IDFU')->where([
            ['ACCI_IDUS', '=', $id],
            ['ACCI_NULI', '=', $line],
        ])->orderBy('ACCI_FEAC', 'desc')->get()->all();

        $userInfo->HISTORIAL = $actions;

        $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($userInfo->NOMBRE, $userInfo->APEPAT, $userInfo->APEMAT);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M01ADSI',
            'S002V01F02SAUS',
            'S002V01P02HIAC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las acciones del usuario $nameCons (" . $userInfo->IDUSUARIO . ")",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        
        return $this->responseController->makeResponse(false, 'EXITO', $userInfo);
    }

    public function downloadCatalogue($id, $idUser, $line, $token, Request $request){
        $id = $this->encryptionController->shortDec($id);
        if(!$id){
            return $this->responseController->makeResponse(true, "El ID del catálogo no fue encriptado correctamente.", [], 400);
        }

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

        $token = $this->encryptionController->shortDec($token);
        if(!$token){
            return $this->responseController->makeResponse(true, "El token de descarga no fue encriptado correctamente.", [], 400);
        }

        $tokenArr = json_decode($token, true);
        $now = Carbon::now('America/Mexico_city');
        $timestamp = $now->timestamp;
        $ip = $request->ip();

        if(intval($tokenArr['cad']) < $timestamp){
            return $this->responseController->makeResponse(true, "El token enviado está caducado", [], 401);
        }else if($tokenArr['ip4'] != $ip){
            return $this->responseController->makeResponse(true, "La ip que generó el token es difrente a la ip que realizó la solicitud", [], 401);
        }else if($tokenArr['usr'] != $idUser){
            return $this->responseController->makeResponse(true, "El usuario que generó el token es diferente al que realizó la solicitud", [], 401);
        }else if($tokenArr['typ'] != 'catalogue'){
            return $this->responseController->makeResponse(true, "El tipo de descarga es incorrecto", [], 401);
        }

        $fileInfo = DB::table('S002V01TCATA')->where('CATA_IDCA', '=', $id)->get()->first();
        if(is_null($fileInfo)){
            return $this->responseController->makeResponse(true, "El catálogo solicitado no existe", [], 404);
        }
        return response()->download($fileInfo->CATA_UBIC);
    }

    public function generateDownloadToken($idUser, $type, Request $request){
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID del usuario que realiza la solicitud no fue encriptado correctamente", [], 400);
        }

        $type = $this->encryptionController->shortDec($type);
        if(!$type){
            return $this->responseController->makeResponse(true, "El tipo de descarga no fue encriptado correctamente", [], 400);
        }

        $generatedAt = Carbon::now('America/Mexico_city')->timestamp;
        $expiresAt = Carbon::now('America/Mexico_city')->addMinutes(5)->timestamp;

        $ip = $request->ip();
        $tokenArr = [
            "gen" => $generatedAt,
            "cad" => $expiresAt,
            "ip4" => $ip,
            "usr" => $idUser,
            "typ" => $type
        ];

        $tokenStr = json_encode($tokenArr);
        $tokenEnc = $this->encryptionController->shortEnc($tokenStr);
        $token = str_replace("/", "=S=", $tokenEnc);
        $token = str_replace("+", "=P=", $token);
        
        return $this->responseController->makeResponse(false, "EXITO", ["downloadToken" => $token]);
    }

    public function readCatalogue($id, $idUser, $line){
        $id = $this->encryptionController->shortDec($id);
        if(!$id){
            return $this->responseController->makeResponse(true, "El ID del catálogo no fue encriptado correctamente");
        }

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID del usuario no fue encriptado correctamente");
        }

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

        $idArr = explode("-", $id);
        $idArr2 = explode("=", end($idArr));

        $catalogue = DB::table('S002V01TAFAL')->where([
            ['AFAL_NULI', '=', $idArr[0]],
            ['AFAL_COMO', '=', $idArr[1]],
            ['AFAL_CLDO', '=', $idArr[2]],
            ['AFAL_FECR', '=', $idArr[3]],
            ['AFAL_NUSE', '=', $idArr2[0]],
            ['AFAL_NUVE', '=', $idArr2[1]],
        ])->first();

        if(is_null($catalogue)){
            return $this->responseController->makeResponse(true, 'El catálogo solicitado no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->timestamp;
        $response = [
            "IDCATALOGO" => $this->encryptionController->encrypt($id),
            "EXTENSION" => $catalogue->AFAL_EXTE,
            "FECHA" => $nowStr
        ];
        
        copy($catalogue->AFAL_UBIC, 'C:\\inetpub\\wwwroot\\sam\\public_files\\' . $id);
        return $this->responseController->makeResponse(false, "EXITO", $response);
    }

    public function getAdvices($idUser, $line){
        DB::enableQueryLog();
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $advices = DB::table('S002V01TAVIS')->select(
            'AVIS_IDAV AS IDAVISO',
            'AVIS_TIAV AS TITULO',
            'AVIS_CADU AS CADUCIDAD',
            'AVIS_ESTA AS ESTATUS'
        )->orderBy('AVIS_IDAV', '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,
            'S002V01M01ADSI',
            'S002V01F03CRAV',
            'S002V01P01HIAV',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los avisos registrados.",
            $idUser,
            $nowStr
        );

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

        return $this->responseController->makeResponse(false, 'EXITO', $advices);
    }

    public function getAdvice($id, $idUser, $line){
        DB::enableQueryLog();
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }
        
        $id = $this->encryptionController->shortDec($id);
        if(!$id){
            return $this->responseController->makeResponse(true, 'El ID del aviso que consultó no está encriptado correctamente.', [], 400);
        }

        $advice = DB::table('S002V01TAVIS')->where([
            ['AVIS_NULI', '=', $line],
            ['AVIS_IDAV', '=', $id]
        ])->first();

        if(is_null($advice)){
            return $this->responseController->makeResponse(true, 'El aviso consultado no existe.', [], 404);
        }else if($advice->AVIS_ESTA != 'Activo'){
            return $this->responseController->makeResponse(true, 'El aviso consultado no está disponible.', [], 401);
        }

        $caduStr = $advice->AVIS_CADU;
        $caduObj = (new Carbon($caduStr))->timezone('America/Mexico_city');
        $now = Carbon::now('America/Mexico_city');
        
        if($now->gt($caduObj)){
            return $this->responseController->makeResponse(true, 'El aviso consultado está caducado.', [], 401);
        }

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

        $adviceFin = [
            'TITULO' => $advice->AVIS_TIAV,
            'CONTENIDO' => $advice->AVIS_COAV,
            'CADUCIDAD' => $advice->AVIS_CADU,
            'AUDIENCIA' => $this->encryptionController->encrypt($advice->AVIS_ALAV),
            'ADJUNTOS' => $advice->AVIS_ADJU,
            'IDUSUARIO' => $this->encryptionController->encrypt($advice->AVIS_USRE),
            'NOMBREUSUARIO' => $this->functionsController->joinName($usre->USUA_NOMB, $usre->USUA_APPA, $usre->USUA_APMA)
        ];

        $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,
            'S002V01M01ADSI',
            'S002V01F03CRAV',
            'S002V01P01HIAV',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el aviso " . $advice->AVIS_TIAV . " ($id).",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $adviceFin);
    }

    public function uploadFile(Request $request){
        DB::enableQueryLog();
        if(!$request->hasFile('file')){
            return $this->responseController->makeResponse(true, "No se envió ningún archivo.", [], 400);
        }

        $validator = Validator::make($request->all(), [
            '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
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->shortDec($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que realizó la petición no fue encriptado correctamente", [], 400);
        }

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

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

        $originalFileName = $request->file('file')->getClientOriginalName();
        $extension = $request->file('file')->extension();
        $size = $request->file('file')->getSize();

        $extArr = explode(".", $originalFileName);
        $extArr = array_reverse($extArr);
        $extStr = $extArr[0];

        $isValid = $this->functionsController->checkFileSize($extStr, $size);
        if($isValid){
            $dir = str_replace("app\\Http\\Controllers", "storage\\app", __DIR__);
            $tmpPath = $request->file('file')->store('tempFiles');
            $tmpPath = str_replace("/", "\\", $tmpPath);

            $location = "$dir\\$tmpPath";
            $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();

            $fileID = DB::table('S002V01TARTE')->insertGetId([
                'ARTE_NULI' => $form['linea'],
                'ARTE_NOAR' => $originalFileName,
                'ARTE_EXTE' => $extension,
                'ARTE_TAMA' => $size,
                'ARTE_UBTE' => $location,
                'ARTE_USRE' => $idUser,
                'ARTE_FERE' => $nowStr
            ]);
            
            $actions = DB::getQueryLog();
            $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);

            $idac = $this->functionsController->registerActivity(
                $form['linea'],
                'S002V01M04GDEL',
                'S002V01F01ADDO',
                'S002V01P05REDO',
                'Registro',
                "El usuario $name (" . $usr->USUA_IDUS . ") subió de manera temporal el archivo $originalFileName.",
                $idUser,
                $nowStr,
            );

            $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
            
            return $this->responseController->makeresponse(false, "EXITO", [
                'idArchivo' => $this->encryptionController->encrypt($fileID),
            ]);
        }else{
            return $this->responseController->makeResponse(true, "El archivo enviado tiene una extensión no soportada o sobrepasa el límite de peso de su categoría.", [], 400);
        }
    }

    public function deleteFile(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'id_file' => '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
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->shortDec($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El id del usuario que realizó la petición no fue encriptado correctamente", [], 400);
        }

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

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

        $idFile = $this->encryptionController->decrypt($form['id_file']);
        if(!$idFile){
            return $this->responseController->makeResponse(true, "El id del archivo que desea eliminar no fue encriptado correctamente", [], 400);
        }
        
        $file = DB::table('S002V01TARTE')->where([
            ['ARTE_IDAR', '=', $idFile],
            ['ARTE_NULI', '=', $form['linea']]
        ])->first();

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

        if(file_exists($file->ARTE_UBTE)){
            unlink($file->ARTE_UBTE);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TARTE')->where([
            ['ARTE_IDAR', '=', $idFile],
            ['ARTE_NULI', '=', $form['linea']]
        ])->update([
            'ARTE_ESTA' => 'Eliminado',
            'ARTE_USMO' => $idUser,
            'ARTE_FEMO' => $nowStr
        ]);

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

        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M04GDEL',
            'S002V01F01ADDO',
            'S002V01P05REDO',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el archivo " . $file->ARTE_NOAR,
            $idUser,
            $nowStr,
        );

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

    public function publishAdvice(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'titulo' => 'required|string|max:100',
            'caducidad' => 'required|date_format:Y-m-d H:i:s',
            'contenido' => 'required|string',
            'audiencia' => 'required|json',
            'archivos' => 'required|json',
        ]);

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

        $advice = $request->all();
        $idUser = $this->encryptionController->decrypt($advice['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID del usuario que realizó la petición no fue encriptado correctamente", [], 400);
        }

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

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

        $filesArr = json_decode($advice['archivos'], true);
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $attachedArr = [];
        foreach($filesArr as $file){
            $idFile = $file['id'];
            $idFile = $this->encryptionController->decrypt($idFile);
            if(!$idFile){
                return $this->responseController->makeResponse(true, "El ID del archivo $file[name] no fue encriptado correctamente", [], 400);
            }

            $fileObj = DB::table('S002V01TARTE')->where([
                ['ARTE_IDAR', '=', $idFile],
                ['ARTE_NULI', '=', $advice['linea']]
            ])->first();

            if(is_null($fileObj)){
                return $this->responseController->makeResponse(true, "El ID del archivo $file[name] no existe", [], 404);
            }else if($fileObj->ARTE_ESTA == 'Eliminado'){
                return $this->responseController->makeResponse(true, "El archivo $file[name] está eliminado", [], 404);
            }

            $fileSaved = $this->moveFinalFile($advice['linea'], 'AV', $fileObj, 'S002V01M01ADSI', 'S002V01F03CRAV', 'S002V01P02CNAV');
            if(!$fileSaved[0]){
                return $this->responseController->makeResponse(true, "El archivo no pudo guardarse: $fileSaved[1]", [], 500);
            }
            
            $attachedArr[] = $this->encryptionController->encrypt($fileSaved[1]);

            DB::table('S002V01TARTE')->where([
                ['ARTE_IDAR', '=', $idFile],
                ['ARTE_NULI', '=', $advice['linea']],
            ])->update([
                'ARTE_ESTA' => 'Eliminado',
                'ARTE_USMO' => $idUser,
                'ARTE_FEMO' => $nowStr
            ]);
        }

        $attachedStr = json_encode($attachedArr);
        $idav = DB::table('S002V01TAVIS')->insertGetId([
            'AVIS_NULI' => $advice['linea'],
            'AVIS_TIAV' => $advice['titulo'],
            'AVIS_COAV' => $advice['contenido'],
            'AVIS_ALAV' => $advice['audiencia'],
            'AVIS_ADJU' => $attachedStr,
            'AVIS_CADU' => $advice['caducidad'],
            'AVIS_FERE' => $nowStr,
            'AVIS_USRE' => $idUser
        ]);

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

        $idac = $this->functionsController->registerActivity(
            $advice['linea'],
            'S002V01M01ADSI',
            'S002V01F03CRAV',
            'S002V01P02CNAV',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró un nuevo aviso.",
            $idUser,
            $nowStr,
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $advice['linea']);
        return $this->responseController->makeresponse(false, "EXITO", ['idav' => $this->encryptionController->encrypt($idav)]);
    }

    public function updateAdvice(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'id_advice' =>'required|string',
            'linea' => 'required|integer',
            'titulo' => 'required|string|max:100',
            'caducidad' => 'required|date_format:Y-m-d H:i:s',
            'contenido' => 'required|string',
            'audiencia' => 'required|json',
        ]);

        if($validator->fails()){
            return $this->responseController->makeResponse(
                true,
                "Se encontraron uno o más errores.",
                $this->responseController->makeErrors(
                    $validator->errors()->messages()
                ),
                401
            );
        }
        
        $advice = $request->all();
        $idAdvice = $this->encryptionController->decrypt($advice['id_advice']);
        if(!$idAdvice){
            return $this->responseController->makeResponse(true, "El ID del aviso no fue encriptado correctamente.", [], 401);
        }

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

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

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

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TAVIS')->where([
            ['AVIS_NULI', '=', $advice['linea']],
            ['AVIS_IDAV', '=', $idAdvice]
        ])->update([
            'AVIS_TIAV' => $advice['titulo'],
            'AVIS_COAV' => $advice['contenido'],
            'AVIS_ALAV' => $advice['audiencia'],
            'AVIS_CADU' => $advice['caducidad'],
            'AVIS_FEMO' => $nowStr,
            'AVIS_USMO' => $idUser,
        ]);

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

        $idac = $this->functionsController->registerActivity(
            $advice['linea'],
            'S002V01M01ADSI',
            'S002V01F03CRAV',
            'S002V01P03EDAV',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el aviso $idAdvice.",
            $idUser,
            $nowStr,
        );

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

    public function deleteAdvice(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'id_advice' =>'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
            );
        }

        $advice = $request->all();
        $idAdvice = $this->encryptionController->decrypt($advice['id_advice']);
        if(!$idAdvice){
            return $this->responseController->makeResponse(true, "El ID del aviso no fue encriptado correctamente.", [], 401);
        }

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

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

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

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TAVIS')->where([
            ['AVIS_NULI', '=', $advice['linea']],
            ['AVIS_IDAV', '=', $idAdvice]
        ])->update([
            'AVIS_ESTA' => 'Eliminado',
            'AVIS_FEMO' => $nowStr,
            'AVIS_USMO' => $idUser,
        ]);

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

        $idac = $this->functionsController->registerActivity(
            $advice['linea'],
            'S002V01M01ADSI',
            'S002V01F03CRAV',
            'S002V01P01HIAV',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el aviso $idAdvice.",
            $idUser,
            $nowStr,
        );

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

    public function moveFinalFile(int $line, string $cldo, object $file, string $module, string $function, string $screen, string $submodule = null){
        $ubiTempFile = $file->ARTE_UBTE;
        $ubiFileArr = explode('tempFiles', $ubiTempFile);
        $ubic = $ubiFileArr[0] . 'files' . $ubiFileArr[1];

        $como = substr($module, -4);
        $date = Carbon::now('America/Mexico_city')->toDateTimeString();
        $dateArr = explode(' ', $date);
        $dateStr = $dateArr[0];
        $dA = explode('-', $dateStr);
        $dA[0] = substr($dA[0], -2);
        $fecr = implode('', $dA);

        $nameStr = $file->ARTE_NOAR;
        $nameArr = explode('.', $nameStr);

        $nuve = 0;
        $nuse = 0;

        $lastSec = DB::table('S002V01TAFAL')->where([
            ['AFAL_NULI', '=', $line],
            ['AFAL_COMO', '=', $como],
            ['AFAL_CLDO', '=', $cldo]
        ])->orderBy('AFAL_NUSE', 'desc')->first();

        if(is_null($lastSec)){
            $nuse = 1;
        }else{
            $nuse = $lastSec->AFAL_NUSE + 1;
        }

        $lastVersion = DB::table('S002V01TAFAL')->where([
            ['AFAL_NULI', '=', $line],
            ['AFAL_NOAR', '=', $nameArr[0]],
            ['AFAL_EXTE', '=', $nameArr[1]],
        ])->orderBy('AFAL_NUVE', 'desc')->first();

        if(is_null($lastVersion)){
            $nuve = 1;
        }else{
            $nuve = $lastVersion->AFAL_NUVE + 1;
        }

        if($nuve > 99) return [false, 'El archivo llegó al número máximo de versiones'];
        if($nuse > 999999)return [false, 'El archivo llegó al número de secuencia máximo'];

        
        $noar = $nameArr[0];
        $exte = $nameArr[1];

        if(strlen($noar) > 100) return [false, 'El nombre del archivo tiene una longitud mayor a 100 caracteres'];
        $tama = $file->ARTE_TAMA;
        $usac = json_encode([$file->ARTE_USRE]);
        $usre = $file->ARTE_USRE;
        $fere = $file->ARTE_FERE;

        DB::table('S002V01TAFAL')->insert([
            'AFAL_NULI' => $line,
            'AFAL_COMO' => $como,
            'AFAL_CLDO' => $cldo,
            'AFAL_FECR' => $fecr,
            'AFAL_NUSE' => $nuse,
            'AFAL_NUVE' => $nuve,
            'AFAL_NOAR' => $noar,
            'AFAL_EXTE' => $exte,
            'AFAL_TAMA' => $tama,
            'AFAL_UBIC' => $ubic,
            'AFAL_USAC' => $usac,
            'AFAL_USRE' => $usre,
            'AFAL_FERE' => $fere
        ]);

        if(file_exists($file->ARTE_UBTE)){
            rename($file->ARTE_UBTE, $ubic);
        }

        $codigo = "";
        if(strlen($line) < 2){
            $codigo .= "0$line-";
        }else{
            $codigo .= "$line-";
        }

        $codigo .= "$como-$cldo-$fecr-";
        switch(strlen($nuse)){
            case 1: $codigo .= "00000$nuse"; break;
            case 2: $codigo .= "0000$nuse"; break;
            case 3: $codigo .= "000$nuse"; break;
            case 4: $codigo .= "00$nuse"; break;
            case 5: $codigo .= "0$nuse"; break;
            default: $codigo .= "$nuse"; break;
        }
        
        if(strlen($nuve) < 2){
            $codigo .= "=0$nuve=";
        }else{
            $codigo .= "=$nuve=";
        }
        
        $codigo .= "$noar.$exte";

        return [true, $codigo];
    }

    public function getTwoStepsAuthUsers($idUser, $line){
        DB::enableQueryLog();
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $usersAuth = DB::table('S002V01TUSUA')->select([
            'USUA_IDUS',
            'USUA_NOMB',
            'USUA_APPA',
            'USUA_APMA',
            'USUA_FADO',
        ])->where('USUA_NULI', '=', $line)->get()->all();

        $arrAuth = [];
        foreach($usersAuth as $user){
            $name = $this->functionsController->joinName($user->USUA_NOMB, $user->USUA_APPA, $user->USUA_APMA);
            $authEnabled = $user->USUA_FADO == 'Si';

            $arrAuth[] = [
                'IDUSUARIO' => $this->encryptionController->encrypt($user->USUA_IDUS),
                'NOMBREUSUARIO' => $name,
                'AUTHENABLED' => $authEnabled
            ];
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P03ADPA',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las autenticaciones en dos pasos de los usuarios.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $arrAuth);
    }

    public function setTwoStepsAuth(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'factor_doble' => 'required|in:Si,No',
            'usuario' => '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
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->shortDec($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, "El ID del usuario que realizó la solicitud no fue encriptado correctamente.", [], 401);
        }

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

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

        $idChange = $this->encryptionController->shortDec($form['usuario']);
        if(!$idChange){
            return $this->responseController->makeResponse(true, "El ID del usuario que desea modificar no fue encriptado correctamente.", [], 401);
        }

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

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

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idChange],
            ['USUA_NULI', '=', $form['linea']]
        ])->update([
            'USUA_FADO' => $form['factor_doble'],
            '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);

        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P03ADPA',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") cambió el factor de dos pasos del usuario $nameMod ($idChange).",
            $idUser,
            $nowStr,
        );

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

    public function getPasswordFormat($idUser, $line){
        DB::enableQueryLog();
        
        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $politicsInfoRoute  = str_replace("app\Http\Controllers", "", __DIR__);
        $politicsInfoRoute .= "storage\\app\\files\\security-politics.json";
        $politicsStr = file_get_contents($politicsInfoRoute);
        $politicsArr = json_decode($politicsStr, true);

        $passwordFormat = $politicsArr['password_format'];
        $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,
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P01PACO',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el formato de las contraseñas.",
            $idUser,
            $nowStr
        );

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

    public function savePasswordFormat(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'min_length' => 'required|integer|between:8,30',
            'upper_enabled' => 'required|boolean',
            'min_upper' => 'required|integer|between:1,10',
            'number_enabled' => 'required|boolean',
            'min_number' => 'required|integer|between:1,10',
            'chars_enabled' => 'required|boolean',
            'min_chars' => 'required|integer|between:1,10',
        ]);

        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 de usuario 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 petición no existe.', [], 404);
        }

        $filePoliticsExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json');
        if(!$filePoliticsExists){
            return $this->responseController->makeResponse(true, 'El archivo de politicas de seguridad no fue encontrado.', [], 500);
        }

        $politicsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json');
        $politicsArr = json_decode($politicsStr, true);
        $passwordFormat = $politicsArr['password_format'];
        $formatBKP = $politicsStr;
        
        $passwordFormat['min_length'] = intval($info['min_length']);
        $passwordFormat['upper_enabled'] = intval($info['upper_enabled']) == 1;
        $passwordFormat['min_upper'] = intval($info['min_upper']);
        $passwordFormat['number_enabled'] = intval($info['number_enabled']) == 1;
        $passwordFormat['min_number'] = intval($info['min_number']);
        $passwordFormat['chars_enabled'] = intval($info['chars_enabled']) == 1;
        $passwordFormat['min_chars'] = intval($info['min_chars']);

        $politicsArr['password_format'] = $passwordFormat;
        $finalStr = json_encode($politicsArr); 
        file_put_contents('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json', $finalStr);

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TAPSE')->insert([
            'APSE_NULI' => $info['linea'],
            'APSE_USMO' => $idUser,
            'APSE_FEMO' => $nowStr,
            'APSE_VAAN' => $formatBKP,
            'APSE_VAAC' => $finalStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $info['linea'],
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P01PACO',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el formato de las contraseñas.",
            $idUser,
            $nowStr
        );

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $politicsInfoRoute  = str_replace("app\Http\Controllers", "", __DIR__);
        $politicsInfoRoute .= "storage\\app\\files\\security-politics.json";
        $politicsStr = file_get_contents($politicsInfoRoute);
        $politicsArr = json_decode($politicsStr, true);

        $sessionsDuration = $politicsArr['sessions_duration'];
        $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,
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P02DUSE',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la configuración de duración de sesiones.",
            $idUser,
            $nowStr
        );

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

    public function saveSessionsDuration(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'days' => 'required|integer|max:30',
            'hours' => 'required|integer|max:23',
            'minutes' => 'required|integer|max:59',
            'seconds' => 'required|integer|max:59',
        ]);

        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 de usuario 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 petición no existe.', [], 404);
        }

        $filePoliticsExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json');
        if(!$filePoliticsExists){
            return $this->responseController->makeResponse(true, 'El archivo de politicas de seguridad no fue encontrado.', [], 500);
        }

        $politicsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json');
        $politicsArr = json_decode($politicsStr, true);
        $sessionsDuration = $politicsArr['sessions_duration'];
        $formatBKP = $politicsStr;

        $sessionsDuration['days'] = intval($info['days']);
        $sessionsDuration['hours'] = intval($info['hours']);
        $sessionsDuration['minutes'] = intval($info['minutes']);
        $sessionsDuration['seconds'] = intval($info['seconds']);

        $politicsArr['sessions_duration'] = $sessionsDuration;
        $finalStr = json_encode($politicsArr); 
        file_put_contents('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json', $finalStr);

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TAPSE')->insert([
            'APSE_NULI' => $info['linea'],
            'APSE_USMO' => $idUser,
            'APSE_FEMO' => $nowStr,
            'APSE_VAAN' => $formatBKP,
            'APSE_VAAC' => $finalStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $info['linea'],
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P02DUSE',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la duración de las sesiones.",
            $idUser,
            $nowStr
        );

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $politicsInfoRoute  = str_replace("app\Http\Controllers", "", __DIR__);
        $politicsInfoRoute .= "storage\\app\\files\\security-politics.json";
        $politicsStr = file_get_contents($politicsInfoRoute);
        $politicsArr = json_decode($politicsStr, true);

        $activeSessionsNumber = $politicsArr['active_sessions_number'];
        $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,
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P04NSAC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la configuración del número de sesiones activas.",
            $idUser,
            $nowStr
        );

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

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

        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 de usuario 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 petición no existe.', [], 404);
        }

        $filePoliticsExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json');
        if(!$filePoliticsExists){
            return $this->responseController->makeResponse(true, 'El archivo de politicas de seguridad no fue encontrado.', [], 500);
        }

        $politicsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json');
        $politicsArr = json_decode($politicsStr, true);
        $formatBKP = $politicsStr;
        
        $politicsArr['active_sessions_number'] = intval($info['sessions']);
        $finalStr = json_encode($politicsArr); 
        file_put_contents('C:\inetpub\wwwroot\sam\storage\app\files\security-politics.json', $finalStr);

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TAPSE')->insert([
            'APSE_NULI' => $info['linea'],
            'APSE_USMO' => $idUser,
            'APSE_FEMO' => $nowStr,
            'APSE_VAAN' => $formatBKP,
            'APSE_VAAC' => $finalStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $info['linea'],
            'S002V01M01ADSI',
            'S002V01F04POSE',
            'S002V01P04NSAC',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el número de sesiones activas.",
            $idUser,
            $nowStr
        );

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

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

        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 de usuario 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 petición no existe.', [], 404);
        }

        $maintenanceModeExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json');
        if(!$maintenanceModeExists){
            return $this->responseController->makeResponse(true, 'El archivo de mantenimiento no fue encontrado.', [], 500);
        }

        $maintenanceStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json');
        $maintenanceArr = json_decode($maintenanceStr, true);

        if($maintenanceArr['activated']){
            return $this->responseController->makeResponse(true, 'El modo mantenimiento ya se encuentra activado', [], 401);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $idMant = DB::table('S002V01THMSA')->insertGetId([
            'HMSA_NULI' => $info['linea'],
            'HMSA_USAC' => $idUser,
            'HMSA_FEAC' => $nowStr,
            'HMSA_MOAC' => $info['motivos']
        ]);

        $maintenanceArr['activated'] = true;
        $maintenanceArr['last_activation_id'] = $idMant;
        $finalStr = json_encode($maintenanceArr);
        file_put_contents('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json', $finalStr);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $info['linea'],
            'S002V01M01ADSI',
            'S002V01F05MOMA',
            'S002V01P01AMMA',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") activó el modo mantenimiento",
            $idUser,
            $nowStr
        );

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

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

        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 de usuario 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 petición no existe.', [], 404);
        }

        $maintenanceModeExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json');
        if(!$maintenanceModeExists){
            return $this->responseController->makeResponse(true, 'El archivo de mantenimiento no fue encontrado.', [], 500);
        }

        $maintenanceStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json');
        $maintenanceArr = json_decode($maintenanceStr, true);

        if(!$maintenanceArr['activated']){
            return $this->responseController->makeResponse(true, 'El modo mantenimiento ya se encuentra desactivado', [], 401);
        }

        $maintenanceDB = DB::table('S002V01THMSA')->where([
            ['HMSA_IDAC', '=', $maintenanceArr['last_activation_id']],
            ['HMSA_NULI', '=', $info['linea']],
        ])->first();

        if(!is_null($maintenanceDB->HMSA_USDE)){
            $maintenanceArr['activated'] = false;
            $finalStr = json_encode($maintenanceArr);
            file_put_contents('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json', $finalStr);

            return $this->responseController->makeResponse(true, 'El modo mantenimiento ya fue desactivado en la base de datos.', [], 500);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01THMSA')->where([
            ['HMSA_IDAC', '=', $maintenanceArr['last_activation_id']],
            ['HMSA_NULI', '=', $info['linea']],
        ])->update([
            'HMSA_USDE' => $idUser,
            'HMSA_FEDE' => $nowStr,
            'HMSA_JUDE' => $info['justificacion']
        ]);

        
        $maintenanceArr['activated'] = false;
        $finalStr = json_encode($maintenanceArr);
        file_put_contents('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json', $finalStr);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $info['linea'],
            'S002V01M01ADSI',
            'S002V01F05MOMA',
            'S002V01P01AMMA',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") desactivó el modo mantenimiento",
            $idUser,
            $nowStr
        );

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $history = DB::table('S002V01THMSA')->where('HMSA_NULI', '=', $line)->get()->all();
        $historyF = array();

        foreach($history as $val){
            $activationDate = new Carbon($val->HMSA_FEAC, 'America/Mexico_city');
            $deactivationDate = new Carbon($val->HMSA_FEDE, 'America/Mexico_city');

            $diffDays = $deactivationDate->diffInDays($activationDate);
            $activationDate->addDays($diffDays);

            $diffHours = $deactivationDate->diffInHours($activationDate);
            $activationDate->addHours($diffHours);
            
            $diffMinutes = $deactivationDate->diffInMinutes($activationDate);
            $activationDate->addMinutes($diffMinutes);
            
            $diffSeconds = $deactivationDate->diffInSeconds($activationDate);

            $duration = "";
            if($diffDays > 0) $duration .= "$diffDays días, ";
            if($diffHours > 0) $duration .= "$diffHours horas, ";
            if($diffMinutes > 0) $duration .= "$diffMinutes minutos, ";
            if($diffSeconds > 0) $duration .= "$diffSeconds segundos, ";

            $duration = substr($duration, 0, -2);
            $usac = DB::table('S002V01TUSUA')->select([
                'USUA_NOMB', 'USUA_APPA', 'USUA_APMA'
            ])->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $val->HMSA_USAC]
            ])->first();
            $nomUSAC = $this->functionsController->joinName($usac->USUA_NOMB, $usac->USUA_APPA, $usac->USUA_APMA);

            $usde = DB::table('S002V01TUSUA')->select([
                'USUA_NOMB', 'USUA_APPA', 'USUA_APMA'
            ])->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $val->HMSA_USDE]
            ])->first();
            $nomUSDE = $this->functionsController->joinName($usde->USUA_NOMB, $usde->USUA_APPA, $usde->USUA_APMA);

            $historyF[] = [
                "IDACTIVACION" => $val->HMSA_IDAC,
                "LINEA" => $val->HMSA_NULI,
                "USUARIOACTIVO" => $nomUSAC . " (" . $val->HMSA_USAC . ")",
                "FECHAACTIVACION" => $val->HMSA_FEAC,
                "MOTIVOS" => $val->HMSA_MOAC,
                "USUARIODESACTIVO" => $nomUSDE . " (" . $val->HMSA_USDE . ")",
                "FECHADESACTIVACION" => $val->HMSA_FEDE,
                "JUSTIFICACION" => $val->HMSA_JUDE,
                "DURACION" => $duration
            ];
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F05MOMA',
            'S002V01P02HIMA',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el historial de mantenimientos.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $historyF);
    }

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $maintenanceModeExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json');
        if(!$maintenanceModeExists){
            return $this->responseController->makeResponse(true, 'El archivo de mantenimiento no fue encontrado.', [], 500);
        }

        $maintenanceStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\maintenance_mode.json');
        $maintenanceArr = json_decode($maintenanceStr, true);

        $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,
            'S002V01M01ADSI',
            'S002V01F05MOMA',
            'S002V01P02HIMA',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el estado actual del modo mantenimiento.",
            $idUser,
            $nowStr
        );

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $emailServers = DB::table('S002V01TSCEL')->where('SCEL_NULI', '=', $line)->orderBy('SCEL_PRIO')->get()->all();
        $serversArr = [];
        foreach($emailServers as $server){
            $usal = DB::table('S002V01TUSUA')->where([
                ['USUA_IDUS', '=', $server->SCEL_USAL],
                ['USUA_NULI', '=', $line],
            ])->first();
            $usalName = $this->functionsController->joinName($usal->USUA_NOMB, $usal->USUA_APPA, $usal->USUA_APMA);
            
            $usmo = DB::table('S002V01TUSUA')->where([
                ['USUA_IDUS', '=', $server->SCEL_USMO],
                ['USUA_NULI', '=', $line],
            ])->first();
            $usmoName = is_null($usmo) ? '-' : $this->functionsController->joinName($usmo->USUA_NOMB, $usmo->USUA_APPA, $usmo->USUA_APMA);

            $serversArr[] = [
                'USUARIO' => $server->SCEL_USUA,
                'HOST' => $server->SCEL_HOST,
                'PRIORIDAD' => $server->SCEL_PRIO,
                'USRREG' => "$usalName (" . $server->SCEL_USAL . ")",
                'FECREG' => $server->SCEL_FEAL,
                'USRMOD' => is_null($usmo) ? $usmoName : "$usalName (" . $server->SCEL_USMO . ")",
                'FECMOD' => is_null($server->SCEL_FEMO) ? '-' : $server->SCEL_FEMO,
                'ESTADO' => $server->SCEL_ESCO,
            ];
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F07CCEL',
            'S002V01P01CNSC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los servidores de correo electrónico registrados.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $serversArr);
    }

    public function registerEmailServer(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'user' => 'required|string|max:50',
            'host' => 'required|string|max:50',
            'priority' => 'required|integer|between:1,100',
            'smtpsec' => 'string|max:50',
            'port' => 'required|string|max:10',
            'password' => 'required|string|max:2000',
            'timeout' => 'required|string|max:3',
            'smtpaut' => 'required|string|max:2',
            'portals' => 'required|json',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']],
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $smtpsec = isset($form['smtpsec']) ? $form['smtpsec'] : null;

        DB::table('S002V01TSCEL')->insert([
            'SCEL_NULI' => $form['linea'],
            'SCEL_USUA' => $form['user'],
            'SCEL_HOST' => $form['host'],
            'SCEL_PRIO' => $form['priority'],
            'SCEL_SESM' => $smtpsec,
            'SCEL_PUER' => $form['port'],
            'SCEL_CONT' => $form['password'],
            'SCEL_TIES' => $form['timeout'],
            'SCEL_AUSM' => $form['smtpaut'],
            'SCEL_ADPO' => $form['portals'],
            'SCEL_USAL' => $idUser,
            'SCEL_FEAL' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F07CCEL',
            'S002V01P01CNSC',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró el servidor $form[host]",
            $idUser,
            $nowStr
        );

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

    public function getEmailServer($host, $user, $idUser, $line){
        DB::enableQueryLog();

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

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

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

        $server = DB::table('S002V01TSCEL')->select([
            'SCEL_USUA AS USUARIO',
            'SCEL_HOST AS HOST',
            'SCEL_PRIO AS PRIORIDAD',
            'SCEL_SESM AS SEGSMTP',
            'SCEL_PUER AS PUERTO',
            'SCEL_CONT AS CONTRASENA',
            'SCEL_TIES AS TIEMPOESPERA',
            'SCEL_AUSM AS AUTSMTP',
            'SCEL_ADPO AS PORTALES'
        ])->where([
            ['SCEL_NULI', '=', $line],
            ['SCEL_USUA', '=', $user],
            ['SCEL_HOST', '=', $host],
        ])->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,
            'S002V01M01ADSI',
            'S002V01F07CCEL',
            'S002V01P01CNSC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el servidor $host.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $server);
    }

    public function updateEmailServer(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'user' => 'required|string|max:50',
            'host' => 'required|string|max:50',
            'priority' => 'required|integer|between:1,100',
            'smtpsec' => 'string|max:50',
            'port' => 'required|string|max:10',
            'password' => 'required|string|max:2000',
            'timeout' => 'required|string|max:3',
            'smtpaut' => 'required|string|max:2',
            'portals' => 'required|json',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $server = DB::table('S002V01TSCEL')->where([
            ['SCEL_NULI', '=', $form['linea']],
            ['SCEL_USUA', '=', $form['user']],
            ['SCEL_HOST', '=', $form['host']],
        ])->first();
        
        if(is_null($server)){
            return $this->responseController->makeResponse(true, 'El servidor que desea modificar no existe.', [], 404);
        }

        $smtpsec = isset($form['smtpsec']) ? $form['smtpsec'] : null;
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TSCEL')->where([
            ['SCEL_NULI', '=', $form['linea']],
            ['SCEL_USUA', '=', $form['user']],
            ['SCEL_HOST', '=', $form['host']],
        ])->update([
            'SCEL_PRIO' => $form['priority'],
            'SCEL_SESM' => $smtpsec,
            'SCEL_PUER' => $form['port'],
            'SCEL_CONT' => $form['password'],
            'SCEL_TIES' => $form['timeout'],
            'SCEL_AUSM' => $form['smtpaut'],
            'SCEL_ADPO' => $form['portals'],
            'SCEL_USMO' => $idUser,
            'SCEL_FEMO' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F07CCEL',
            'S002V01P01CNSC',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el servidor $form[host]",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $server = DB::table('S002V01TSCEL')->where([
            ['SCEL_NULI', '=', $form['linea']],
            ['SCEL_USUA', '=', $form['user']],
            ['SCEL_HOST', '=', $form['host']],
        ])->first();
        
        if(is_null($server)){
            return $this->responseController->makeResponse(true, 'El servidor que desea eliminar no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TSCEL')->where([
            ['SCEL_NULI', '=', $form['linea']],
            ['SCEL_USUA', '=', $form['user']],
            ['SCEL_HOST', '=', $form['host']],
        ])->update([
            'SCEL_ESCO' => 'Eliminado',
            'SCEL_USMO' => $idUser,
            'SCEL_FEMO' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F07CCEL',
            'S002V01P01CNSC',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el servidor $form[host]",
            $idUser,
            $nowStr
        );

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

    public function deactivateEmailServer(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'user' => 'required|string|max:50',
            'host' => 'required|string|max:50',
            'state' => 'required|string|in:Activo,Inactivo',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $server = DB::table('S002V01TSCEL')->where([
            ['SCEL_NULI', '=', $form['linea']],
            ['SCEL_USUA', '=', $form['user']],
            ['SCEL_HOST', '=', $form['host']],
        ])->first();
        
        if(is_null($server)){
            return $this->responseController->makeResponse(true, 'El servidor que desea modificar no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TSCEL')->where([
            ['SCEL_NULI', '=', $form['linea']],
            ['SCEL_USUA', '=', $form['user']],
            ['SCEL_HOST', '=', $form['host']],
        ])->update([
            'SCEL_ESCO' => $form['state'],
            'SCEL_USMO' => $idUser,
            'SCEL_FEMO' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F07CCEL',
            'S002V01P01CNSC',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") cambió el estado del servidor $form[host]",
            $idUser,
            $nowStr
        );

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

    public function registerEmailTemplate(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'module' => 'required|string|max:25',
            'submodule' => 'string|max:25',
            'function' => 'required|string|max:25',
            'screen' => 'required|string|max:25',
            'subject' => 'required|string|max:50',
            'body' => 'required|string',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $module = DB::table('S002V01TMODU')->where([
            ['MODU_IDMO', '=', $form['module']],
            ['MODU_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($module)){
            return $this->responseController->makeResponse(true, 'El módulo seleccionado no existe.', [], 404);
        }

        $hasSubmodule = isset($form['submodule']);
        if($hasSubmodule){
            $submodule = DB::table('S002V01TSUBM')->where([
                ['SUBM_IDSM', '=', $form['submodule']],
                ['SUBM_IDMO', '=', $form['module']],
                ['SUBM_NULI', '=', $form['linea']],
            ])->first();
        
            if(is_null($submodule)){
                return $this->responseController->makeResponse(true, 'El submódulo seleccionado no existe.', [], 404);
            }
        }

        $submodule = $hasSubmodule ? $form['submodule'] : null;
        $function = DB::table('S002V01TFUNC')->where([
            ['FUNC_NULI', '=', $form['linea']],
            ['FUNC_IDFU', '=', $form['function']],
            ['FUNC_IDMO', '=', $form['module']],
            ['FUNC_IDSM', '=', $submodule],
        ])->first();
        
        if(is_null($function)){
            return $this->responseController->makeResponse(true, 'La función seleccionada no existe.', [], 404);
        }

        $screen = DB::table('S002V01TPANT')->where([
            ['PANT_NULI', '=', $form['linea']],
            ['PANT_IDPA', '=', $form['screen']],
            ['PANT_IDFU', '=', $form['function']],
        ])->first();
        
        if(is_null($screen)){
            return $this->responseController->makeResponse(true, 'La pantalla seleccionada no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $idPlan = DB::table('S002V01TPCEL')->insertGetId([
            'PCEL_NULI' => $form['linea'],
            'PCEL_IDMO' => $form['module'],
            'PCEL_IDSM' => $submodule,
            'PCEL_IDFU' => $form['function'],
            'PCEL_IDPA' => $form['screen'],
            'PCEL_ASCO' => $form['subject'],
            'PCEL_CUCO' => $form['body'],
            'PCEL_USRE' => $idUser,
            'PCEL_FERE' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F08CPCE',
            'S002V01P02NPEP',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró la plantilla $form[subject] ($idPlan)",
            $idUser,
            $nowStr
        );

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $emailTemplates = DB::table('S002V01TPCEL')->select([
            'PCEL_IDPL AS IDPLANTILLA',
            'PCEL_NULI AS LINEA',
            'MODU_NOMO AS NOMBREMODULO',
            'SUBM_NOMB AS NOMBRESUBMODULO',
            'FUNC_NOMB AS NOMBREFUNCION',
            'PANT_NOMB AS NOMBREPANTALLA',
            'PCEL_ASCO AS ASUNTO',
            'PCEL_CUCO AS CUERPO',
            'PCEL_ESTA AS ESTADO',
            'PCEL_USRE AS USUARIOREGISTRA',
            'PCEL_FERE AS FECHAREGISTRO',
            'PCEL_USMO AS USUARIOMODIFICA',
            'PCEL_FEMO AS FECHAMODIFICACION'
        ])->join('S002V01TMODU', 'MODU_IDMO', '=', 'PCEL_IDMO')
        ->leftJoin('S002V01TSUBM', 'SUBM_IDSM', '=', 'PCEL_IDSM')
        ->join('S002V01TFUNC', 'FUNC_IDFU', '=', 'PCEL_IDFU')
        ->join('S002V01TPANT', 'PANT_IDPA', '=', 'PCEL_IDPA')->where([
            ['PCEL_NULI', '=', $line]
        ])->orderBy('PCEL_IDPL', 'asc')->get()->all();

        $emailTemplatesF = [];
        foreach($emailTemplates as $template){
            $usrTemplate = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $template->USUARIOREGISTRA],
            ])->first();

            $idus = $template->USUARIOREGISTRA;
            $template->USUARIOREGISTRA = $this->functionsController->joinName(
                $usrTemplate->USUA_NOMB, 
                $usrTemplate->USUA_APPA, 
                $usrTemplate->USUA_APMA
            ) . " ($idus)";

            if(!is_null($template->USUARIOMODIFICA)){
                $usrTemplate = DB::table('S002V01TUSUA')->where([
                    ['USUA_NULI', '=', $line],
                    ['USUA_IDUS', '=', $template->USUARIOMODIFICA],
                ])->first();
    
                $idus = $template->USUARIOMODIFICA;
                $template->USUARIOMODIFICA = $this->functionsController->joinName(
                    $usrTemplate->USUA_NOMB, 
                    $usrTemplate->USUA_APPA, 
                    $usrTemplate->USUA_APMA
                ) . " ($idus)";
            }
            
            $emailTemplatesF[] = $template;
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F09MACS',
            'S002V01P01HIPL',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las plantillas de correo electrónico registradas.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $emailTemplatesF);
    }

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $id = $this->encryptionController->shortDec($id);
        if(!$id){
            return $this->responseController->makeResponse(true, 'El ID de la plantilla consultada no está encriptado correctamente.', [], 400);
        }

        $emailTemplate = DB::table('S002V01TPCEL')->select([
            'PCEL_IDPL AS IDPLANTILLA',
            'PCEL_IDMO AS MODULO',
            'PCEL_IDSM AS SUBMODULO',
            'PCEL_IDFU AS FUNCION',
            'PCEL_IDPA AS PANTALLA',
            'PCEL_ASCO AS ASUNTO',
            'PCEL_CUCO AS CUERPO'
        ])->where([
            ['PCEL_IDPL', '=', $id],
            ['PCEL_NULI', '=', $line],
        ])->first();

        if(is_null($emailTemplate)){
            return $this->responseController->makeResponse(true, 'La plantilla solicitada 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);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M01ADSI',
            'S002V01F09MACS',
            'S002V01P01HIPL',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la plantilla " . $emailTemplate->ASUNTO . " ($id).",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $emailTemplate);
    }

    public function updateEmailTemplate(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'id_template' => 'required|string',
            'module' => 'required|string|max:25',
            'submodule' => 'string|max:25',
            'function' => 'required|string|max:25',
            'screen' => 'required|string|max:25',
            'subject' => 'required|string|max:50',
            'body' => 'required|string',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }
        
        $idTemplate = $this->encryptionController->decrypt($form['id_template']);
        if(!$idTemplate){
            return $this->responseController->makeResponse(true, 'El ID de la plantilla no fue encriptado correctamente.', [], 400);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $submodule = isset($form['submodule']) ? $form['submodule'] : null;
        DB::table('S002V01TPCEL')->where([
            ['PCEL_NULI', '=', $form['linea']],
            ['PCEL_IDPL', '=', $idTemplate]
        ])->update([
            'PCEL_IDMO' => $form['module'],
            'PCEL_IDSM' => $submodule,
            'PCEL_IDFU' => $form['function'],
            'PCEL_IDPA' => $form['screen'],
            'PCEL_ASCO' => $form['subject'],
            'PCEL_CUCO' => $form['body'],
            'PCEL_USMO' => $idUser,
            'PCEL_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F08CPCE',
            'S002V01P02NPEP',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la plantilla $form[subject] ($idTemplate)",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }
        
        $idTemplate = $this->encryptionController->decrypt($form['id_template']);
        if(!$idTemplate){
            return $this->responseController->makeResponse(true, 'El ID de la plantilla no fue encriptado correctamente.', [], 400);
        }
        
        $template = DB::table('S002V01TPCEL')->where([
            ['PCEL_IDPL', '=', $idTemplate],
            ['PCEL_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'La plantilla solicitada no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TPCEL')->where([
            ['PCEL_IDPL', '=', $idTemplate],
            ['PCEL_NULI', '=', $form['linea']]
        ])->update([
            'PCEL_ESTA' => 'Eliminado',
            'PCEL_USMO' => $idUser,
            'PCEL_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F08CPCE',
            'S002V01P01HIPL',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la plantilla ($idTemplate)",
            $idUser,
            $nowStr
        );

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

    public function saveCatalogue(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'tipo' => 'required|string|max:35',
            'adjuntos' => 'required|json',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }
        
        $allowedFiles = ["Colonias", "Códigos postales", "Estados", "Localidades", "Municipios"];
        if(!in_array($form['tipo'], $allowedFiles)){
            return $this->responseController->makeResponse(true, "El tipo de catálogo no está soportado.", [], 400);
        }

        $attachedFiles = json_decode($form['adjuntos'], true);
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $attachedArr = [];
        foreach($attachedFiles as $file){
            $idFile = $file['id'];
            $idFile = $this->encryptionController->decrypt($idFile);
            if(!$idFile){
                return $this->responseController->makeResponse(true, "El ID del archivo $file[name] no fue encriptado correctamente", [], 400);
            }

            $fileObj = DB::table('S002V01TARTE')->where([
                ['ARTE_IDAR', '=', $idFile],
                ['ARTE_NULI', '=', $form['linea']]
            ])->first();

            if(is_null($fileObj)){
                return $this->responseController->makeResponse(true, "El ID del archivo $file[name] no existe", [], 404);
            }else if($fileObj->ARTE_ESTA == 'Eliminado'){
                return $this->responseController->makeResponse(true, "El archivo $file[name] está eliminado", [], 404);
            }

            $fileSaved = $this->moveFinalFile($form['linea'], 'CA', $fileObj, 'S002V01M01ADSI', 'S002V01F10AGCA', 'S002V01P02NUCA');
            if(!$fileSaved[0]){
                return $this->responseController->makeResponse(true, "El archivo no pudo guardarse: $fileSaved[1]", [], 500);
            }
            
            $attachedArr[] = $this->encryptionController->encrypt($fileSaved[1]);

            DB::table('S002V01TARTE')->where([
                ['ARTE_IDAR', '=', $idFile],
                ['ARTE_NULI', '=', $form['linea']],
            ])->update([
                'ARTE_ESTA' => 'Eliminado',
                'ARTE_USMO' => $idUser,
                'ARTE_FEMO' => $nowStr
            ]);
        }

        $lastVersionObj = DB::table('S002V01TCATA')->where([
            ['CATA_NULI', '=', $form['linea']],
            ['CATA_TICA', '=', $form['tipo']]
        ])->orderBy('CATA_IDCA', 'desc')->first();

        $lastVersion = 0;
        if(is_null($lastVersionObj)){
            $lastVersion = 1;
        }else{
            DB::table('S002V01TCATA')->where([
                ['CATA_NULI', '=', $form['linea']],
                ['CATA_IDCA', '=', $lastVersionObj->CATA_IDCA],
            ])->update([
                'CATA_ESTA' => 'Obsoleto',
            ]);

            $lastVersion = intval($lastVersionObj->CATA_VERS) + 1;
        }

        $attachedStr = json_encode($attachedArr);
        DB::table('S002V01TCATA')->insert([
            'CATA_NULI' => $form['linea'],
            'CATA_TICA' => $form['tipo'],
            'CATA_VERS' => $lastVersion,
            'CATA_ARRE' => $attachedStr,
            'CATA_USRE' => $idUser,
            'CATA_FERE' => $nowStr,
        ]);

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

        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F10AGCA',
            'S002V01P02NUCA',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró un nuevo catálogo.",
            $idUser,
            $nowStr,
        );

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

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $types = ['Colonias', 'Códigos postales', 'Estados', 'Localidades', 'Municipios'];
        if(!in_array($type, $types)){
            return $this->responseController->makeResponse(true, 'El tipo de catálogo no está soportado.', [], 404);
        }

        $catalogueHistory = DB::table('S002V01TCATA')->select([
            'CATA_IDCA AS IDCATALOGO',
            'CATA_VERS AS VERSION',
            'CATA_ARRE AS ARCHIVO',
            'CATA_ESTA AS ESTADO',
            'CATA_USRE AS USUARIOREGISTRA',
            'CATA_FERE AS FECHAREGISTRO',
        ])->where([
            ['CATA_NULI', '=', $line],
            ['CATA_TICA', '=', $type],
        ])->get()->all();

        $cont = 0;
        foreach($catalogueHistory as $reg){
            $usrReg = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $reg->USUARIOREGISTRA]
            ])->first();

            $catalogueHistory[$cont]->USUARIOREGISTRA = $this->functionsController->joinName(
                $usrReg->USUA_NOMB,
                $usrReg->USUA_APPA,
                $usrReg->USUA_APMA,
            ) . " (" . $reg->USUARIOREGISTRA . ")";

            $cont++;
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F10AGCA',
            'S002V01P01HICA',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el historial de catálogos $type.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $catalogueHistory);
    }

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $iconsStr = file_get_contents("C:\\inetpub\\wwwroot\\sam\\storage\\app\\files\\icons.json");
        $iconsArr = json_decode($iconsStr, true);
        $icons = $iconsArr['icons'];

        $iconsF = [];
        foreach($icons as $icon){
            if(!array_key_exists($icon['name'], $iconsF)){
                $iconsF[$icon['name']] = [
                    'name' => $icon['name'],
                    'categorie' => $icon['categories'],
                ];
            }
        }

        $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 íconos de Material.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', array_values($iconsF));
    }

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

        $idUser = $this->encryptionController->shortDec($idUser);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta 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);
        }

        $systemParamsExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
        if(!$systemParamsExists){
            return $this->responseController->makeResponse(true, 'El archivo de parámetros del sistema no fue encontrado.', [], 500);
        }

        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
        $paramsArr = json_decode($paramsStr, true);

        $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,
            'S002V01M01ADSI',
            'S002V01F05MOMA',
            'S002V01P02HIMA',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el estado actual del modo mantenimiento.",
            $idUser,
            $nowStr
        );

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

    public function saveLoginImage(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'tipo' => 'required|string|in:image,background',
            'archivo' => 'required|string',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $systemParamsExists = file_exists('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
        if(!$systemParamsExists){
            return $this->responseController->makeResponse(true, 'El archivo de parámetros del sistema no fue encontrado.', [], 500);
        }

        $paramsStr = file_get_contents('C:\inetpub\wwwroot\sam\storage\app\files\system-params.json');
        $paramsArr = json_decode($paramsStr, true);
        
        $actualImage = $paramsArr["login_params"]["login_$form[tipo]"];
        $replaceImage = $this->encryptionController->decrypt($form['archivo']);
        if(!$replaceImage){
            return $this->responseController->makeResponse(true, 'El ID de la imágen enviada no fue encriptado correctamente.', [], 500);
        }

        $imageObj = DB::table('S002V01TARTE')->where([
            ['ARTE_IDAR', '=', $replaceImage],
            ['ARTE_NULI', '=', $form['linea']]
        ])->first();

        $ubiImgTmp = $imageObj->ARTE_UBTE;
        if(!file_exists($ubiImgTmp)){
            return $this->responseController->makeResponse(true, 'El archivo de la imagen enviada no existe.', [], 500);
        }

        $ubiImgAct = "C:\\inetpub\\wwwroot\\sam\\public\\assets\\$actualImage";
        if(!file_exists($ubiImgAct)){
            return $this->responseController->makeResponse(true, 'La imagen actual no existe.', [], 500);
        }

        $timestamp = Carbon::now('America/Mexico_city')->timestamp;

        rename($ubiImgAct, "C:\\inetpub\\wwwroot\\sam\\public\\assets\\UPDATED_$timestamp.png");
        copy($ubiImgTmp, $ubiImgAct);

        $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(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P04EILO',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") cambió la apariencia del login.",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $moduleIconsStr = $form['module_icons'];
        $moduleIconsDec = $this->encryptionController->shortDec($moduleIconsStr);
        if(!$moduleIconsDec){
            return $this->responseController->makeResponse(true, 'El arreglo de módulos no fue encriptado correctamente.', [], 400);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $moduleIconsArr = json_decode($moduleIconsDec, true);
        foreach($moduleIconsArr as $modIcon){
            DB::table('S002V01TMODU')->where([
                ['MODU_NULI', '=', $form['linea']],
                ['MODU_IDMO', '=', $modIcon['IDMODULO']]
            ])->update([
                'MODU_ICON' => $modIcon['ICONOMODULO'],
                'MODU_USMO' => $idUser,
                'MODU_FEMO' => $nowStr,
            ]);
        }

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P05EIMO',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") cambió los íconos de los módulos.",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $submoduleIconsDec = $this->encryptionController->shortDec($form['submodule_icons']);
        if(!$submoduleIconsDec){
            return $this->responseController->makeResponse(true, 'El arreglo de submódulos no fue encriptado correctamente.', [], 400);
        }

        $submodulesArr = json_decode($submoduleIconsDec, true);
        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        foreach($submodulesArr as $module=>$submodules){
            foreach($submodules as $submodule){
                DB::table('S002V01TSUBM')->where([
                    ['SUBM_NULI', '=', $form['linea']],
                    ['SUBM_IDSM', '=', $submodule['IDSUBMODULO']],
                    ['SUBM_IDMO', '=', $module],
                ])->update([
                    'SUBM_ICON' => $submodule['ICONOSUBMODULO'],
                    'SUBM_USMO' => $idUser,
                    'SUBM_FEMO' => $nowStr,
                ]);
            }
        }

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P06EISU',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") cambió los íconos de los submódulos.",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $moduleFunctionIconsDec = $this->encryptionController->shortDec($form['module_functions_icons']);
        if(!$moduleFunctionIconsDec){
            return $this->responseController->makeResponse(true, 'El arreglo de funciones por módulo no fue encriptado correctamente.', [], 400);
        }

        $submoduleFunctionIconsDec = $this->encryptionController->shortDec($form['submodule_functions_icons']);
        if(!$submoduleFunctionIconsDec){
            return $this->responseController->makeResponse(true, 'El arreglo de funciones por submódulo no fue encriptado correctamente.', [], 400);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $moduleFunctionIconsArr = json_decode($moduleFunctionIconsDec, true);
        foreach($moduleFunctionIconsArr as $module=>$functions){
            foreach($functions as $function){
                DB::table('S002V01TFUNC')->where([
                    ['FUNC_NULI', '=', $form['linea']],
                    ['FUNC_IDFU', '=', $function['IDFUNCION']],
                    ['FUNC_IDMO', '=', $module],
                    ['FUNC_IDSM', '=', null],
                ])->update([
                    'FUNC_ICON' => $function['ICONOFUNCION'],
                    'FUNC_USMO' => $idUser,
                    'FUNC_FEMO' => $nowStr,
                ]);
            }
        }

        $submoduleFunctionIconsArr = json_decode($submoduleFunctionIconsDec, true);
        foreach($submoduleFunctionIconsArr as $module=>$submodules){
            foreach($submodules as $submodule=>$functions){
                foreach($functions as $function){
                    DB::table('S002V01TFUNC')->where([
                        ['FUNC_NULI', '=', $form['linea']],
                        ['FUNC_IDFU', '=', $function['IDFUNCION']],
                        ['FUNC_IDMO', '=', $module],
                        ['FUNC_IDSM', '=', $submodule],
                    ])->update([
                        'FUNC_ICON' => $function['ICONOFUNCION'],
                        'FUNC_USMO' => $idUser,
                        'FUNC_FEMO' => $nowStr,
                    ]);
                }
            }
        }

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P07EIFU',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") cambió los íconos de las funciones.",
            $idUser,
            $nowStr
        );

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

    public function getModuleFunctions($idMod, $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);
        }

        $mod = DB::table('S002V01TMODU')->where([
            ['MODU_NULI', '=', $line],
            ['MODU_IDMO', '=', $idMod]
        ])->first();

        if(is_null($mod)){
            return $this->responseController->makeResponse(true, 'El módulo consultado no existe', [], 404);
        }

        $functions = DB::table('S002V01TFUNC')->where([
            ['FUNC_NULI', '=', $line],
            ['FUNC_IDMO', '=', $idMod],
            ['FUNC_IDSM', '=', null],
        ])->select([
            'FUNC_IDFU AS IDFUNCION',
            'FUNC_NOMB AS NOMBREFUNCION',
            'FUNC_ICON AS ICONOFUNCION'
        ])->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ó las funciones del módulo '" . $mod->MODU_NOMO . "'.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $functions);
    }

    public function getSubmodules($idMod, $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);
        }

        $mod = DB::table('S002V01TMODU')->where([
            ['MODU_NULI', '=', $line],
            ['MODU_IDMO', '=', $idMod]
        ])->first();

        if(is_null($mod)){
            return $this->responseController->makeResponse(true, 'El módulo consultado no existe', [], 404);
        }

        $submodules = DB::table('S002V01TSUBM')->where([
            ['SUBM_NULI', '=', $line],
            ['SUBM_IDMO', '=', $idMod],
        ])->select([
            'SUBM_IDSM AS IDSUBMODULO',
            'SUBM_NOMB AS NOMBRESUBMODULO',
            'SUBM_ICON AS ICONOSUBMODULO'
        ])->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 submódulos del módulo '" . $mod->MODU_NOMO . "'.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $submodules);
    }

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TLISC')->insert([
            'LISC_NULI' => $form['linea'],
            'LISC_NOSC' => $form['scada_name'],
            'LISC_USRE' => $idUser,
            'LISC_FERE' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P02RESC',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró el SCADA $form[scada_name].",
            $idUser,
            $nowStr
        );

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

    public function getSCADAList($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);
        }

        $list = DB::table('S002V01TLISC')->select([
            'LISC_IDSC AS IDSCADA',
            'LISC_NOSC AS NOMBRESCADA',
            'LISC_ESTA AS ESTATUS',
            'LISC_USRE AS USUARIOREGISTRO',
            'LISC_FERE AS FECHAREGISTRO',
            'LISC_USMO AS USUARIOMODIFICO',
            'LISC_FEMO AS FECHAMODIFICACION',
        ])->where('LISC_NULI', '=', $line)->get()->all();

        foreach($list as $item){
            $usrReg = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $item->USUARIOREGISTRO],
            ])->first();
            $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA) . " (" . $item->USUARIOREGISTRO . ")";
            $item->USUARIOREGISTRO = $nameReg;

            $usrMod = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $item->USUARIOMODIFICO],
            ])->first();
            if(!is_null($usrMod)){
                $nameMod = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA) . " (" . $item->USUARIOMODIFICO . ")";
                $item->USUARIOMODIFICO = $nameMod;
            }
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P01ADSC',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los SCADA registrados en el sistema.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $list);
    }

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $idSCADA = $this->encryptionController->decrypt($form['id_scada']);
        if(!$idSCADA){
            return $this->responseController->makeResponse(true, 'El ID del SCADA no fue encriptado correctamente.', [], 400);
        }

        $scada = DB::table('S002V01TLISC')->where([
            ['LISC_NULI', '=', $form['linea']],
            ['LISC_IDSC', '=', $idSCADA],
        ])->first();
        
        if(is_null($scada)){
            return $this->responseController->makeResponse(true, 'El SCADA solicitado no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TLISC')->where([
            ['LISC_NULI', '=', $form['linea']],
            ['LISC_IDSC', '=', $idSCADA],
        ])->update([
            'LISC_NOSC' => $form['scada_name'],
            'LISC_USMO' => $idUser,
            'LISC_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P02RESC',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el SCADA $form[scada_name] ($idSCADA).",
            $idUser,
            $nowStr
        );

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

    public function deleteSCADA(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'id_scada' => '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
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $idSCADA = $this->encryptionController->decrypt($form['id_scada']);
        if(!$idSCADA){
            return $this->responseController->makeResponse(true, 'El ID del SCADA no fue encriptado correctamente.', [], 400);
        }

        $scada = DB::table('S002V01TLISC')->where([
            ['LISC_NULI', '=', $form['linea']],
            ['LISC_IDSC', '=', $idSCADA],
        ])->first();
        
        if(is_null($scada)){
            return $this->responseController->makeResponse(true, 'El SCADA solicitado no existe.', [], 404);
        }

        $tokensSCADA = DB::table('S002V01TTASW')->where([
            ['TASW_NULI', '=', $form['linea']],
            ['TASW_IDSC', '=', $idSCADA],
        ])->get()->all();

        if(!empty($tokensSCADA)){
            return $this->responseController->makeResponse(true, 'No se pudo eliminar el SCADA porque tiene tokens asignados.', [], 400);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TLISC')->where([
            ['LISC_NULI', '=', $form['linea']],
            ['LISC_IDSC', '=', $idSCADA],
        ])->update([
            'LISC_ESTA' => 'Eliminado',
            'LISC_USMO' => $idUser,
            'LISC_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P01ADSC',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el SCADA " . $scada->LISC_NOSC . " ($idSCADA).",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['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', '=', $form['linea']]
        ])->first();

        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
        }
        
        $id = $this->encryptionController->decrypt($form['id_scada']);
        if(!$id){
            return $this->responseController->makeResponse(true, 'El ID del SCADA no está encriptado correctamente', [], 400);
        }

        $scada = DB::table('S002V01TLISC')->where([
            ['LISC_NULI', '=', $form['linea']],
            ['LISC_IDSC', '=', $id],
        ])->first();

        if(is_null($scada)){
            return $this->responseController->makeResponse(true, 'El SCADA consultado no existe', [], 404);
        }

        $now = Carbon::now('America/Mexico_city');
        $iat = $now->timestamp;
        $cad = $now->addYear()->timestamp;

        $payload = [
            "iss" => $scada->LISC_IDSC,
            "aud" => "dominio.syp.mx",
            "iat" => $iat,
            "cad" => $cad
        ];

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

        DB::table('S002V01TTASW')->insert([
            'TASW_NULI' => $form['linea'],
            'TASW_IDSC' => $scada->LISC_IDSC,
            'TASW_TOKE' => $token,
            'TASW_DETO' => $form['descripcion'],
            'TASW_TIMO' => "PRUEBA",
            'TASW_USRE' => $idUser,
            'TASW_FERE' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P04GETO',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró y asignó el token \"$token\" al SCADA \"" . $scada->LISC_NOSC . " ($id)\".",
            $idUser,
            $nowStr
        );

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

    public function getGeneratedTokens($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);
        }

        $tokens = DB::table('S002V01TTASW')->join('S002V01TLISC', 'LISC_IDSC', '=', 'TASW_IDSC')->select([
            'LISC_NOSC AS NOMBRESCADA',
            'TASW_DETO AS DESCRIPCION',
            'TASW_ESTA AS ESTATUS',
            'TASW_USRE AS USUARIOREGISTRO',
            'TASW_FERE AS FECHAREGISTRO',
            'TASW_USMO AS USUARIOMODIFICACION',
            'TASW_FEMO AS FECHAMODIFICACION',
            'TASW_IDSC AS IDSCADA',
            'TASW_TOKE AS TOKEN'
        ])->where([
            ['TASW_NULI', '=', $line],
            ['LISC_ESTA', '=', 'Activo'],
        ])->get()->all();

        foreach($tokens as $token){
            $usre = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $token->USUARIOREGISTRO]
            ])->first();
            $usreName = $this->functionsController->joinName($usre->USUA_NOMB, $usre->USUA_APPA, $usre->USUA_APMA) . " (" . $token->USUARIOREGISTRO . ")";
            $token->USUARIOREGISTRO = $usreName;

            
            $usmo = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $token->USUARIOMODIFICACION]
            ])->first();
            if(!is_null($usmo)){
                $usmoName = $this->functionsController->joinName($usmo->USUA_NOMB, $usmo->USUA_APPA, $usmo->USUA_APMA) . " (" . $token->USUARIOMODIFICACION . ")";
                $token->USUARIOMODIFICACION = $usmoName;
            }

            $keyStr = $token->IDSCADA . "|" . $token->TOKEN;
            $keyEnc = $this->encryptionController->shortEnc($keyStr);
            $keyEnc = str_replace("+", "=P=", $keyEnc);
            $keyEnc = str_replace("/", "=S=", $keyEnc);

            unset($token->IDSCADA);
            unset($token->TOKEN);
            
            $token->KEY = $keyEnc;
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P03ADTO',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los tokens generados.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $tokens);
    }

    public function revokeToken(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'token_key' => '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
            );
        }

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_IDUS', '=', $idUser],
            ['USUA_NULI', '=', $form['linea']]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $tokenKey = $this->encryptionController->shortDec($form['token_key']);
        if(!$tokenKey){
            return $this->responseController->makeResponse(true, 'La llave del token solicitado no fue encriptado correctamente.', [], 400);
        }

        $keyArr = explode("|", $tokenKey);
        $token = DB::table('S002V01TTASW')->where([
            ['TASW_NULI', '=', $form['linea']],
            ['TASW_IDSC', '=', $keyArr[0]],
            ['TASW_TOKE', '=', $keyArr[1]]
        ])->first();

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

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TTASW')->where([
            ['TASW_NULI', '=', $form['linea']],
            ['TASW_IDSC', '=', $keyArr[0]],
            ['TASW_TOKE', '=', $keyArr[1]]
        ])->update([
            'TASW_ESTA' => 'Revocado',
            'TASW_USMO' => $idUser,
            'TASW_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P03ADTO',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") revocó el token \"$keyArr[1]\".",
            $idUser,
            $nowStr
        );

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

    public function registerWebService(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'url' => 'required|string|max:250',
            'description' => 'required|string|max:100',
        ]);

        if($validator->fails()){
            return $this->responseController->makeResponse(
                true,
                "Se encontraron uno o más errores.",
                $this->responseController->makeErrors(
                    $validator->errors()->messages()
                ),
                401
            );
        }
        
        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        $idWebService = DB::table('S002V01TLSWE')->insertGetId([
            'LSWE_NULI' => $form['linea'],
            'LSWE_URLX' => $form['url'],
            'LSWE_DESC' => $form['description'],
            'LSWE_USRE' => $idUser,
            'LSWE_FERE' => $nowStr
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P07RESW',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró el servicio web $form[url] ($idWebService).",
            $idUser,
            $nowStr
        );

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

    public function getWebServices($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);
        }

        $webServices = DB::table('S002V01TLSWE')->where([
            ['LSWE_NULI', '=', $line]
        ])->select([
            'LSWE_IDSW AS IDSERVICIO',
            'LSWE_URLX AS URL',
            'LSWE_DESC AS DESCRIPCION',
            'LSWE_ESTA AS ESTADO',
            'LSWE_USRE AS USUREG',
            'LSWE_FERE AS FECREG',
            'LSWE_USMO AS USUMOD',
            'LSWE_FEMO AS FECMOD'
        ])->get()->all();

        foreach($webServices as $webService){
            $usre = DB::table('S002V01TUSUA')->where([
                ['USUA_NULI', '=', $line],
                ['USUA_IDUS', '=', $webService->USUREG],
            ])->first();

            $usreName = $this->functionsController->joinName($usre->USUA_NOMB, $usre->USUA_APPA, $usre->USUA_APMA) . " (" . $webService->USUREG . ")";
            $webService->USUREG = $usreName;

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

            if(!is_null($usmo)){
                $usmoName = $this->functionsController->joinName($usmo->USUA_NOMB, $usmo->USUA_APPA, $usmo->USUA_APMA) . " (" . $webService->USUMOD . ")";
                $webService->USUMOD = $usmoName;
            }

            $vinculos = DB::table('S002V01TTASW')->where([
                ['TASW_NULI', '=', $line],
                ['TASW_IDSW', '=', $webService->IDSERVICIO],
            ])->get()->all();

            $webService->VINCULOS = count($vinculos);
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P06LSWE',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó los servicios web almacenados.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $webServices);
    }

    public function getRoutedTokens($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);
        }

        $list = DB::table('S002V01TTASW')
        ->join('S002V01TLISC', 'LISC_IDSC', '=', 'TASW_IDSC')
        ->leftJoin('S002V01TLSWE', 'LSWE_IDSW', '=', 'TASW_IDSW')
        ->where([
            ['TASW_NULI', '=', $line],
            ['TASW_ESTA', '!=', 'Revocado'],
        ])->get()->all();

        $arrList = [];
        foreach($list as $val){
            $key = $this->encryptionController->shortEnc($val->TASW_IDSC . "|" . $val->TASW_TOKE);
            $key = str_replace("+", "=P=", $key);
            $key = str_replace("/", "=S=", $key);
            
            $arrList[] = [
                'SCADA' => $val->LISC_NOSC . " (" . $val->LISC_IDSC . ")",
                'DESCRIPCIONSC' => $val->TASW_DETO,
                'SERVICIOWEB' => is_null($val->LSWE_IDSW) ? 'No asignado' : $val->LSWE_URLX . " (" . $val->LSWE_IDSW . ")",
                'DESCRIPCIONSW' => $val->LSWE_DESC,
                'ESTADO' => $val->TASW_ESTA,
                "KEY" => $key
            ];
        }

        $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,
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P05ESSW',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó el enrutamiento de los SCADA a los servicios web.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $arrList);
    }

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $keyStr = $this->encryptionController->shortDec($form['key']);
        if(!$keyStr){
            return $this->responseController->makeResponse(true, 'La llave del token no fue encriptada correctamente.', [], 400);
        }

        $keyArr = explode('|', $keyStr);
        if(count($keyArr) != 2){
            return $this->responseController->makeResponse(true, 'La llave del token no tiene un formato correcto.', [], 400);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TTASW')->where([
            ['TASW_NULI', '=', $form['linea']],
            ['TASW_IDSC', '=', $keyArr[0]],
            ['TASW_TOKE', '=', $keyArr[1]],
        ])->update([
            'TASW_ESTA' => $form['estado'],
            'TASW_TIMO' => 'Cambio de estado del token',
            'TASW_USMO' => $idUser,
            'TASW_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P05ESSW',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de un token.",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }
        
        $keyToken = $this->encryptionController->shortDec($form['key']);
        if(!$keyToken){
            return $this->responseController->makeResponse(true, 'La llave del token no está encriptada correctamente.', [], 400);
        }

        $keyArr = explode('|', $keyToken);
        $token = DB::table('S002V01TTASW')->where([
            ['TASW_NULI', '=', $form['linea']],
            ['TASW_IDSC', '=', $keyArr[0]],
            ['TASW_TOKE', '=', $keyArr[1]],
        ])->first();

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

        $idWS = $this->encryptionController->decrypt($form['id_web_service']);
        if(!$idWS){
            return $this->responseController->makeResponse(true, 'El ID del servicio web no fue encriptado correctamente.', [], 400);
        }

        $webService = DB::table('S002V01TLSWE')->where([
            ['LSWE_NULI', '=', $form['linea']],
            ['LSWE_IDSW', '=', $idWS]
        ])->first();
        
        if(is_null($webService)){
            return $this->responseController->makeResponse(true, 'El servicio web solicitado no existe', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TTASW')->where([
            ['TASW_NULI', '=', $form['linea']],
            ['TASW_IDSC', '=', $keyArr[0]],
            ['TASW_TOKE', '=', $keyArr[1]],
        ])->update([
            'TASW_IDSW' => $idWS,
            'TASW_TIMO' => 'Cambio de servicio web',
            'TASW_USMO' => $idUser,
            'TASW_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P05ESSW',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el servicio web de un SCADA.",
            $idUser,
            $nowStr
        );

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

    public function updateWebService(Request $request){
        DB::enableQueryLog();
        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'id_web_service' => 'required|string',
            'url' => 'required|string|max:250',
            'description' => 'required|string|max:100',
        ]);

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $idWS = $this->encryptionController->decrypt($form['id_web_service']);
        if(!$idWS){
            return $this->responseController->makeResponse(true, 'El ID del servicio web no fue encriptado correctamente.', [], 400);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TLSWE')->where([
            ['LSWE_IDSW', '=', $idWS],
            ['LSWE_NULI', '=', $form['linea']]
        ])->update([
            'LSWE_URLX' => $form['url'],
            'LSWE_DESC' => $form['description'],
            'LSWE_USMO' => $idUser,
            'LSWE_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P07RESW',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el servicio web $form[url] ($idWS).",
            $idUser,
            $nowStr
        );

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

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

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

        $form = $request->all();
        $idUser = $this->encryptionController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
        }

        $usr = DB::table('S002V01TUSUA')->where([
            ['USUA_NULI', '=', $form['linea']],
            ['USUA_IDUS', '=', $idUser]
        ])->first();
        
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
        }

        $idWS = $this->encryptionController->decrypt($form['id_web_service']);
        if(!$idWS){
            return $this->responseController->makeResponse(true, 'El ID del servicio web no fue encriptado correctamente.', [], 400);
        }

        $webService = DB::table('S002V01TLSWE')->where([
            ['LSWE_NULI', '=', $form['linea']],
            ['LSWE_IDSW', '=', $idWS]
        ])->first();
        
        if(is_null($webService)){
            return $this->responseController->makeResponse(true, 'El servicio web solicitado no existe.', [], 404);
        }

        $nowStr = Carbon::now('America/Mexico_city')->toDateTimeString();
        DB::table('S002V01TLSWE')->where([
            ['LSWE_NULI', '=', $form['linea']],
            ['LSWE_IDSW', '=', $idWS],
        ])->update([
            'LSWE_ESTA' => $form['status'],
            'LSWE_USMO' => $idUser,
            'LSWE_FEMO' => $nowStr,
        ]);

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $form['linea'],
            'S002V01M01ADSI',
            'S002V01F06ASWA',
            'S002V01P07RESW',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado servicio web de un SCADA.",
            $idUser,
            $nowStr
        );

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

    public function getBackupsList($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);
        }

        $backups = DB::table('S002V01TRESP')->select([
            'RESP_IDRE AS IDRESPALDO',
            'RESP_FERE AS FECHARESPALDO',
            'RESP_ESTA AS ESTADO',
            'RESP_LORE AS LOG',
        ])->where('RESP_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,
            'S002V01M01ADSI',
            'S002V01F12GERE',
            'S002V01P01HRES',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la lista de respaldos.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $backups);
    }

    public function getSubmoduleFunctions($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 está encriptado correctamente', [], 400);
        }

        $mod = DB::table('S002V01TMODU')->where([
            ['MODU_NULI', '=', $line],
            ['MODU_IDMO', '=', $idMod]
        ])->first();

        if(is_null($mod)){
            return $this->responseController->makeResponse(true, 'El módulo enviado no existe', [], 404);
        }

        $idSub = $this->encryptionController->shortDec($idSub);
        if(!$idSub){
            return $this->responseController->makeResponse(true, 'El ID del submódulo no está encriptado correctamente', [], 400);
        }

        $sub = DB::table('S002V01TSUBM')->where([
            ['SUBM_NULI', '=', $line],
            ['SUBM_IDSM', '=', $idSub],
            ['SUBM_IDMO', '=', $idMod],
        ])->first();

        if(is_null($sub)){
            return $this->responseController->makeResponse(true, 'El submódulo enviado no existe', [], 404);
        }

        $functions = DB::table('S002V01TFUNC')->select([
            'FUNC_IDFU AS IDFUNCION',
            'FUNC_NOMB AS NOMBREFUNCION',
            'FUNC_ICON AS ICONOFUNCION',
        ])->where([
            ['FUNC_NULI', '=', $line],
            ['FUNC_IDMO', '=', $idMod],
            ['FUNC_IDSM', '=', $idSub],
        ])->get()->all();

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

            $function->HASSCREENS = count($screens) > 0;
        }

        $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ó las funciones del submódulo " . $sub->SUBM_NOMB . " ($idSub).",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO', $functions);
    }
}