<?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 SymptomListController 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 getSymptoms($user, $line) {
        try {
            $getSymptom = DB::table('S002V01TLISI')
                ->where('LISI_NULI', '=', $line)
                ->where('LIME_NULI', '=', $line)
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'LISI_IDME')
                ->get([
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION',
                    'LISI_CAUS AS CAUSA',
                    'LISI_DESC AS DESCRIPCION',
                    'LISI_SOLU AS SOLUCION',
                    'LISI_LIVA AS LIMITE_VALOR',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'LISI_ESTA AS ESTADO',
                    'LISI_USRE AS USUARIO_REGISTRA',
                    'LISI_FERE AS FECHA_REGISTRA',
                    'LISI_USMO AS USUARIO_MODIFICA',
                    'LISI_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_GET000: No se pudo realizar la consulta a la base.", 
                $th->getMessage(), 
                500
            );
        }

        $arrSymtoms = json_decode( json_encode($getSymptom), true );

        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrSymtoms);
    }

    public function getSymptomsActives($user, $line) {
        try {
            $getSymptom = DB::table('S002V01TLISI')
                ->where('LISI_NULI', '=', $line)
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_NULI', '=', $line)
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'LISI_IDME')
                ->get([
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION',
                    'LISI_CAUS AS CAUSA',
                    'LISI_DESC AS DESCRIPCION',
                    'LISI_SOLU AS SOLUCION',
                    'LISI_LIVA AS LIMITE_VALOR',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'LISI_ESTA AS ESTADO',
                    'LISI_USRE AS USUARIO_REGISTRA',
                    'LISI_FERE AS FECHA_REGISTRA',
                    'LISI_USMO AS USUARIO_MODIFICA',
                    'LISI_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_GETACTIVE000: No se pudo realizar la consulta a la base.", 
                $th->getMessage(), 
                500
            );
        }

        $arrSymtoms = json_decode( json_encode($getSymptom), true );
        
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrSymtoms);
    }

    public function getSymptomsByEquipment($equipment, $user, $line) {
        try {
            $equipment = $this->encController->decrypt($equipment);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_GETBYEQUIPMENT000: No se pudo obtener el equipamiento.", $th->getMessage(), 500);
        }

        try {
            $getSymptom = DB::table('S002V01TLSEQ')
                ->where('LSEQ_NULI', '=', $line)
                ->where('LSEQ_ESTA', '=', 'Activo')
                ->where('LSEQ_COEQ', '=', $equipment)
                ->where('LISI_NULI', '=', $line)
                ->where('LISI_ESTA', '=', 'Activo')
                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'LSEQ_IDSI')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'LISI_IDME')
                ->get([
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION',
                    'LISI_CAUS AS CAUSA',
                    'LISI_DESC AS DESCRIPCION',
                    'LISI_SOLU AS SOLUCION',
                    'LISI_LIVA AS LIMITE_VALOR',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'LISI_ESTA AS ESTADO',
                    'LISI_USRE AS USUARIO_REGISTRA',
                    'LISI_FERE AS FECHA_REGISTRA',
                    'LISI_USMO AS USUARIO_MODIFICA',
                    'LISI_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_GETBYEQUIPMENT001: No se pudo realizar la consulta a la base.", 
                $th->getMessage(), 
                500
            );
        }

        $arrSymtoms = json_decode( json_encode($getSymptom), true );
        
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrSymtoms);
    }

    public function getSymptomById($idSymptom, $user, $line) {

        try {
            $idSymptom = $this->encController->decrypt($idSymptom);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_GETBYID000: No se pudo obtener el ID del síntoma.", $th->getMessage(), 500);
        }

        try {
            $arrSymptom = (array) DB::table('S002V01TLISI')
                ->where('LISI_IDSI', '=', $idSymptom)
                ->where('LISI_NULI', '=', $line)
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_NULI', '=', $line)
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'LISI_IDME')
                ->first([
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION',
                    'LISI_CAUS AS CAUSA',
                    'LISI_DESC AS DESCRIPCION',
                    'LISI_SOLU AS SOLUCION',
                    'LISI_LIVA AS LIMITE_VALOR',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'LISI_ESTA AS ESTADO',
                    'LISI_USRE AS USUARIO_REGISTRA',
                    'LISI_FERE AS FECHA_REGISTRA',
                    'LISI_USMO AS USUARIO_MODIFICA',
                    'LISI_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_GETBYID001: No se pudo realizar la consulta a la base.", 
                $th->getMessage(), 
                500
            );
        }

        if ( !empty($arrSymptom) ) {
            try {
                $arrEquipment = DB::table('S002V01TLSEQ')
                    ->where('LSEQ_IDSI', '=', $idSymptom)
                    ->where('LSEQ_NULI', '=', $line)
                    ->where('LSEQ_ESTA', '=', 'Activo')
                    ->where('EQUI_NULI', '=', $line)
                    ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'LSEQ_COEQ')
                    ->get([
                        'EQUI_COEQ AS CODIGO',
                        'EQUI_TIPO AS TIPO',
                        'EQUI_MODE AS MODELO',
                        'EQUI_IDEQ AS ID_EQUIPO',
                        'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
                        'EQUI_ELOR AS ELEMENTO_ORIGEN',
                        'EQUI_TICO AS TIPO_CODIGO'
                    ]);
            } catch (\Throwable $th) {
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_GETBYID002: No se pudo realizar la consulta a la base.", 
                    $th->getMessage(), 
                    500
                );
            }

            $arrEquipment = json_decode( json_encode($arrEquipment), true );

            foreach ($arrEquipment as $keyEquipment => $equipment) {
                $equipment['ID_EQUIPO'] = strval($equipment['ID_EQUIPO']);
                $arrEquipment[$keyEquipment] = $equipment;
            }
            $arrSymptom['EQUIPAMIENTOS'] = $arrEquipment;


            try {
                $arrFailure = DB::table('S002V01TLFLS')
                    ->where('LFLS_IDSI', '=', $idSymptom)
                    ->where('LFLS_NULI', '=', $line)
                    ->where('LFLS_ESTA', '=', 'Activo')
                    ->where('LIFA_NULI', '=', $line)
                    ->where('LIFA_ESTA', '=', 'Activo')
                    ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'LFLS_IDFA')
                    ->get([
                        'LIFA_IDFA AS ID_FALLA',
                        'LIFA_NOFA AS NOMBRE_FALLA',
                        'LIFA_NIVE AS NIVEL_CRITICIDAD',
                        'LIFA_CAUS AS CAUSA_FALLA',
                        'LIFA_SOLU AS SOLICION',
                        'LIFA_DESC AS DESCRIPCION',
                    ]);
            } catch (\Throwable $th) {
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_GETBYID003: No se pudo realizar la consulta a la base.", 
                    $th->getMessage(), 
                    500
                );
            }
            $arrFailure = json_decode( json_encode($arrFailure), true );

            $arrSymptom['FALLAS'] = $arrFailure;
        }

        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrSymptom);
    }

    public function registerSymptom(Request $request) {
        $validator = Validator::make($request->all(), [
            'NOMBRE_SINTOMA' => 'required|string',
            'CLASIFICACION' => 'required|string',
            'CAUSA' => 'required|string', 
            'DESCRIPCION' => 'required|string', 
            'SOLUCION' => 'required|string', 
            'LIMITE_VALOR' => 'required|string', 
            'ID_MEDIDA' => 'required|string', 
            'FALLAS' => 'required|array', 
            'EQUIPAMIENTOS' => 'required|array',
            'USUARIO' => 'required|string', 
            'NUMERO_LINEA' => 'required|string', 

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

        DB::beginTransaction();
        $requestData = $request->all();

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

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

        try {
            $idSymptom = DB::table('S002V01TLISI')->insertGetId([
                'LISI_NULI' => $requestData['NUMERO_LINEA'],
                'LISI_NOSI' => $requestData['NOMBRE_SINTOMA'],
                'LISI_CLAS' => $requestData['CLASIFICACION'],
                'LISI_CAUS' => $requestData['CAUSA'],
                'LISI_SOLU' => $requestData['SOLUCION'],
                'LISI_DESC' => $requestData['DESCRIPCION'],
                'LISI_LIVA' => $requestData['LIMITE_VALOR'],
                'LISI_IDME' => $requestData['ID_MEDIDA'],
                'LISI_USRE' => $user,
                'LISI_FERE' => $currentDate,
                'LISI_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
            ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_REG002: Ocurrió un error en el registro de la lista de síntoma en la base de datos.", 
                $th->getMessage(), 
                500
            );
        }

        if ( !$idSymptom ) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_REG003: No se pudo hacer el registro de la lista de síntoma en la base de datos.", 
                [], 
                500
            );
        }

        foreach ($requestData['EQUIPAMIENTOS'] as $keyEquipment => $equipment) {
            try {
                $validateRegisterEquipment = DB::table('S002V01TLSEQ')->insert([
                    'LSEQ_NULI' => $requestData['NUMERO_LINEA'],
                    'LSEQ_IDSI' => $idSymptom,
                    'LSEQ_COEQ' => $equipment,
                    'LSEQ_USRE' => $user,
                    'LSEQ_FERE' => $currentDate,
                    'LSEQ_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                ]);
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse( 
                    true, 
                    "ERR_SYMPTOM_REG004: Ocurrió un error al registrar el formulario en la lista de síntomas.", 
                    $th->getMessage(), 
                    500
                );
            }

            if ( !$validateRegisterEquipment ) {
                DB::rollBack();
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_REG005: No se pudo registrar el equipamiento $equipment en la lista de síntomas.", 
                    [], 
                    500
                );
            }
        }

        foreach ($requestData['FALLAS'] as $keyFailure => $failure) {
            try {
                $validateRegisterFailure = DB::table('S002V01TLFLS')->insert([
                    'LFLS_NULI' => $requestData['NUMERO_LINEA'],
                    'LFLS_IDFA' => $failure,
                    'LFLS_IDSI' => $idSymptom,
                    'LFLS_USRE' => $user,
                    'LFLS_FERE' => $currentDate,
                    'LFLS_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                ]);
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse( 
                    true, 
                    "ERR_SYMPTOM_REG006: Ocurrió un error al registrar el formulario en la lista de síntomas.", 
                    $th->getMessage(), 
                    500
                );
            }

            if ( !$validateRegisterFailure ) {
                DB::rollBack();
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_REG007: No se pudo registrar el equipamiento $equipment en la lista de síntomas.", 
                    [], 
                    500
                );
            }
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
    }

    public function updateSymptom(Request $request) {
        $validator = Validator::make($request->all(), [
            'ID_SINTOMA' => 'required|integer',
            'NOMBRE_SINTOMA' => 'required|string',
            'CLASIFICACION' => 'required|string',
            'CAUSA' => 'required|string', 
            'DESCRIPCION' => 'required|string', 
            'SOLUCION' => 'required|string', 
            'LIMITE_VALOR' => 'required|string', 
            'ID_MEDIDA' => 'required|string', 
            'FALLAS' => 'required|array', 
            'EQUIPAMIENTOS' => 'required|array',
            'USUARIO' => 'required|string', 
            'NUMERO_LINEA' => 'required|string', 

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

        DB::beginTransaction();
        $requestData = $request->all();

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

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

        try {
            $validateUpdate = DB::table('S002V01TLISI')
                ->where('LISI_IDSI', '=', $requestData['ID_SINTOMA'])
                ->where('LISI_NULI', '=', $requestData['NUMERO_LINEA'])
                ->update([
                    'LISI_NOSI' => $requestData['NOMBRE_SINTOMA'],
                    'LISI_CLAS' => $requestData['CLASIFICACION'],
                    'LISI_CAUS' => $requestData['CAUSA'],
                    'LISI_SOLU' => $requestData['SOLUCION'],
                    'LISI_DESC' => $requestData['DESCRIPCION'],
                    'LISI_LIVA' => $requestData['LIMITE_VALOR'],
                    'LISI_IDME' => $requestData['ID_MEDIDA'],
                    'LISI_USMO' => $user,
                    'LISI_FEMO' => $currentDate,
                    'LISI_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_UPD002: Ocurrió un error en el registro de la lista de síntoma en la base de datos.", 
                $th->getMessage(), 
                500
            );
        }

        if ( !$validateUpdate ) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_UPD003: Ocurrió un error en la modificación de la lista de síntoma en la base de datos.", 
                [], 
                500
            );
        }

        foreach ($requestData['EQUIPAMIENTOS'] as $keyEquipment => $equipment) {
            try {
                $validateExists = DB::table('S002V01TLSEQ')
                    ->where('LSEQ_IDSI', '=', $requestData['ID_SINTOMA'])
                    ->where('LSEQ_NULI', '=', $requestData['NUMERO_LINEA'])
                    ->where('LSEQ_COEQ', '=', $equipment)
                    ->exists();
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_UPD004: Ocurrió un error al consultar el equipamiento.", 
                    $th->getMessage(), 
                    500
                );
            }
    
            if ( $validateExists ) {
                try {
                    $validate = DB::table('S002V01TLSEQ')
                        ->where('LSEQ_NULI', '=', $requestData['NUMERO_LINEA'])
                        ->where('LSEQ_IDSI', '=', $requestData['ID_SINTOMA'])
                        ->where('LSEQ_COEQ', '=', $equipment)
                        ->update([
                            'LSEQ_ESTA' => 'Activo',
                            'LSEQ_USMO' => $user,
                            'LSEQ_FEMO' => $currentDate,
                            'LSEQ_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                        ]);
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD005: Ocurrió un error al modificar el formulario en la lista de falla el equipamiento $equipment.", 
                        $th->getMessage(), 
                        500
                    );
                }
            } else {
                try {
                    $validate = DB::table('S002V01TLSEQ')->insert([
                        'LSEQ_NULI' => $requestData['NUMERO_LINEA'],
                        'LSEQ_IDSI' => $requestData['ID_SINTOMA'],
                        'LSEQ_COEQ' => $equipment,
                        'LSEQ_USRE' => $user,
                        'LSEQ_FERE' => $currentDate,
                        'LSEQ_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                    ]);
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD006: Ocurrió un error al registrar el formulario en la lista de falla el equipamiento $equipment.", 
                        $th->getMessage(), 
                        500
                    );
                }
            }
            if ( !$validate ) {
                DB::rollBack();
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_UPD007: No se pudo modificar el equipamiento $equipment en la lista de fallas.", 
                    [], 
                    500
                );
            }
        }

        try {
            $getListEquipment = DB::table('S002V01TLSEQ')
                ->where('LSEQ_IDSI', '=', $requestData['ID_SINTOMA'])
                ->where('LSEQ_NULI', '=', $requestData['NUMERO_LINEA'])
                ->get([
                    'LSEQ_IDLS',
                    'LSEQ_IDSI',
                    'LSEQ_COEQ',
                    'LSEQ_ESTA',
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_UPD008: Ocurrió un error al consultar la lista de equipamientos.", 
                $th->getMessage(), 
                500
            );
        }

        $arrListEquipment = json_decode( json_encode($getListEquipment), true );
        
        foreach ($arrListEquipment as $keyListEquipment => $listEquipment) {
            if( !in_array($listEquipment['LSEQ_COEQ'], $requestData['EQUIPAMIENTOS']) ) {
                try {
                    $validateDelete = DB::table('S002V01TLSEQ')
                        ->where('LSEQ_NULI', '=', $requestData['NUMERO_LINEA'])
                        ->where('LSEQ_IDSI', '=', $requestData['ID_SINTOMA'])
                        ->where('LSEQ_COEQ', '=', $listEquipment['LSEQ_COEQ'])
                        ->update([
                            'LSEQ_ESTA' => 'Eliminado',
                            'LSEQ_USMO' => $user,
                            'LSEQ_FEMO' => $currentDate,
                            'LSEQ_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                        ]);
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD009: Ocurrió un error al eliminar de la lista de falla el equipamiento ". $listEquipment['LSEQ_COEQ'].".", 
                        $th->getMessage(), 
                        500
                    );
                }

                if ( !$validateDelete ) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD010: No se pudo eliminar de la lista de falla el equipamiento ". $listEquipment['LFEQ_COEQ'].".", 
                        [], 
                        500
                    );
                }
            }
        }

        foreach ($requestData['FALLAS'] as $keyFailure => $failure) {
            try {
                $validateExists = DB::table('S002V01TLFLS')
                    ->where('LFLS_IDFA', '=', $failure)
                    ->where('LFLS_IDSI', '=', $requestData['ID_SINTOMA'])
                    ->where('LFLS_NULI', '=', $requestData['NUMERO_LINEA'])
                    ->exists();
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_UPD011: Ocurrió un error al consultar la falla.", 
                    $th->getMessage(), 
                    500
                );
            }

            if ( $validateExists ) {
                try {
                    $validate = DB::table('S002V01TLFLS')
                        ->where('LFLS_NULI', '=', $requestData['NUMERO_LINEA'])
                        ->where('LFLS_IDFA', '=', $failure)
                        ->where('LFLS_IDSI', '=', $requestData['ID_SINTOMA'])
                        ->update([
                            'LFLS_ESTA' => 'Activo',
                            'LFLS_USMO' => $user,
                            'LFLS_FEMO' => $currentDate,
                            'LFLS_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                        ]);
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD012: Ocurrió un error al modificar el formulario en la lista de falla del síntoma.", 
                        $th->getMessage(), 
                        500
                    );
                }
            } else {
                try {
                    $validate = DB::table('S002V01TLFLS')->insert([
                        'LFLS_NULI' => $requestData['NUMERO_LINEA'],
                        'LFLS_IDSI' => $requestData['ID_SINTOMA'],
                        'LFLS_IDFA' => $failure,
                        'LFLS_USRE' => $user,
                        'LFLS_FERE' => $currentDate,
                        'LFLS_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                    ]);
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD013: Ocurrió un error al registrar el formulario en la lista de falla del síntoma.", 
                        $th->getMessage(), 
                        500
                    );
                }
            }
            if ( !$validate ) {
                DB::rollBack();
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_SYMPTOM_UPD014: No se pudo modificar la lista de fallas.", 
                    [], 
                    500
                );
            }
        }

        try {
            $arrListFaliure = DB::table('S002V01TLFLS')
                ->where('LFLS_IDSI', '=', $requestData['ID_SINTOMA'])
                ->where('LFLS_NULI', '=', $requestData['NUMERO_LINEA'])
                ->get([
                    'LFLS_IDFA',
                    'LFLS_IDSI',
                    'LFLS_ESTA',
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_UPD015: Ocurrió un error al consultar la lista de fallas del síntoma.", 
                $th->getMessage(), 
                500
            );
        }

        $arrListFaliure = json_decode( json_encode($arrListFaliure), true );
        
        foreach ($arrListFaliure as $keyListFaliure => $listFaliure) {
            if( !in_array($listFaliure['LFLS_IDFA'], $requestData['FALLAS']) ) {
                try {
                    $validateDelete = DB::table('S002V01TLFLS')
                        ->where('LFLS_IDFA', '=', $listFaliure['LFLS_IDFA'])
                        ->where('LFLS_IDSI', '=', $requestData['ID_SINTOMA'])
                        ->where('LFLS_NULI', '=', $requestData['NUMERO_LINEA'])
                        ->update([
                            'LFLS_ESTA' => 'Eliminado',
                            'LFLS_USMO' => $user,
                            'LFLS_FEMO' => $currentDate,
                            'LFLS_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                        ]);
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD016: Ocurrió un error al eliminar las falla ".$listFaliure['LFLS_IDFA']." del síntoma.", 
                        $th->getMessage(), 
                        500
                    );
                }

                if ( !$validateDelete ) {
                    DB::rollBack();
                    return $this->responseController->makeResponse( 
                        true, 
                        "ERR_SYMPTOM_UPD017: No se pudo eliminar la falla ".$listFaliure['LFLS_IDFA']." del síntoma.", 
                        [], 
                        500
                    );
                }
            }
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
    }

    public function deleteSymptom(Request $request) {
        $validator = Validator::make($request->all(), [
            'ID_SINTOMA' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
            'USUARIO' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_SYMPTOM_DEL000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($validator->errors()->messages()),
                401
            );
        }

        DB::beginTransaction();
        $requestData = $request->all();

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

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

        try {
            $exist = DB::table('S002V01TLISI')
                ->where('LISI_IDSI', '=', $requestData['ID_SINTOMA'])
                ->where('LISI_NULI', '=', $requestData['NUMERO_LINEA'])
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_DEL002: Ocurrió un error al consultar en la base de datos.", $th->getMessage(), 500);
        }
        
        if (!$exist) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_DEL003: El archivo no existe.", [], 500);
        }

        try {
            $validateDelete = DB::table('S002V01TLISI')
                ->where('LISI_IDSI', '=', $requestData['ID_SINTOMA'])
                ->where('LISI_NULI', '=', $requestData['NUMERO_LINEA'])
                ->update([
                    'LISI_ESTA' => 'Eliminado',
                    'LISI_USMO' => $user,
                    'LISI_FEMO' => $currentDate,
                    'LISI_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_DEL004: Ocurrió un error al eliminar el síntoma de la base de datos.", $th->getMessage(), 500);
        }
        if ( !$validateDelete ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_DEL005: No se pudo eliminar el síntoma de la base de datos.", [], 500);
        }


        try {
            $validateDelete = DB::table('S002V01TLSEQ')
                ->where('LSEQ_IDSI', '=', $requestData['ID_SINTOMA'])
                ->where('LSEQ_NULI', '=', $requestData['NUMERO_LINEA'])
                ->update([
                    'LSEQ_ESTA' => 'Eliminado',
                    'LSEQ_USMO' => $user,
                    'LSEQ_FEMO' => $currentDate,
                    'LSEQ_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_DEL006: Ocurrió un error al eliminar la lista de equipamientos.", 
                $th->getMessage(), 
                500
            );
        }
        if ( !$validateDelete ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_DEL007: No se pudo eliminar la lista de equipamientos.", [], 500);
        }

        try {
            $validateDelete = DB::table('S002V01TLFLS')
                ->where('LFLS_IDSI', '=', $requestData['ID_SINTOMA'])
                ->where('LFLS_NULI', '=', $requestData['NUMERO_LINEA'])
                ->update([
                    'LFLS_ESTA' => 'Eliminado',
                    'LFLS_USMO' => $user,
                    'LFLS_FEMO' => $currentDate,
                    'LFLS_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(
                true, 
                "ERR_SYMPTOM_DEL008: Ocurrió un error al eliminar la lista de fallas.", 
                $th->getMessage(), 
                500
            );
        }
        if ( !$validateDelete ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_SYMPTOM_DEL009: No se pudo eliminar la lista de fallas.", [], 500);
        }
        
        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Eliminación Exitosa");
    }

}
