<?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 CatalogMeasuresController extends Controller
{
    private $responseController;
    private $encController;

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

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

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

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

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

        $measurement = trim($request['MEDIDA']);
        $acronym = trim($request['ACRONIMO']);
        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.", $th, 500);
        }
        $line = $request['NUMERO_LINEA'];
        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();

        $arrInsert = [
            'LIME_MEDI' => $measurement,
            'LIME_ACRO' => $acronym,
            'LIME_NULI' => $line,
            'LIME_USRE' => $user,
            'LIME_FERE' => $currentDate,
            'LIME_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
        ];
        try {
            $response = DB::table('S002V01TLIME')->insert($arrInsert);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_REG001: Ocurrió un error al insertar el formulario en la base de datos.", $th, 500);
        }

        if (!$response) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_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 updateMeasures(Request $request) {
        $validator = Validator::make($request->all(), [
            'ID_MEDIDA' => 'required|string',
            'MEDIDA' => 'required|string',
            'ACRONIMO' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
            'USUARIO' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_MEASUREMENT_UPD000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($validator->errors()->messages()),
                401
            );
        }

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

        $idMeasures = trim($request['ID_MEDIDA']);
        $measurement = trim($request['MEDIDA']);
        $acronym = trim($request['ACRONIMO']);
        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('S002V01TLIME')->where('LIME_IDME', '=', $idMeasures)->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_UPD001: Ocurrió un error al consultar en la base de datos.", $th, 500);
        }

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

        $arrUpdate = [
            'LIME_MEDI' => $measurement,
            'LIME_ACRO' => $acronym,
            'LIME_USMO' => $user,
            'LIME_FEMO' => $currentDate,
            'LIME_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
        ];
        try {
            $response = DB::table('S002V01TLIME')->where('LIME_IDME', '=', $idMeasures)->where('LIME_NULI', '=', $line)->update($arrUpdate);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_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_MEASUREMENT_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 deleteMeasures(Request $request) {
        $validator = Validator::make($request->all(), [
            'ID_MEDIDA' => 'required|integer',
            'NUMERO_LINEA' => 'required|integer',
            'USUARIO' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_MEASUREMENT_DEL000: Se encontraron uno o más errores.",
                $this->responseController->makeErrors($validator->errors()->messages()),
                401
            );
        }

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

        $idMeasures = trim($request['ID_MEDIDA']);
        $line = $request['NUMERO_LINEA'];
        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();
        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);
        }

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

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

        $arrUpdate = [
            'LIME_ESTA' => 'Eliminado',
            'LIME_USMO' => $user,
            'LIME_FEMO' => $currentDate,
            'LIME_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
        ];
        try {
            $response = DB::table('S002V01TLIME')->where('LIME_IDME', '=', $idMeasures)->where('LIME_NULI', '=', $line)->update($arrUpdate);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_MEASUREMENT_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_MEASUREMENT_DEL004: No se pudo modificar el formulario en la base de datos.", [], 500);
        }

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

}
