<?php
/*
    Desarrollador: Ing. Jean Jairo Benitez Meza
    Ultima Modificación: 11/04/2023
    Módulo: Analisis de Fallas
*/
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ResponseController;
use App\Http\Controllers\EncryptionController;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\FunctionsController;

class CatalogMeasuresController extends Controller
{
    private $responseController;
    private $encController;
    private $functionsController;

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

    public function getMeasures($user, $line) {
        try {
            $getMeasures = DB::table('S002V01TLIME')
                ->where('LIME_NULI', '=', $line)
                ->get([
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'LIME_ESTA AS ESTADO',
                    'LIME_USRE AS USUARIO_REGISTRA ',
                    'LIME_FERE AS FECHA_REGISTRA',
                    'LIME_USMO AS USUARIO_MODIFICA',
                    'LIME_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $getMeasures);
    }

    public function getMeasuresActives($user, $line) {
        try {
            $getMeasures = DB::table('S002V01TLIME')
                ->where('LIME_ESTA', '=', 'Activo')
                ->where('LIME_NULI', '=', $line)
                ->get([
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'LIME_USRE AS USUARIO_REGISTRA ',
                    'LIME_FERE AS FECHA_REGISTRA',
                    'LIME_USMO AS USUARIO_MODIFICA',
                    'LIME_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $getMeasures);
    }

    public function registerMeasures(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'NOMBRE_MEDIDA' => 'required|string',
            'ACRONIMO_MEDIDA' => 'required|string',
            'NUMERO_LINEA' => 'required|integer',
            'USUARIO' => 'required|string',
            'ID_MAGNITUD' =>  'required|string',
        ]);

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

        $requestData = $request->all();

        try {
            $idUser = $this->encController->decrypt($requestData['USUARIO']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: No se pudo obtener el usuario.", $th->getMessage(), 500);
        }

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

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

        try {
            $idMagnitude = $this->encController->decrypt($requestData['ID_MAGNITUD']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la magnitud relacionada no fe encriptado correctamente.", $th->getMessage(), 500);
        }

        $magnitude = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $requestData['NUMERO_LINEA']],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        try {
            $validateRegister = DB::table('S002V01TLIME')->insertGetId([
                'LIME_NULI' => $requestData['NUMERO_LINEA'],
                'LIME_MAGN' => $idMagnitude,
                'LIME_NOME' => $requestData['NOMBRE_MEDIDA'],
                'LIME_ACME' => $requestData['ACRONIMO_MEDIDA'],
                'LIME_USRE' => $idUser,
                'LIME_FERE' => $currentDate,
            ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_REG001: Ocurrió un error al insertar el formulario en la base de datos.", $th->getMessage(), 500);
        }

        if (!$validateRegister) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_REG002: No se pudo insertar el formulario en la base de datos.", [], 500);
        }

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $requestData['NUMERO_LINEA'],
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró la unidad $requestData[NOMBRE_MEDIDA] ($validateRegister).",
            $idUser,
            $currentDate
        );

        $this->functionsController->registerLog($actions, $idUser, $currentDate, $idac, $requestData['NUMERO_LINEA']);
        return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
    }

    public function updateMeasures(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'ID_MEDIDA' => 'required|string',
            'NOMBRE_MEDIDA' => 'required|string',
            'ACRONIMO_MEDIDA' => 'required|string',
            'NUMERO_LINEA' => 'required|integer',
            'USUARIO' => 'required|string',
            'ID_MAGNITUD' =>  'required|string',
        ]);

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

        $requestData = $request->all();

        try {
            $idUser = $this->encController->decrypt($request['USUARIO']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD001: No se pudo obtener el usuario.", $th->getMessage(), 500);
        }

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

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

        try {
            $idMagnitude = $this->encController->decrypt($requestData['ID_MAGNITUD']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la magnitud relacionada no fe encriptado correctamente.", $th->getMessage(), 500);
        }

        $magnitude = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $requestData['NUMERO_LINEA']],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

        try {
            $idUnit = $this->encController->decrypt($requestData['ID_MEDIDA']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la unidad seleccionada no fe encriptado correctamente.", $th->getMessage(), 500);
        }

        try {
          $validateExists = DB::table('S002V01TLIME')->where([
              ['LIME_IDME', '=', $idUnit],
              ['LIME_NULI', '=', $requestData['NUMERO_LINEA']],
              ['LIME_MAGN', '=', $idMagnitude]
          ])->first();
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD002: Ocurrió un error al consultar en la base de datos.", $th->getMessage(), 500);
        }

        if(is_null($validateExists)){
          return $this->responseController->makeResponse(true, 'La unidad de medición seleccionada no está registrada.', [], 404);
      }

        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        try {
            $validateUpdate = DB::table('S002V01TLIME')
                ->where('LIME_IDME', '=', $idUnit)
                ->where('LIME_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('LIME_MAGN', '=', $idMagnitude)
                ->update([
                    'LIME_NOME' => $requestData['NOMBRE_MEDIDA'],
                    'LIME_ACME' => $requestData['ACRONIMO_MEDIDA'],
                    'LIME_USMO' => $idUser,
                    'LIME_FEMO' => $currentDate,
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD004: Ocurrió un error al modificar el formulario en la base de datos.", $th, 500);
        }

        if ( !$validateUpdate ) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD005: No se pudo modificar el formulario en la base de datos.", [], 500);
        }

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $requestData['NUMERO_LINEA'],
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la unidad de medida #$idUnit.",
            $idUser,
            $currentDate
        );

        $this->functionsController->registerLog($actions, $idUser, $currentDate, $idac, $requestData['NUMERO_LINEA']);
        return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
    }

    public function deleteMeasures(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'ID_MEDIDA' => 'required|string',
            'NUMERO_LINEA' => 'required|integer',
            'USUARIO' => 'required|string',
            'ID_MAGNITUD' =>  'required|string',
        ]);

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

        $requestData = $request->all();

        try {
          $idUser = $this->encController->decrypt($request['USUARIO']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL001: No se pudo obtener el usuario.", [], 500);
        }

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

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

        try {
            $idMagnitude = $this->encController->decrypt($requestData['ID_MAGNITUD']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la magnitud relacionada no fe encriptado correctamente.", $th->getMessage(), 500);
        }

        $magnitude = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $requestData['NUMERO_LINEA']],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

        try {
            $idUnit = $this->encController->decrypt($requestData['ID_MEDIDA']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: El ID de la unidad seleccionada no fe encriptado correctamente.", $th->getMessage(), 500);
        }

        try {
          $validateExists = DB::table('S002V01TLIME')->where([
              ['LIME_IDME', '=', $idUnit],
              ['LIME_NULI', '=', $requestData['NUMERO_LINEA']],
              ['LIME_MAGN', '=', $idMagnitude]
          ])->first();
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD002: Ocurrió un error al consultar en la base de datos.", $th->getMessage(), 500);
        }

        if(is_null($validateExists)){
            return $this->responseController->makeResponse(true, 'La unidad de medición seleccionada no está registrada.', [], 404);
        }

        $now = $this->functionsController->now();
        $currentDate = $now->toDateTimeString();

        try {
            $validateDelete = DB::table('S002V01TLIME')
                ->where('LIME_IDME', '=', $idUnit)
                ->where('LIME_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('LIME_MAGN', '=', $idMagnitude)
                ->update([
                    'LIME_ESTA' => 'Eliminado',
                    'LIME_USMO' => $idUser,
                    'LIME_FEMO' => $currentDate,
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL004: Ocurrió un error al eliminar la medida base de datos.", $th, 500);
        }
        if (!$validateDelete) {
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_DEL005: No se pudo eliminar la medida en la base de datos..", [], 500);
        }

        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $requestData['NUMERO_LINEA'],
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la unidad de medida #$idUnit.",
            $idUser,
            $currentDate
        );

        $this->functionsController->registerLog($actions, $idUser, $currentDate, $idac, $requestData['NUMERO_LINEA']);
        return $this->responseController->makeResponse(false, "ÉXITO: Eliminación Exitosa");
    }

    public function registerMagnitude(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'magnitude' => '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->encController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
        }

        $magnitudes = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $form['linea']],
            ['MAGN_MAGN', '=', $form['magnitude']]
        ])->get()->all();

        if(count($magnitudes) > 0){
            return $this->responseController->makeResponse(true, "La magnitud $form[magnitude] ya ha sido registrada.", [], 400);
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $idMagnitude = DB::table('S002V01TMAGN')->insertGetId([
            'MAGN_NULI' => $form['linea'],
            'MAGN_MAGN' => $form['magnitude'],
            'MAGN_USRE' => $idUser,
            'MAGN_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',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Registro',
            "El usuario $name (" . $usr->USUA_IDUS . ") registró la magnitud $form[magnitude] ($idMagnitude).",
            $idUser,
            $nowStr
        );

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

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

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

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

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

        $magnitudes = DB::table('S002V01TMAGN')->select([
            'MAGN_IDMA AS ID_MAGNITUD',
            'MAGN_MAGN AS MAGNITUD',
            'MAGN_ESTA AS ESTADO',
            'MAGN_USRE AS USRREG',
            'MAGN_FERE AS FECREG',
            'MAGN_USMO AS USRMOD',
            'MAGN_FEMO AS FECMOD'
        ])->get()->all();

        foreach($magnitudes as $key=>$magnitude){
            $units = DB::table('S002V01TLIME')->where([
                ['LIME_NULI', '=', $line],
                ['LIME_MAGN', '=', $magnitude->ID_MAGNITUD]
            ])->get()->all();

            $magnitude->ID_MAGNITUD = $this->encController->encrypt($magnitude->ID_MAGNITUD);
            $magnitude->UNIDADES_RELACIONADAS = count($units);

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

            $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
            $magnitude->USRREG = $nameUsrReg . " (" . $magnitude->USRREG . ")";

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

            $magnitudes[$key] = $magnitude;
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las magnitudes registradas.",
            $idUser,
            $nowStr
        );

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

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

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

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

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

        $idMagnitude = $this->encController->decrypt($idMagnitude);
        if(!$idMagnitude){
            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
        }

        $magnitude = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $line],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

        $units = DB::table('S002V01TLIME')->select([
            'LIME_IDME AS ID_UNIDAD',
            'LIME_MAGN AS ID_MAGNITUD',
            'LIME_NOME AS NOMBRE_UNIDAD',
            'LIME_ACME AS ACRONIMO_UNIDAD',
            'LIME_ESTA AS ESTADO',
            'LIME_USRE AS USRREG',
            'LIME_FERE AS FECREG',
            'LIME_USMO AS USRMOD',
            'LIME_FEMO AS FECMOD'
        ])->where([
            ['LIME_NULI', '=', $line],
            ['LIME_MAGN', '=', $idMagnitude],
        ])->get()->all();

        foreach($units as $key=>$unit){
            $unit->ID_UNIDAD = $this->encController->encrypt($unit->ID_UNIDAD);
            $unit->ID_MAGNITUD = $this->encController->encrypt($unit->ID_MAGNITUD);

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

            $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
            $unit->USRREG = $nameUsrReg . " (" . $unit->USRREG . ")";

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

            $units[$key] = $unit;
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó las unidades relacionadas a la magnitud #$idMagnitude.",
            $idUser,
            $nowStr
        );

        $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
        return $this->responseController->makeResponse(false, 'EXITO.', $units);
    }
    
    public function getMagnitude($idMagnitude, $idUser, $line) {
        DB::enableQueryLog();

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

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

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

        $idMagnitude = $this->encController->decrypt($idMagnitude);
        if(!$idMagnitude){
            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
        }

        $magnitude = DB::table('S002V01TMAGN')->select([
            'MAGN_IDMA AS ID_MAGNITUD',
            'MAGN_MAGN AS MAGNITUD',
            'MAGN_ESTA AS ESTADO',
            'MAGN_USRE AS USRREG',
            'MAGN_FERE AS FECREG',
            'MAGN_USMO AS USRMOD',
            'MAGN_FEMO AS FECMOD'
        ])->where([
            ['MAGN_NULI', '=', $line],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

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

        $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
        $magnitude->USRREG = $nameUsrReg . " (" . $magnitude->USRREG . ")";

        if(!is_null($magnitude->USRMOD)){
            $usrMod = DB::table('S002V01TUSUA')->where([
                ['USUA_IDUS', '=', $magnitude->USRMOD],
                ['USUA_NULI', '=', $line]
            ])->first();

            $nameUsrMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
            $magnitude->USRMOD = $nameUsrMod . " (" . $magnitude->USRMOD . ")";
        }

        $units = DB::table('S002V01TLIME')->select([
            'LIME_IDME AS ID_UNIDAD',
            'LIME_MAGN AS ID_MAGNITUD',
            'LIME_NOME AS NOMBRE_UNIDAD',
            'LIME_ACME AS ACRONIMO_UNIDAD',
            'LIME_ESTA AS ESTADO',
            'LIME_USRE AS USRREG',
            'LIME_FERE AS FECREG',
            'LIME_USMO AS USRMOD',
            'LIME_FEMO AS FECMOD'
        ])->where([
            ['LIME_NULI', '=', $line],
            ['LIME_MAGN', '=', $idMagnitude],
        ])->get()->all();

        foreach($units as $key=>$unit){
            $unit->ID_UNIDAD = $this->encController->encrypt($unit->ID_UNIDAD);
            $unit->ID_MAGNITUD = $this->encController->encrypt($unit->ID_MAGNITUD);

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

            $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
            $unit->USRREG = $nameUsrReg . " (" . $unit->USRREG . ")";

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

            $units[$key] = $unit;
        }

        $magnitude->UNIDADES = $units;
        $magnitude->ID_MAGNITUD = $this->encController->encrypt($magnitude->ID_MAGNITUD);

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la magnitud #$idMagnitude.",
            $idUser,
            $nowStr
        );

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

    public function updateMagnitude(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'magnitude' => 'required|string|max:50',
            'id_magnitude' => '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->encController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
        }

        $idMagnitude = $this->encController->decrypt($form['id_magnitude']);
        if(!$idMagnitude){
            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
        }

        $magnitude = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $form['linea']],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $form['linea']],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->update([
            'MAGN_MAGN' => $form['magnitude'],
            'MAGN_USMO' => $idUser,
            'MAGN_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',
            'S002V01P09MAUN',
            'Actualización',
            "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la magnitud $form[magnitude] ($idMagnitude).",
            $idUser,
            $nowStr
        );

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

    public function deleteMagnitude(Request $request) {
        DB::enableQueryLog();

        $validator = Validator::make($request->all(), [
            'id_user' => 'required|string',
            'linea' => 'required|integer',
            'id_magnitude' => '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->encController->decrypt($form['id_user']);
        if(!$idUser){
            return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la petición no está 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 consulta no está registrado.', [], 404);
        }

        $idMagnitude = $this->encController->decrypt($form['id_magnitude']);
        if(!$idMagnitude){
            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
        }

        $magnitude = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $form['linea']],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $form['linea']],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->update([
            'MAGN_ESTA' => 'Eliminado',
            'MAGN_USMO' => $idUser,
            'MAGN_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',
            'S002V01P09MAUN',
            'Eliminación',
            "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la magnitud #$idMagnitude.",
            $idUser,
            $nowStr
        );

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

    public function getUnit($idMagnitude, $idUnit, $idUser, $line) {
        DB::enableQueryLog();

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

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

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

        $idMagnitude = $this->encController->decrypt($idMagnitude);
        if(!$idMagnitude){
            return $this->responseController->makeResponse(true, 'El ID de la magnitud relacionada no está encriptado correctamente.', [], 400);
        }

        $magnitude = DB::table('S002V01TMAGN')->where([
            ['MAGN_NULI', '=', $line],
            ['MAGN_IDMA', '=', $idMagnitude]
        ])->first();

        if(is_null($magnitude)){
            return $this->responseController->makeResponse(true, 'La magnitud relacionada no está registrada.', [], 404);
        }

        $idUnit = $this->encController->decrypt($idUnit);
        if(!$idUnit){
            return $this->responseController->makeResponse(true, 'El ID de la unidad seleccionada no está encriptado correctamente.', [], 400);
        }

        $unit = DB::table('S002V01TLIME')->select([
            'LIME_IDME AS ID_UNIDAD',
            'LIME_MAGN AS ID_MAGNITUD',
            'LIME_NOME AS NOMBRE_UNIDAD',
            'LIME_ACME AS ACRONIMO_UNIDAD',
            'LIME_ESTA AS ESTADO',
            'LIME_USRE AS USRREG',
            'LIME_FERE AS FECREG',
            'LIME_USMO AS USRMOD',
            'LIME_FEMO AS FECMOD'
        ])->where([
            ['LIME_NULI', '=', $line],
            ['LIME_MAGN', '=', $idMagnitude],
            ['LIME_IDME', '=', $idUnit],
        ])->first();

        if(is_null($unit)){
            return $this->responseController->makeResponse(true, 'La unidad seleccionada no está registrada.', [], 404);
        }

        $unit->ID_UNIDAD = $this->encController->encrypt($unit->ID_UNIDAD);
        $unit->ID_MAGNITUD = $this->encController->encrypt($unit->ID_MAGNITUD);

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

        $nameUsrReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
        $unit->USRREG = $nameUsrReg . " (" . $unit->USRREG . ")";

        if(!is_null($unit->USRMOD)){
            $usrMod = DB::table('S002V01TUSUA')->where([
                ['USUA_IDUS', '=', $unit->USRMOD],
                ['USUA_NULI', '=', $line]
            ])->first();

            $nameUsrMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
            $unit->USRMOD = $nameUsrMod . " (" . $unit->USRMOD . ")";
        }

        $now = $this->functionsController->now();
        $nowStr = $now->toDateTimeString();
        $actions = DB::getQueryLog();
        $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
        
        $idac = $this->functionsController->registerActivity(
            $line,
            'S002V01M01ADSI',
            'S002V01F11PASI',
            'S002V01P09MAUN',
            'Consulta',
            "El usuario $name (" . $usr->USUA_IDUS . ") consultó la unidad de medida #$idUnit.",
            $idUser,
            $nowStr
        );

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