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

class CatalogFailureController extends Controller
{

    private $responseController;
    private $encController;

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

    public function getFailures($line) {
        try {
            $getFailures = DB::table('S002V01TLIFA')
                ->where('LIFA_NULI', '=', $line)
                ->get([
                    'LIFA_IDFA', // ID_FALLA
                    'LIFA_NOFA', // FALLA
                    'LIFA_ESTA', // ESTADO
                    'LIFA_USRE', // USUARIO_REGISTRA
                    'LIFA_FERE', // FECHA_REGISTRA
                    'LIFA_USMO', // USUARIO_MODIFICA
                    'LIFA_FEMO', // FECHA_MODIFICA
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $getFailures);
    }

    public function getFailuresActives() {
        try {
            $getFailures = DB::table('S002V01TLIFA')
                ->where('LIFA_ESTA', '=', 'Activo')
                ->where('LIFA_NULI', '=', 1)
                ->get([
                    'LIFA_IDFA', // ID_FALLA
                    'LIFA_NOFA', // FALLA
                    'LIFA_ESTA', // ESTADO
                    'LIFA_USRE', // USUARIO_REGISTRA
                    'LIFA_FERE', // FECHA_REGISTRA
                    'LIFA_USMO', // USUARIO_MODIFICA
                    'LIFA_FEMO', // FECHA_MODIFICA
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_FAILURES_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $getFailures);
    }

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

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

        try {
            $user = $this->encController->decrypt($request['USUARIO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: No se pudo obtener el usuario.", [], 500);
        }
        $nameFailures = trim($request['FALLA']);
        $line = $request['NUMERO_LINEA'];
        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();

        $arrInsert = [
            'LIFA_NOFA' => $nameFailures,
            'LIFA_NULI' => $line,
            'LIFA_USRE' => $user,
            'LIFA_FERE' => $currentDate,
            'LIFA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
        ];
        try {
            $validatorRegister = DB::table('S002V01TLIFA')->insert($arrInsert);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: Ocurrió un error al insertar el formulario en la base de datos.", $th, 500);
        }

        if (!$validatorRegister) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG002: No se pudo insertar el formulario en la base de datos.", [], 500);
        }
        DB::commit();
        return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
    }

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

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

        $idFailure = trim($request['ID_FALLA']);
        $nameFailures = trim($request['FALLA']);
        try {
            $user = $this->encController->decrypt($request['USUARIO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: No se pudo obtener el usuario.", [], 500);
        }
        $line = $request['NUMERO_LINEA'];
        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();

        try {
            $exist = DB::table('S002V01TLIFA')->where('LIFA_IDFA', '=', $idFailure)->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_UPD001: Ocurrió un error al consultar en la base de datos.", $th, 500);
        }

        if (!$exist) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_UPD002: No se pudo encontrar el registro dentro de la base de datos.", [], 500);
        }

        $arrUpdate = [
            'LIFA_NOFA' => $nameFailures,
            'LIFA_USMO' => $user,
            'LIFA_FEMO' => $currentDate,
            'LIFA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
        ];
        try {
            $response = DB::table('S002V01TLIFA')->where('LIFA_IDFA', '=', $idFailure)->where('LIFA_NULI', '=', $line)->update($arrUpdate);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_UPD003: Ocurrió un error al modificar el formulario en la base de datos.", $th, 500);
        }

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

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

    }

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

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

        $idFailure = trim($request['ID_FALLA']);
        try {
            $user = $this->encController->decrypt($request['USUARIO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_REG001: No se pudo obtener el usuario.", [], 500);
        }
        $line = $request['NUMERO_LINEA'];
        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();

        try {
            $exist = DB::table('S002V01TLIFA')->where('LIFA_IDFA', '=', $idFailure)->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_DEL001: Ocurrió un error al consultar en la base de datos.", $th, 500);
        }

        if (!$exist) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_DEL002: No se pudo encontrar el registro dentro de la base de datos.", [], 500);
        }

        $arrUpdate = [
            'LIFA_ESTA' => 'Eliminado',
            'LIFA_USMO' => $user,
            'LIFA_FEMO' => $currentDate,
            'LIFA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
        ];
        try {
            $response = DB::table('S002V01TLIFA')->where('LIFA_IDFA', '=', $idFailure)->where('LIFA_NULI', '=', $line)->update($arrUpdate);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_FAILURES_DEL003: Ocurrió un error al modificar el formulario en la base de datos.", $th, 500);
        }

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

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

}
