<?php
/*
    Desarrollador: Ing. Jean Jairo Benitez Meza
    Ultima Modificación: 21/09/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;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Dompdf\Dompdf;

class FailureLogController extends Controller
{
    private $responseController;
    private $encController;
    private $functionsController;
    private $resourcesController;

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

    public function getFailureLog($user, $line) {

        try {
            $getFailureLog = DB::table('S002V01TBIFA')
                ->where('BIFA_NULI', '=', $line)
                ->where('LIFA_NULI', '=', $line)
                ->where('LISI_NULI', '=', $line)
                ->where('LIME_NULI', '=', $line)
                ->where('LIFA_ESTA', '=', 'Activo')
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
                ->get([
                    'BIFA_NUFA AS NUMERO_FALLA',
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'BIFA_ESFA AS ESTADO_FALLA',
                    'LIFA_IDFA AS ID_FALLA',
                    'LIFA_NOFA AS NOMBRE_FALLA',
                    'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
                    'LIFA_CAUS AS CAUSA_FALLA',
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION_SINTOMA',
                    'LISI_CAUS AS CAUSA_SINTOMA',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'BIFA_REPA AS REPARABLE',
                    'BIFA_DESO AS SOLUCION',
                    'BIFA_COME AS COMENTARIOS',
                    'BIFA_VAOB AS VALOR_OBTENIDO',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'BIFA_ESTA AS ESTADO',
                    'BIFA_USRE AS USUARIO_REGISTRA',
                    'BIFA_FERE AS FECHA_REGISTRA',
                    'BIFA_USMO AS USUARIO_MODIFICA',
                    'BIFA_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GET000: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        $arrFailureLog = json_decode( json_encode( $getFailureLog ), true );

        $arrEquipmentCode = array_column($arrFailureLog, 'CODIGO_EQUIPAMIENTO');
        $arrEquipmentCode = array_unique($arrEquipmentCode);

        $count = 0;
        $arrEquipmentFailureLog = array();
        foreach ($arrEquipmentCode as $keyEquipmentCode => $equipmentCode) {
            $lastUpdate = '';
            $lastUser = '';
            $lastState = '';
            $lastClassification = '';
            $amountFailures = 0;
            foreach ($arrFailureLog as $keyFailureLog => $failureLog) {
                if ( $equipmentCode === $failureLog['CODIGO_EQUIPAMIENTO'] ) {
                   
                    $tempLastUpdate = '';
                    $tempLastUser = '';
                    if ( is_null($failureLog['FECHA_MODIFICA']) ) {
                        $tempLastUpdate = $failureLog['FECHA_REGISTRA'];
                        $tempLastUser = $failureLog['USUARIO_REGISTRA'];
                    } else {
                        $tempLastUpdate = $failureLog['FECHA_MODIFICA'];
                        $tempLastUser = $failureLog['USUARIO_MODIFICA'];
                    }

                    if ($lastUpdate === '') {
                        $lastUpdate = $tempLastUpdate;
                        $lastUser = $tempLastUser;
                        $lastState = $failureLog['ESTADO_FALLA'];
                        $lastClassification = $failureLog['NIVEL_CRITICIDAD_FALLA'];
                    } else {
                        $carTempLastUpdate = Carbon::create($tempLastUpdate);
                        $carLastState = Carbon::create($lastUpdate);

                        if ($carTempLastUpdate->greaterThan($carLastState)) {
                            $lastUpdate = $tempLastUpdate;
                            $lastUser = $tempLastUser;
                            $lastState = $failureLog['ESTADO_FALLA'];
                            $lastClassification = $failureLog['NIVEL_CRITICIDAD_FALLA'];
                        }
                    }
                    $amountFailures ++;
                }
            }

            $arrEquipmentFailureLog[$count]['CODIGO_EQUIPAMIENTO'] = $equipmentCode;
            $arrEquipmentFailureLog[$count]['ULTIMA_MODIFICACION'] = $lastUpdate;
            $arrEquipmentFailureLog[$count]['ULTIMO_USUARIO'] = $lastUser;
            $arrEquipmentFailureLog[$count]['ESTADO_ACTUAL'] = $lastState;
            $arrEquipmentFailureLog[$count]['CLASIFICACION_ACTUAL'] = $lastClassification;
            $arrEquipmentFailureLog[$count]['CANTIDAD_FALLAS'] = $amountFailures;

            $count++;
        }
        

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

    public function getHistoryFailureEquipment($equipment, $user, $line) {
        try {
            $equipment = $this->encController->decrypt($equipment);    
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_GETHISTORY_GETEQUIPMENT000", $th->getMessage(), 500);
        }

        try {
            $getFailuresLog = DB::table('S002V01TBIFA')
                ->where('BIFA_COEQ', '=', $equipment)
                ->where('BIFA_NULI', '=', $line)
                ->where('BIFA_ESTA', '=', 'Activo')
                ->where('LIFA_ESTA', '=', 'Activo')
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
                ->get([
                    'BIFA_NUFA AS NUMERO_FALLA',
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'BIFA_ESFA AS ESTADO_FALLA',
                    'LIFA_IDFA AS ID_FALLA',
                    'LIFA_NOFA AS NOMBRE_FALLA',
                    'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
                    'LIFA_CAUS AS CAUSA_FALLA',
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION_SINTOMA',
                    'LISI_CAUS AS CAUSA_SINTOMA',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'BIFA_REPA AS REPARABLE',
                    'BIFA_DESO AS SOLUCION',
                    'BIFA_COME AS COMENTARIOS',
                    'BIFA_VAOB AS VALOR_OBTENIDO',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'BIFA_USRE AS USUARIO_REGISTRA',
                    'BIFA_FERE AS FECHA_REGISTRA',
                    'BIFA_USMO AS USUARIO_MODIFICA',
                    'BIFA_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_GETHISTORY_GETEQUIPMENT001: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        $arrFailureLogTemp = json_decode( json_encode( $getFailuresLog ), true );

        $arrFailureLog = array();
        foreach ($arrFailureLogTemp as $keyFailureLogTemp => $failureLogTemp) {
            $numero_falla = $failureLogTemp['NUMERO_FALLA'];

            $nombre_falla = $failureLogTemp['NOMBRE_FALLA'].' ('.$failureLogTemp['ID_FALLA'].')';

            $nivel_criticidad_falla = $failureLogTemp['NIVEL_CRITICIDAD_FALLA'];

            $nombre_sintoma = $failureLogTemp['NOMBRE_SINTOMA'].' ('.$failureLogTemp['ID_SINTOMA'].')';

            $estado_falla = $failureLogTemp['ESTADO_FALLA'];

            $causa = $failureLogTemp['CAUSA_FALLA'];

            $fecha_fala = $failureLogTemp['FECHA_FALLA'];

            $reparable = $failureLogTemp['REPARABLE'] === 1 ? 'Si' : 'No';

            $usuario_registra = is_null($failureLogTemp['USUARIO_MODIFICA']) ?  $failureLogTemp['USUARIO_REGISTRA'] : $failureLogTemp['USUARIO_MODIFICA'];

            $fecha_registra = is_null($failureLogTemp['FECHA_MODIFICA']) ?  $failureLogTemp['FECHA_REGISTRA'] : $failureLogTemp['FECHA_MODIFICA'];

            $arrFailureLog[] = [
                'NUMERO_FALLA' => $numero_falla,
                'NOMBRE_FALLA' => $nombre_falla,
                'NIVEL_CRITICIDAD_FALLA' => $nivel_criticidad_falla,
                'ESTADO_FALLA' => $estado_falla,
                'CAUSA' => $causa,
                'FECHA_FALLA' => $fecha_fala,
                'REPARABLE' => $reparable,
                'USUARIO_REGISTRA' => $usuario_registra,
                'FECHA_REGISTRA' => $fecha_registra,
            ];
        }

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

        
    }

    public function getDetailsHistoryFailureEquipment($failure, $user, $line) {
        try {
            $failure = $this->encController->decrypt($failure);    
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_GETHISTORY_GETEQUIPMENT000", $th->getMessage(), 500);
        }

        try {
            $getFailureLog = DB::table('S002V01TBIFA')
                ->where('BIFA_NUFA', '=', $failure)
                ->where('BIFA_NULI', '=', $line)
                ->where('LIFA_NULI', '=', $line)
                ->where('LISI_NULI', '=', $line)
                ->where('LIME_NULI', '=', $line)
                ->where('BIFA_ESTA', '=', 'Activo')
                ->where('LIFA_ESTA', '=', 'Activo')
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
                ->first([
                    'BIFA_NUFA AS NUMERO_FALLA',
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'BIFA_ESFA AS ESTADO_FALLA',
                    'LIFA_IDFA AS ID_FALLA',
                    'LIFA_NOFA AS NOMBRE_FALLA',
                    'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
                    'LIFA_CAUS AS CAUSA_FALLA',
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION_SINTOMA',
                    'LISI_CAUS AS CAUSA_SINTOMA',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'BIFA_FERF AS FECHA_RESOLUCION',
                    'BIFA_REPA AS REPARABLE',
                    'BIFA_DESO AS SOLUCION',
                    'BIFA_COME AS COMENTARIOS',
                    'BIFA_VAOB AS VALOR_OBTENIDO',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GETACTIVE000: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        $arrFailureLog = json_decode( json_encode( $getFailureLog ), true );

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

    public function getFailureLogActives($user, $line) {

        try {
            $getFailureLog = DB::table('S002V01TBIFA')
                ->where('BIFA_NULI', '=', $line)
                ->where('LIFA_NULI', '=', $line)
                ->where('LISI_NULI', '=', $line)
                ->where('LIME_NULI', '=', $line)
                ->where('BIFA_ESTA', '=', 'Activo')
                ->where('LIFA_ESTA', '=', 'Activo')
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
                ->get([
                    'BIFA_NUFA AS NUMERO_FALLA',
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'LIFA_IDFA AS ID_FALLA',
                    'LIFA_NOFA AS NOMBRE_FALLA',
                    'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
                    'LIFA_CAUS AS CAUSA_FALLA',
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION_SINTOMA',
                    'LISI_CAUS AS CAUSA_SINTOMA',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'BIFA_REPA AS REPARABLE',
                    'BIFA_DESO AS SOLUCION',
                    'BIFA_COME AS COMENTARIOS',
                    'BIFA_VAOB AS VALOR_OBTENIDO',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                    'BIFA_USRE AS USUARIO_REGISTRA',
                    'BIFA_FERE AS FECHA_REGISTRA',
                    'BIFA_USMO AS USUARIO_MODIFICA',
                    'BIFA_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GETACTIVE000: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        $arrFailureLog = json_decode( json_encode( $getFailureLog ), true );

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

    public function getEquipmentByFailure($failure, $user, $line) {

        try {
            $failure = $this->encController->decrypt($failure);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_EQUIPMENT000: No se pudo obtener el usuario.", $th->getMessage(), 500);
        }
        try {
            $getEquipmentByFailure = DB::table('S002V01TBIFA')
                ->where('BIFA_IDFA', '=', $failure)
                ->where('BIFA_NULI', '=', $line)
                ->where('BIFA_ESTA', '=', 'Activo')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
                ->get([
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'BIFA_ESFA AS ESTADO_FALLA',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'BIFA_FERF AS FECHA_REPARACION',
                    'BIFA_VAOB AS VALOR_OBTENIDO',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURES_EQUIPMENT001: No se pudo realizar la consulta a la base.", 
                $th->getMessage(), 
                500
            );
        }
        
        $arrFaultyEquipment = json_decode(json_encode($getEquipmentByFailure), true);

        $arrEquipmentCode = array_column($arrFaultyEquipment, 'CODIGO_EQUIPAMIENTO');
        $arrEquipmentCode = array_unique($arrEquipmentCode);

        $count = 0;
        $arrEquipmentFailureLog = array();
        foreach ($arrEquipmentCode as $keyEquipmentCode => $equipmentCode) {
            foreach ($arrFaultyEquipment as $keyFaultyEquipment => $faultyEquipment) {
                if ( $equipmentCode === $faultyEquipment['CODIGO_EQUIPAMIENTO'] ) {
                    $arrEquipmentFailureLog[$count]['CODIGO_EQUIPAMIENTO'] = $faultyEquipment['CODIGO_EQUIPAMIENTO'];
                    $arrEquipmentFailureLog[$count]['DETALLES'][] = [
                        'ESTADO_FALLA' => $faultyEquipment['ESTADO_FALLA'], 
                        'FECHA_FALLA' => $faultyEquipment['FECHA_FALLA'], 
                        'FECHA_REPARACION' => $faultyEquipment['FECHA_REPARACION'], 
                        'VALOR_OBTENIDO' => $faultyEquipment['VALOR_OBTENIDO'], 
                        'ID_MEDIDA' => $faultyEquipment['ID_MEDIDA'], 
                        'NOMBRE_MEDIDA' => $faultyEquipment['NOMBRE_MEDIDA'], 
                        'ACRONIMO_MEDIDA' => $faultyEquipment['ACRONIMO_MEDIDA'], 
                    ];
                }
            }

            $count++;
        }

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

    public function getAlarmEmissionFromFailures($user, $line) {
        try {
            $getAlarmEmission = DB::table('S002V01TBIFA')
                ->where('BIFA_NULI', '=', $line)
                ->where('BIFA_ESTA', '=', 'Activo')
                ->where('ACTI_NULI', '=', $line)
                ->join('S002V01TACTI', 'ACTI_IDAC', '=', 'BIFA_IDAC')
                ->get([
                    'BIFA_NUFA AS NUMERO_FALLA',
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'ACTI_IDAC AS ID_ACTIVADOR',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'ACTI_PRIO AS PRIORIDAD',
                    'ACTI_TIAC AS TIPO_ACTIVADOR',
                    'ACTI_COAC AS CONDICION_ACTIVADOR',
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_ALARM000: No se pudo obtener la información de la base de datos.", $th->getMessage(), 500);
        }

        $arrAlarmEmission = json_decode(json_encode($getAlarmEmission), true);

        foreach ($arrAlarmEmission as $key => $alarmEmission) {
            
            switch ($alarmEmission['PRIORIDAD']) {
                case 1:
                    $alarmEmission['PRIORIDAD'] = 'Muy alta';
                    break;
                case 2:
                    $alarmEmission['PRIORIDAD'] = 'Alta';
                    break;
                case 3:
                    $alarmEmission['PRIORIDAD'] = 'Media';
                    break;
                case 4:
                    $alarmEmission['PRIORIDAD'] = 'Baja';
                    break;
            }

            $arrAlarmEmission[$key] = $alarmEmission;
        }

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

    public function generateSheetFailureXLS($failure, $user, $line) {
        try {
            $failure = $this->encController->decrypt($failure);    
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GENERATEXLS000", $th->getMessage(), 500);
        }
        try {
            $user = $this->encController->decrypt($user);    
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GENERATEXLS001", $th->getMessage(), 500);
        }

        try {
            $getFailureLog = DB::table('S002V01TBIFA')
                ->where('BIFA_NUFA', '=', $failure)
                ->where('BIFA_NULI', '=', $line)
                ->where('LIFA_NULI', '=', $line)
                ->where('LISI_NULI', '=', $line)
                ->where('LIME_NULI', '=', $line)
                ->where('BIFA_ESTA', '=', 'Activo')
                ->where('LIFA_ESTA', '=', 'Activo')
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
                ->first([
                    'BIFA_NUFA AS NUMERO_FALLA',
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'BIFA_ESFA AS ESTADO_FALLA',
                    'LIFA_IDFA AS ID_FALLA',
                    'LIFA_NOFA AS NOMBRE_FALLA',
                    'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
                    'LIFA_CAUS AS CAUSA_FALLA',
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION_SINTOMA',
                    'LISI_CAUS AS CAUSA_SINTOMA',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'BIFA_FERF AS FECHA_RESOLUCION',
                    'BIFA_REPA AS REPARABLE',
                    'BIFA_DESO AS SOLUCION',
                    'BIFA_COME AS COMENTARIOS',
                    'BIFA_VAOB AS VALOR_OBTENIDO',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GENERATEXLS002: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        $arrFailureLog = json_decode( json_encode( $getFailureLog ), true );

        $spreadsheet = new Spreadsheet();
        $activeWorksheet = $spreadsheet->getActiveSheet()->setTitle($arrFailureLog['NUMERO_FALLA']);

        $activeWorksheet->setCellValue("A1", 'Número de Falla');
        $activeWorksheet->setCellValue("B1", $arrFailureLog['NUMERO_FALLA']);
        $activeWorksheet->getStyle( "A1" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A2", 'Número de Equipamiento');
        $activeWorksheet->setCellValue("B2", $arrFailureLog['CODIGO_EQUIPAMIENTO']);
        $activeWorksheet->getStyle( "A2" )->getFont()->setBold(true);
        
        $activeWorksheet->setCellValue("A3", 'Estado de la Falla');
        $activeWorksheet->setCellValue("B3", $arrFailureLog['ESTADO_FALLA']);
        $activeWorksheet->getStyle( "A3" )->getFont()->setBold(true);
        
        $activeWorksheet->setCellValue("A4", 'Nombre de la Falla');
        $activeWorksheet->setCellValue("B4", $arrFailureLog['NOMBRE_FALLA'].' ('.$arrFailureLog['ID_FALLA'].')');
        $activeWorksheet->getStyle( "A4" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A5", 'Nivel de Criticidad de la Falla');
        $activeWorksheet->setCellValue("B5", $arrFailureLog['NIVEL_CRITICIDAD_FALLA']);
        $activeWorksheet->getStyle( "A5" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A6", 'Causa de la Falla');
        $activeWorksheet->setCellValue("B6", $arrFailureLog['CAUSA_FALLA']);
        $activeWorksheet->getStyle( "A6" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A7", 'Nombre del Síntoma');
        $activeWorksheet->setCellValue("B7", $arrFailureLog['NOMBRE_SINTOMA'].' ('.$arrFailureLog['ID_SINTOMA'].')');
        $activeWorksheet->getStyle( "A7" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A8", 'Clasificación del Síntoma');
        $activeWorksheet->setCellValue("B8", $arrFailureLog['CLASIFICACION_SINTOMA']);
        $activeWorksheet->getStyle( "A8" )->getFont()->setBold(true);
      
        $activeWorksheet->setCellValue("A9", 'Causa del Síntoma');
        $activeWorksheet->setCellValue("B9", $arrFailureLog['CAUSA_SINTOMA']);
        $activeWorksheet->getStyle( "A9" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A10", 'Fecha de la Falla');
        $activeWorksheet->setCellValue("B10", $arrFailureLog['FECHA_FALLA']);
        $activeWorksheet->getStyle( "A10" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A11", 'Fecha de la Resolución');
        $activeWorksheet->setCellValue("B11", $arrFailureLog['FECHA_RESOLUCION']);
        $activeWorksheet->getStyle( "A11" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A12", 'Reparable');
        $activeWorksheet->setCellValue("B12", $arrFailureLog['REPARABLE'] === 1 ? 'Si' : 'No');
        $activeWorksheet->getStyle( "A12" )->getFont()->setBold(true);
        
        $activeWorksheet->setCellValue("A13", 'Valor Obtenido');
        $activeWorksheet->setCellValue("B13", $arrFailureLog['VALOR_OBTENIDO'].' '.$arrFailureLog['ACRONIMO_MEDIDA']);
        $activeWorksheet->getStyle( "A13" )->getFont()->setBold(true);

        $activeWorksheet->setCellValue("A14", 'Tipo de Medido');
        $activeWorksheet->setCellValue("B14", $arrFailureLog['NOMBRE_MEDIDA']);
        $activeWorksheet->getStyle( "A14" )->getFont()->setBold(true);
        
        $activeWorksheet->setCellValue("A15", 'Solución de la Falla');
        $activeWorksheet->setCellValue("B15", $arrFailureLog['SOLUCION'] === null || $arrFailureLog['SOLUCION'] === '' ? '' : $arrFailureLog['SOLUCION']);
        $activeWorksheet->getStyle( "A15" )->getFont()->setBold(true);
        
        $activeWorksheet->setCellValue("A16", 'Comentarios');
        $activeWorksheet->setCellValue("B16", $arrFailureLog['COMENTARIOS']);
        $activeWorksheet->getStyle( "A16" )->getFont()->setBold(true);


        $activeWorksheet->getColumnDimension("A")->setAutoSize(true);
        $activeWorksheet->getColumnDimension("B")->setAutoSize(true);


        $nuli = $this->resourcesController->formatSecuence($line, 2);
        $como = 'ANFA';         // Código del módulo
        $cldo = 'IN';           // Código de la clasificación
        $fecr = date('ymd');    // Fecha en la se carga el archivo

        try {
            $arrSecuence = (array) DB::table('S002V01TAFAL')
                ->where('AFAL_COMO', '=', $como)
                ->where('AFAL_CLDO', '=', $cldo)
                ->where('AFAL_NULI', '=', $line)
                ->orderBy('AFAL_NUSE', 'desc')
                ->first([ 'AFAL_NUSE' ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEXLS003: Ocurrió un error al obtener la información de la secuencia.", 
                $th->getMessage(), 
                500
            );
        }
        $nuse = 1;              // Secuencia del documento
        if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
            $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1; 
        }
        $nuse = $this->resourcesController->formatSecuence($nuse, 6);
        $nuve = $this->resourcesController->formatSecuence('1', 2);
        $noar = 'ficha_de_falla_'.$arrFailureLog['NUMERO_FALLA'];
        $exte = 'xlsx';

        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $filePath = 'C:/ITTEC/SAM/Dev/SistemaMantenimiento/sistema-mantenimiento-back/public/public_files/';    // API JEAN
        } else {
            $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';     // API QA
        }
        
        $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;

        $tempFile = $filePath.$fileName;

        if ( file_exists( $tempFile ) ) {
            if ( !unlink( $tempFile ) ) {
                return $this->responseController->makeResponse(
                    true, 
                    "ERR_FAILURELOG_GENERATEXLS004: Ocurrió un error al eliminar el siguiente archivo: " . $tempFile, 
                    [], 
                    500
                );
            }
        }
        
        try {
            $writer = new Xlsx($spreadsheet);
            ob_start();
            $writer->save('php://output');
            $base64 = base64_encode(ob_get_clean());
            $validate = \File::put( $tempFile, base64_decode($base64));
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEXLS005: Ocurrió un error al guardar el documento.", 
                $th->getMessage(), 
                500
            );
        }

        $ubic = Storage::putFile('files', new File($tempFile));
        $ubic = str_replace("/", "\\", $ubic);
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
        } else {
            $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
        }
        $tama = filesize($ubic);
        $usac = json_encode([$user]);

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

        try {
            $validateInsert = 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' => $user,
                'AFAL_FERE' => $currentDate,
            ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEXLS006: Ocurrió un error guardar los datos a la tabla final de archivos.", 
                $th->getMessage(), 
                500
            );
        }

        if ( !$validateInsert ) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEXLS007: No se pudo guardar la ficha del proveedor en la base de datos.", 
                [], 
                500
            );
        }
        
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $urlPublic = 'http://192.168.100.105:8000/public_files/' . $fileName;
        } else {
            $urlPublic = $this->functionsController->getApiURI().'sam/public_files/' . $fileName;
        }

        return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa", [ 'url' => $urlPublic ]);

        return $arrFailureLog;
    }
    public function generateSheetFailurePDF($failure, $user, $line){
        try {
            $failure = $this->encController->decrypt($failure);    
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GENERATEPDF000: Ocurrió un error al obtener la falla.", $th->getMessage(), 500);
        }
        try {
            $user = $this->encController->decrypt($user);    
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GENERATEPDF001: Ocurrió un error al obtener el usuario.", $th->getMessage(), 500);
        }
        try {
            $getFailureLog = DB::table('S002V01TBIFA')
                ->where('BIFA_NUFA', '=', $failure)
                ->where('BIFA_NULI', '=', $line)
                ->where('LIFA_NULI', '=', $line)
                ->where('LISI_NULI', '=', $line)
                ->where('LIME_NULI', '=', $line)
                ->where('BIFA_ESTA', '=', 'Activo')
                ->where('LIFA_ESTA', '=', 'Activo')
                ->where('LISI_ESTA', '=', 'Activo')
                ->where('LIME_ESTA', '=', 'Activo')
                ->join('S002V01TLIFA', 'LIFA_IDFA', '=', 'BIFA_IDFA')
                ->join('S002V01TLISI', 'LISI_IDSI', '=', 'BIFA_IDSI')
                ->join('S002V01TLIME', 'LIME_IDME', '=', 'BIFA_IDME')
                ->first([
                    'BIFA_NUFA AS NUMERO_FALLA',
                    'BIFA_COEQ AS CODIGO_EQUIPAMIENTO',
                    'BIFA_ESFA AS ESTADO_FALLA',
                    'LIFA_IDFA AS ID_FALLA',
                    'LIFA_NOFA AS NOMBRE_FALLA',
                    'LIFA_NIVE AS NIVEL_CRITICIDAD_FALLA',
                    'LIFA_CAUS AS CAUSA_FALLA',
                    'LISI_IDSI AS ID_SINTOMA',
                    'LISI_NOSI AS NOMBRE_SINTOMA',
                    'LISI_CLAS AS CLASIFICACION_SINTOMA',
                    'LISI_CAUS AS CAUSA_SINTOMA',
                    'BIFA_FEFA AS FECHA_FALLA',
                    'BIFA_FERF AS FECHA_RESOLUCION',
                    'BIFA_REPA AS REPARABLE',
                    'BIFA_DESO AS SOLUCION',
                    'BIFA_COME AS COMENTARIOS',
                    'BIFA_VAOB AS VALOR_OBTENIDO',
                    'LIME_IDME AS ID_MEDIDA',
                    'LIME_NOME AS NOMBRE_MEDIDA',
                    'LIME_ACME AS ACRONIMO_MEDIDA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_GENERATEPDF002: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        $arrFailureLog = json_decode( json_encode( $getFailureLog ), true );
        // return $arrFailureLog;
        $html = '<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
            <style>
                body {
                    font-family: Arial, Helvetica, sans-serif;
                    font-size: 8pt;
                }
                .section-title { 
                    margin: 20px 0;
                    font-size: 12pt;
                }

                table {
                    width: 100%;
                }

                thead tr th {
                    text-align: start;
                    padding: 0 16px;
                    height: 52px;
                    border-bottom-width: 1px;
                    border-bottom-style: solid;
                    border-bottom-color: #CCC;
                }

                tbody tr td {
                    padding: 0 16px;
                    height: 52px;
                    border-bottom-width: 1px;
                    border-bottom-style: solid;
                    border-bottom-color: #CCC;
                }

                p {
                    text-align: justify;
                }

            </style>
        </head>
        <body>
            <div class="item">
                <b>Número de Falla: </b>
                <span>'.$arrFailureLog['NUMERO_FALLA'].'</span>
            </div>
            <div class="item">
                <b>Número de Equipamiento: </b>
                <span>'.$arrFailureLog['CODIGO_EQUIPAMIENTO'].'</span>
            </div>
            <div class="item">
                <b>Estado de la Falla: </b>
                <span>'.$arrFailureLog['ESTADO_FALLA'].'</span>
            </div>
            <div class="item">
                <b>Nombre de la Falla: </b>
                <span>'.$arrFailureLog['NOMBRE_FALLA'].' ('.$arrFailureLog['ID_FALLA'].')'.'</span>
            </div>
            <div class="item">
                <b>Nivel de Criticidad de la Falla: </b>
                <span>'.$arrFailureLog['NIVEL_CRITICIDAD_FALLA'].'</span>
            </div>
            <div class="item">
                <b>Causa de la Falla: </b>
                <span>'.$arrFailureLog['CAUSA_FALLA'].'</span>
            </div>
            <div class="item">
                <b>Nombre del Síntoma: </b>
                <span>'.$arrFailureLog['NOMBRE_SINTOMA'].' ('.$arrFailureLog['ID_SINTOMA'].')'.'</span>
            </div>
            <div class="item">
                <b>Clasificación del Síntoma: </b>
                <span>'.$arrFailureLog['CLASIFICACION_SINTOMA'].'</span>
            </div>
            <div class="item">
                <b>Causa del Síntoma: </b>
                <span>'.$arrFailureLog['CAUSA_SINTOMA'].'</span>
            </div>
            <div class="item">
                <b>Fecha de la Falla: </b>
                <span>'.$arrFailureLog['FECHA_FALLA'].'</span>
            </div>
            <div class="item">
                <b>Fecha de la Resolución: </b>
                <span>'.$arrFailureLog['FECHA_RESOLUCION'].'</span>
            </div>
            <div class="item">
                <b>Reparable: </b>
                <span>'.(($arrFailureLog['REPARABLE'] === 1) ? ('Si') : ('No')).'</span>
            </div>
            <div class="item">
                <b>Valor Obtenido: </b>
                <span>'.$arrFailureLog['VALOR_OBTENIDO'].' '.$arrFailureLog['ACRONIMO_MEDIDA'].'</span>
            </div>
            <div class="item">
                <b>Tipo de Medido: </b>
                <span>'.$arrFailureLog['NOMBRE_MEDIDA'].'</span>
            </div>
            <div class="item">
                <b>Solución de la Falla: </b>
                <span>'.(($arrFailureLog['SOLUCION'] === null || $arrFailureLog['SOLUCION'] === '') ? ('') : ($arrFailureLog['SOLUCION'])).'</span>
            </div>
            <div class="item">
                <b>Comentarios: </b>
                <span>'.$arrFailureLog['COMENTARIOS'].'</span>
            </div>';
        $html .= '</body></html>';

        $nuli = $this->resourcesController->formatSecuence($line, 2);
        $como = 'ANFA';         // Código del módulo
        $cldo = 'IN';           // Código de la clasificación
        $fecr = date('ymd');    // Fecha en la se carga el archivo

        try {
            $arrSecuence = (array) DB::table('S002V01TAFAL')
                ->where('AFAL_COMO', '=', $como)
                ->where('AFAL_CLDO', '=', $cldo)
                ->where('AFAL_NULI', '=', $line)
                ->orderBy('AFAL_NUSE', 'desc')
                ->first([ 'AFAL_NUSE' ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEPDF003: Ocurrió un error al obtener la información de la secuencia.", 
                $th->getMessage(), 
                500
            );
        }
        $nuse = 1;              // Secuencia del documento
        if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
            $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1; 
        }
        $nuse = $this->resourcesController->formatSecuence($nuse, 6);
        $nuve = $this->resourcesController->formatSecuence('1', 2);
        $noar = 'ficha_de_proveedor_' . $arrFailureLog['NUMERO_FALLA'];

        $nuli = $this->resourcesController->formatSecuence($line, 2);
        $como = 'GEAD';         // Código del módulo
        $cldo = 'IN';           // Código de la clasificación
        $fecr = date('ymd');    // Fecha en la se carga el archivo
        try {
            $arrSecuence = (array) DB::table('S002V01TAFAL')
                ->where('AFAL_COMO', '=', $como)
                ->where('AFAL_CLDO', '=', $cldo)
                ->where('AFAL_NULI', '=', $line)
                ->orderBy('AFAL_NUSE', 'desc')
                ->first([ 'AFAL_NUSE' ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEPDF004: Ocurrió un error al obtener la información de la secuencia.", 
                $th->getMessage(), 
                500
            );
        }
        $nuse = 1;              // Secuencia del documento
        if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
            $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1; 
        }
        $nuse = $this->resourcesController->formatSecuence($nuse, 6);
        $nuve = $this->resourcesController->formatSecuence('1', 2);
        $noar = 'ficha_de_falla_' . $arrFailureLog['NUMERO_FALLA'];
        $exte = 'pdf';        
        
        
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $filePath = 'C:/ITTEC/SAM/Dev/SistemaMantenimiento/sistema-mantenimiento-back/public/public_files/';    // API JEAN
        } else {
            $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';     // API QA
        }

        $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;
        
        $tempFile = $filePath . $fileName;

        $dompdf = new Dompdf();
        $dompdf ->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();


        $output = $dompdf->output();
        file_put_contents($tempFile, $output);
        $ubic = Storage::putFile('files', new File($tempFile));

        $ubic = str_replace("/", "\\", $ubic);
        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
        } else {
            $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
        }
        $tama = filesize($ubic);
        $usac = json_encode([$user]);

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

        try {
            $validateInsert = 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' => $user,
                'AFAL_FERE' => $currentDate,
            ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEPDF005: Ocurrió un error guardar los datos a la tabla final de archivos.", 
                $th->getMessage(), 
                500
            );
        }

        if ( !$validateInsert ) {
            return $this->responseController->makeResponse(
                true, 
                "ERR_FAILURELOG_GENERATEPDF006: No se pudo guardar la ficha del proveedor en la base de datos.", 
                [], 
                500
            );
        }

        if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
            $urlPublic = 'http://192.168.100.105:8000/public_files/' . $fileName;
        } else {
            $urlPublic = $this->functionsController->getApiURI().'sam/public_files/' . $fileName;
        }

        return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa", [ 'url' => $urlPublic ]);


    }


    public function registerFailureLog(Request $request) {
        $validator = Validator::make($request->all(), [
            'CODIGO_EQUIPAMIENTO' => 'required|string',
            'ID_FALLA' => 'required|integer',
            // 'ID_SINTOMA' => 'required|integer',
            'FECHA_FALLA' => 'required|string',
            'REPARABLE' => 'required|string',
            'SOLUCION' => 'required|string',
            'COMENTARIOS' => 'required|string',
            'VALOR_OBTENIDO' => 'required|string',
            'ID_MEDIDA' => 'required|string',
            'USUARIO' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_FAILURELOG_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_FAILURELOG_REG001: No se pudo obtener el usuario.", $th->getMessage(), 500);
        }

        try {
            $validateExistsFailureList = DB::table('S002V01TLIFA')
                ->where('LIFA_NULI',  '=', $requestData['NUMERO_LINEA'])
                ->where('LIFA_IDFA',  '=', $requestData['ID_FALLA'])
                ->where('LIFA_ESTA',  '=', 'Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG002: Ocurrió un error al consultar la lista de fallas.", $th->getMessage(), 500);
        }
        if ( !$validateExistsFailureList ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG003: No existe la falla #".$requestData['ID_FALLA']." en la lista de fallas.", [], 500);
        }

        if ( !is_null($requestData['ID_SINTOMA']) && $requestData['ID_SINTOMA'] !== '' ) {
            try {
                $validateExistsSymptomList = DB::table('S002V01TLISI')
                    ->where('LISI_NULI', '=', $requestData['NUMERO_LINEA'])
                    ->where('LISI_IDSI', '=', $requestData['ID_SINTOMA'])
                    ->where('LISI_ESTA', '=', 'Activo')
                    ->exists();
            } catch (\Throwable $th) {
                DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG004: Ocurrió un error al consultar la lista de síntomas.", $th->getMessage(), 500);
            }
            if ( !$validateExistsSymptomList ) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG005: No existe el síntoma #".$requestData['ID_SINTOMA']." en la lista de síntomas.", [], 500);
            }
        }

        try {
            $validateExistsMeasure = DB::table('S002V01TLIME')
                ->where('LIME_NULI',  '=', $requestData['NUMERO_LINEA'])
                ->where('LIME_IDME',  '=', $requestData['ID_MEDIDA'])
                ->where('LIME_ESTA',  '=', 'Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG006: Ocurrió un error al consultar la lista de medidas.", $th->getMessage(), 500);
        }
        if ( !$validateExistsMeasure ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG007: No existe la medida #".$requestData['ID_MEDIDA']." en la lista de medidas.", [], 500);
        }

        try {
            $validateExistsEquipment = DB::table('S002V01TEQUI')
                ->where('EQUI_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('EQUI_COEQ', '=', $requestData['CODIGO_EQUIPAMIENTO'])
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG008: Ocurrió un error al consultar los equipamientos.", $th->getMessage(), 500);
        }
        if ( !$validateExistsEquipment ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG009: No existe el equipamiento ".$requestData['CODIGO_EQUIPAMIENTO']." en la lista de equipamientos.", [], 500);
        }

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

        try {
            $validateInsert = DB::table('S002V01TBIFA')->insert([
                'BIFA_NULI' => $requestData['NUMERO_LINEA'],
                'BIFA_COEQ' => $requestData['CODIGO_EQUIPAMIENTO'],
                'BIFA_IDFA' => $requestData['ID_FALLA'],
                'BIFA_IDSI' => $requestData['ID_SINTOMA'],
                'BIFA_FEFA' => $requestData['FECHA_FALLA'],
                'BIFA_REPA' => $requestData['REPARABLE'],
                'BIFA_DESO' => $requestData['SOLUCION'],
                'BIFA_COME' => $requestData['COMENTARIOS'],
                'BIFA_VAOB' => $requestData['VALOR_OBTENIDO'],
                'BIFA_IDME' => $requestData['ID_MEDIDA'],
                'BIFA_USRE' => $user,
                'BIFA_FERE' => $currentDate,
                'BIFA_FEAR' => DB::raw('CURRENT_TIMESTAMP')
            ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG010: Ocurrió un error al intentar registrar la falla en la base de datos.", $th->getMessage(), 500);
        }
        if ( !$validateInsert ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_REG011: No se pudo registrar la falla.", [], 500);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
    }
    public function updateFailureLog(Request $request) {
        $validator = Validator::make($request->all(), [
            'NUMERO_FALLA' => 'required|integer',
            'CODIGO_EQUIPAMIENTO' => 'required|string',
            'ID_FALLA' => 'required|integer',
            // 'ID_SINTOMA' => 'required|integer',
            'FECHA_FALLA' => 'required|string',
            'REPARABLE' => 'required|string',
            'SOLUCION' => 'required|string',
            'COMENTARIOS' => 'required|string',
            'VALOR_OBTENIDO' => 'required|string',
            'ID_MEDIDA' => 'required|string',
            'USUARIO' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_FAILURELOG_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_FAILURELOG_UPD001: No se pudo obtener el usuario.", $th->getMessage(), 500);
        }

        try {
            $validateExistsFailureLog = DB::table('S002V01TBIFA')
                ->where('BIFA_NULI',  '=', $requestData['NUMERO_LINEA'])
                ->where('BIFA_NUFA',  '=', $requestData['NUMERO_FALLA'])
                ->where('BIFA_ESTA',  '=', 'Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD002: Ocurrió un error al consultar la bitácora de fallas.", $th->getMessage(), 500);
        }
        if ( !$validateExistsFailureLog ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD003: No existe la falla #".$requestData['NUMERO_FALLA']." en la bitácora de fallas.", [], 500);
        }

        try {
            $validateExistsFailureList = DB::table('S002V01TLIFA')
                ->where('LIFA_NULI',  '=', $requestData['NUMERO_LINEA'])
                ->where('LIFA_IDFA',  '=', $requestData['ID_FALLA'])
                ->where('LIFA_ESTA',  '=', 'Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD004: Ocurrió un error al consultar la lista de fallas.", $th->getMessage(), 500);
        }
        if ( !$validateExistsFailureList ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD005: No existe la falla #".$requestData['ID_FALLA']." en la lista de fallas.", [], 500);
        }

        if ( !is_null($requestData['ID_SINTOMA']) && $requestData['ID_SINTOMA'] !== '' ) {
            try {
                $validateExistsSymptomList = DB::table('S002V01TLISI')
                    ->where('LISI_NULI', '=', $requestData['NUMERO_LINEA'])
                    ->where('LISI_IDSI', '=', $requestData['ID_SINTOMA'])
                    ->where('LISI_ESTA', '=', 'Activo')
                    ->exists();
            } catch (\Throwable $th) {
                DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD006: Ocurrió un error al consultar la lista de síntomas.", $th->getMessage(), 500);
            }
            if ( !$validateExistsSymptomList ) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD007: No existe el síntoma #".$requestData['ID_SINTOMA']." en la lista de síntomas.", [], 500);
            }
        }

        try {
            $validateExistsMeasure = DB::table('S002V01TLIME')
                ->where('LIME_NULI',  '=', $requestData['NUMERO_LINEA'])
                ->where('LIME_IDME',  '=', $requestData['ID_MEDIDA'])
                ->where('LIME_ESTA',  '=', 'Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD008: Ocurrió un error al consultar la lista de medidas.", $th->getMessage(), 500);
        }
        if ( !$validateExistsMeasure ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD009: No existe la medida #".$requestData['ID_MEDIDA']." en la lista de medidas.", [], 500);
        }

        try {
            $validateExistsEquipment = DB::table('S002V01TEQUI')
                ->where('EQUI_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('EQUI_COEQ', '=', $requestData['CODIGO_EQUIPAMIENTO'])
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD010: Ocurrió un error al consultar los equipamientos.", $th->getMessage(), 500);
        }
        if ( !$validateExistsEquipment ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD011: No existe el equipamiento ".$requestData['CODIGO_EQUIPAMIENTO']." en la lista de equipamientos.", [], 500);
        }

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

        try {
            $validateUpdate = DB::table('S002V01TBIFA')
                ->where('BIFA_NUFA', '=', $requestData['NUMERO_FALLA'])
                ->where('BIFA_NULI', '=', $requestData['NUMERO_LINEA'])
                ->update([
                    'BIFA_COEQ' => $requestData['CODIGO_EQUIPAMIENTO'],
                    'BIFA_IDFA' => $requestData['ID_FALLA'],
                    'BIFA_IDSI' => $requestData['ID_SINTOMA'],
                    'BIFA_FEFA' => $requestData['FECHA_FALLA'],
                    'BIFA_REPA' => $requestData['REPARABLE'],
                    'BIFA_DESO' => $requestData['SOLUCION'],
                    'BIFA_COME' => $requestData['COMENTARIOS'],
                    'BIFA_VAOB' => $requestData['VALOR_OBTENIDO'],
                    'BIFA_IDME' => $requestData['ID_MEDIDA'],
                    'BIFA_USMO' => $user,
                    'BIFA_FEMO' => $currentDate,
                    'BIFA_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD012: Ocurrió un error al intentar modificar la falla en la base de datos.", $th->getMessage(), 500);
        }
        if ( !$validateUpdate ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURELOG_UPD013: No se pudo modificar la bitácora de falla.", [], 500);
        }

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