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

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 RequestLineController extends Controller
{
    private $responseController;
    private $encController;
    private $documentManagementController;
    private $functionsController;
    private $resourcesController;
    public function __construct(){
        $this->responseController = new ResponseController();
        $this->encController = new EncryptionController();
        $this->documentManagementController = new DocumentManagementController();
        $this->functionsController = new FunctionsController();
        $this->resourcesController = new ResourcesController();
    }

    // Se registran las líneas de solicitud
    public function createRequestLine(Request $request){
        $validator = Validator::make($request->all(), [
            'LINE' => 'required|string',
            'USER' => 'required|string',
            'PRODUCTS' => 'required|array',
            'PURPOSE' => 'required',
        ]);

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

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

        $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USER'], $requestData['LINE']);
        if ($arrResponseCheckUser['error']) {
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_REG001:'.$arrResponseCheckUser['msg'], [], 401);
        }
        $user = $arrResponseCheckUser['response'];

        $idOrderPreventive = null;
        if ($requestData['PURPOSE']['PROPOSITO'] == 'MANT-PREV') {
            $idOrderPreventive = $requestData['PURPOSE']['ID'];

            try {
                $validateExistsPreventive = DB::table('S002V01TOTPR')
                    ->where('OTPR_NULI', '=', $requestData['LINE'])
                    ->where('OTPR_IDOT', '=', $idOrderPreventive )
                    ->exists();
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG002: Ocurrió un error al validar la orden de mantenimiento preventivo.", $th->getMessage(), 500);
            }
            if (!$validateExistsPreventive) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG003: La orden de mantenimiento preventivo no existe", [], 500);
            }
        }
        
        $idOrderCorrective = null;
        if ($requestData['PURPOSE']['PROPOSITO'] == 'MANT-CORR') {
            $idOrderCorrective = $requestData['PURPOSE']['ID'];

            try {
                $validateExistsCorrective = DB::table('S002V01TOTCO')
                    ->where('OTCO_NULI', '=', $requestData['LINE'])
                    ->where('OTCO_IDOT', '=', $idOrderCorrective )
                    ->exists();
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG004: Ocurrió un error al validar la orden de mantenimiento correctivo.", $th->getMessage(), 500);
            }
            if (!$validateExistsCorrective) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG005: La orden de mantenimiento correctivo no existe", [], 500);
            }
        }

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

        $arrProviders = array_unique(array_column($requestData['PRODUCTS'], 'NUMERO_PROVEEDOR'));

        foreach ($arrProviders as $provider) {
            try {
                $idRegisterLine = DB::table('S002V01TLINE')->insertGetId([
                    'LINE_NUPR' => $provider,
                    'LINE_OTPR' => $idOrderPreventive,
                    'LINE_OTCO' => $idOrderCorrective,
                    'LINE_NULI' => $requestData['LINE'],
                    'LINE_USRE' => $user,
                    'LINE_FERE' => $currentDate,
                    'LINE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ]);
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG006: Ocurrió un error al hacer la inserción en la base.", $th->getMessage(), 500);
            }
            if ($idRegisterLine == null || $idRegisterLine <= 0) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG007: Ocurrió un error al hacer la inserción en la base.", [], 500);
            }

            $nuar = 0;
            foreach ($requestData['PRODUCTS'] as $products) {
                if ($products['NUMERO_PROVEEDOR'] === $provider) {
                    try {
                        $validateInsert = DB::table('S002V01TARSE')->insert([
                            'ARSE_IDAS' => $nuar,
                            'ARSE_NULI' => $requestData['LINE'],
                            'ARSE_IDLI' => $idRegisterLine,
                            'ARSE_IDAR' => $products['NUMERO_ARTICULO'],
                            'ARSE_NUPR' => $products['NUMERO_PROVEEDOR'],
                            'ARSE_IDIN' => $products['NUMERO_INFORMACION'],
                            'ARSE_USRE' => $user,
                            'ARSE_FERE' => $currentDate,
                            'ARSE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                        ]);
                    } catch (\Throwable $th) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG008: Ocurrió un error al insertar los artículos en la base de datos.", $th->getMessage(), 500);
                    }
                    if (!$validateInsert) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_REG009: No se pudo insertar los datos en la base de datos.", [], 500);
                    }
                    $nuar = $nuar + 1;
                }
            }
        }

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

    public function getAllRequestLines($user, $line) {
        try {
            $arrRequestLines = DB::table('S002V01TLINE')
                ->where("LINE_NULI", "=", $line)
                ->join('S002V01TPROV', 'PROV_NUPR', '=', 'LINE_NUPR')
                ->get([
                    'LINE_IDLI AS ID_LINEA_SOLICITUD',
                    'LINE_NUPR AS NUMERO_PROVEEDOR',
                    'PROV_NOCO AS NOMBRE_COMERCIAL',
                    'LINE_OTPR AS ORDEN_TRABAJO_PREVENTIVO',
                    'LINE_OTCO AS ORDEN_TRABAJO_CORRECTIVO',
                    'LINE_ESTA AS ESTADO',
                    'LINE_USRE AS USUARIO_REGISTRA',
                    'LINE_FERE AS FECHA_REGISTRA',
                    'LINE_USMO AS USUARIO_MODIFICA',
                    'LINE_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_GET000: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }
        $arrRequestLines = json_decode(json_encode($arrRequestLines), true);


        try {
            $arrOrders= DB::table('S002V01TORCO')
                ->where("ORCO_NULI", "=", $line)
                ->get([
                    'ORCO_NUOR AS NUMERO_ORDEN',
                    'ORCO_IDLI AS ID_LINEA_SOLICITUD',
                    'ORCO_IDDE AS ID_DESPACHO',
                    'ORCO_ESTA AS ESTADO',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_GET001: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }
        $arrOrders = json_decode(json_encode($arrOrders), true);


        foreach ($arrRequestLines as $keyRequest => $requestLine) {
            try {
                $getSelected = DB::table('S002V01TARSE')
                    ->where('ARSE_IDLI', '=', $requestLine['ID_LINEA_SOLICITUD'])
                    ->where('ARSE_NULI', '=', $line)
                    ->where('INAR_NULI', '=', $line)
                    ->where('DEAR_NULI', '=', $line)
                    ->where('ARTI_NULI', '=', $line)
                    ->where('FAMI_NULI', '=', $line)
                    ->where('SUBF_NULI', '=', $line)
                    ->where('UNID_NULI', '=', $line)
                    ->join('S002V01TINAR','INAR_IDIN','=','ARSE_IDIN')
                    ->join('S002V01TDEAR','DEAR_IDDE','=','INAR_IDDE')
                    ->join('S002V01TARTI','ARTI_IDAR','=','DEAR_IDAR')
                    ->join('S002V01TFAMI','FAMI_COFA','=','ARTI_COFA')
                    ->join('S002V01TSUBF','SUBF_COSU','=','ARTI_COSU')
                    ->join('S002V01TUNID','UNID_IDUN','=','DEAR_IDUN')
                    ->join('S002V01TCAMO','CAMO_COMO','=','INAR_COMO')
                    ->get([
                        'ARSE_IDAS AS ID_ARTICULO_SELECCIONADO',
                        'ARSE_NUPR AS NUMERO_PROVEEDOR',
                        'ARSE_ESTA AS ESTADO',
                        'INAR_IDIN AS NUMERO_INFORMACION',
                        'INAR_CODI AS CODIGO_INFORMACION',
                        'INAR_MODE AS MODELO_INFORMACION',
                        'CAMO_COMO AS CODIGO_MONEDA',
                        'CAMO_DESC AS MONEDA_DESCRIPCION',
                        'INAR_PREC AS PRECIO_UNITARIO',
                        'INAR_MOMI AS MONTO_MINIMO',
                        'INAR_CARA AS CARACTERISTICAS_INFORMACION',
                        'DEAR_IDDE AS NUMERO_DESCRIPCION',
                        'DEAR_IMAG AS IMAGENES',
                        'DEAR_DESC AS DESCRIPCION',
                        'DEAR_CARA AS CARACTERISTICAS',
                        'DEAR_COWE AS COMPRA_WEB',
                        'ARTI_IDAR AS NUMERO_ARTICULO',
                        'ARTI_CODI AS CODIGO',
                        'ARTI_NOMB AS ARTICULO',
                        'FAMI_COFA AS CODIGO_FAMILIA',
                        'FAMI_NOFA AS NOMBRE_FAMILIA',
                        'SUBF_COSU AS CODIGO_SUBFAMILIA',
                        'SUBF_NOSU AS NOMBRE_SUBFAMILIA',
                        'UNID_IDUN AS ID_UNIDAD',
                        'UNID_NOMB AS NOMBRE_UNIDAD',
                        'UNID_ACRO AS ACRONIMO_UNIDAD',
                    ]);
            } catch (\Throwable $th) {
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_GET002: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
            }
            $arrSelected = json_decode(json_encode($getSelected), true);


            $index = 0;
            $arrArtitles = array();
            foreach ($arrSelected as $keyArtitle => $artitles) {
                if ($keyArtitle === 0) {
                    $arrArtitles[$index] = $artitles;
                    $arrArtitles[$index]['CANTIDAD'] = 1;
                } else {
                    if (
                        in_array($artitles['NUMERO_INFORMACION'], array_column($arrArtitles, 'NUMERO_INFORMACION'))
                    ) {
                        $indexArtitle = array_search($artitles['NUMERO_INFORMACION'], array_column($arrArtitles, 'NUMERO_INFORMACION'));
                        $arrArtitles[$indexArtitle]['CANTIDAD'] = $arrArtitles[$indexArtitle]['CANTIDAD'] + 1;
                    } else {
                        $index = $index + 1;
                        $arrArtitles[$index] = $artitles;
                        $arrArtitles[$index]['CANTIDAD'] = 1;
                    }
                }
            }


            foreach ($arrArtitles as $keySelected => $selected) {
                $arrImagen = json_decode($selected['IMAGENES']);
                $arrUrlImage = array();
                foreach ($arrImagen as $key => $imagen) {
                    $responseDocument = $this->documentManagementController->getPublicDocumentURL($imagen, $user, $line);
                    $arrResponseDocument = json_decode($responseDocument->original, true);
                    if ($arrResponseDocument['error']) {
                        return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_GET003: Ocurrió un error al obtener la URL de la imágen.", [], 500);
                    }
                    $arrUrlImage[] = $arrResponseDocument['response']['public_uri'];
                }
                $arrArtitles[$keySelected]['IMAGENES'] = $arrUrlImage;
            }


            foreach ($arrOrders as $order) {
                if ($requestLine['ID_LINEA_SOLICITUD'] == $order['ID_LINEA_SOLICITUD']) {
                    $requestLine['NUMERO_ORDEN'] = $order['NUMERO_ORDEN'];
                }
            }


            if (!array_key_exists('LINE_NUOR', $requestLine)) {
                $requestLine['NUMERO_ORDEN'] = null;
            }
            $arrRequestLines[$keyRequest] = $requestLine;
            $arrRequestLines[$keyRequest]['SELECTED'] = $arrArtitles;
        }

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

    // Se obtiene una línea de solicitud en específico
    public function getRequestLine($encIdRequestLine, $user, $line){

        try {
            $idRequestLine = $this->encController->decrypt($encIdRequestLine);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_ORDER_GET000: Ocurrió un error al obtener el contenido.", $th->getMessage(), 500);
        }
        try {
            $arrRequestLines = DB::table('S002V01TLINE')
                ->where("LINE_NULI", "=", $line)
                ->where("LINE_IDLI", "=", $idRequestLine)
                ->first([
                    'LINE_IDLI AS ID_LINEA_SOLICITUD',
                    'LINE_ESTA AS ESTADO',
                    'LINE_IDME AS METODO_PAGO',
                    'LINE_FERE AS FECHA_REGISTRA',
                    'LINE_FEMO AS FECHA_MODIFICA',
                    'LINE_USRE AS USUARIO_REGISTRA',
                    'LINE_USMO AS USUARIO_MODIFICA'
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_ORDER_GET001: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        try {
            $arrProducts = DB::table('S002V01TARSE')
                ->where("ARSE_NULI", "=", $line)
                ->where('ARSE_IDLI', '=', $idRequestLine)
                ->where('PROV_ESTA', '=', 'Activo')
                ->join('S002V01TPROV', 'ARSE_NUPR', '=', 'PROV_NUPR')
                ->join('S002V01TINAR', 'ARSE_IDIN', '=', 'INAR_IDIN')
                ->join('S002V01TCAMO', 'CAMO_COMO', '=', 'INAR_COMO')
                ->get([
                    'ARSE_IDAS AS NUMERO_ARTI_SELE',
                    'ARSE_IDAR AS NUMERO_ARTICULO',
                    'ARSE_NUPR AS NUMERO_PRODUCTO',
                    'INAR_MODE AS MODELO',
                    'INAR_CODI AS CODIGO',
                    'INAR_CARA AS CARACTERISTICAS',
                    'ARSE_CANT AS CANTIDAD',
                    'INAR_PREC AS PRECIO_UNITARIO',
                    'CAMO_COMO AS MONEDA',
                    'CAMO_DESC AS MONEDA_DESCRIPCION',
                    // 'ARSE_PRTO AS PRECIO_TOTAL',
                    'ARSE_ESTA AS ESTADO',
                    'ARSE_USRE AS USUARIO_REGISTRA',
                    'ARSE_FERE AS FECHA_REGISTRA',
                    'ARSE_USMO AS USUARIO_MODIFICA',
                    'ARSE_FEMO AS FECHA_MODIFICA',
                    'PROV_NUPR AS NUMERO_PROVEEDOR',
                    'PROV_NOCO AS PROVEEDOR',
                    'PROV_ESTA AS ESTADO_PROVEEDOR'
                ]);

                foreach ($arrProducts as $productos) {
                    if ($productos == 'Eliminado') {
                        return $this->responseController->makeResponse(true, "ERR_ORDER_GET002: Existe un usuario en la solicitud que se encuentra eliminado", [], 500);
                    }
                }

            $arrRequestLines->PRODUCTOS = $arrProducts;
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_ORDER_GET003: No se pudo realizar la consulta a la base.", $th->getMessage(), 500);
        }

        return $this->responseController->makeResponse(false, "ÉXITO", $arrRequestLines);
    }

    // Se cancalan la linea de solicitud de compra
    public function cancelRequestLine(Request $request){
        $validator = Validator::make($request->all(), [
            'ID_LINEA_SOLICITUD' => 'required|string',
            'NUMERO_PROVEEDOR' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
            'USUARIO' => 'required|string',
        ]);

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

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

        $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
        if ($arrResponseCheckUser['error']) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN001:'.$arrResponseCheckUser['msg'], [], 401);
        }
        $user = $arrResponseCheckUser['response'];

        try {
            $requestData['ID_LINEA_SOLICITUD'] = $this->encController->decrypt($requestData['ID_LINEA_SOLICITUD']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN002: Ocurrió un error al desencriptar la línea de solicitud de compra.', $th->getMessage(), 500);
        }
        try {
            $requestData['NUMERO_PROVEEDOR'] = $this->encController->decrypt($requestData['NUMERO_PROVEEDOR']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN003: Ocurrió un error al desencriptar el número de proveedor.', $th->getMessage(), 500);
        }


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


        try {
            $validateExists = DB::table('S002V01TPROV')
                ->where('PROV_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])
                ->where('PROV_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('PROV_ESTA', '=', 'Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN004: Ocurrió un error al verificar el número del proveedor.', $th->getMessage(), 500);
        }
        if (!$validateExists) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN005: El número del proveedor no existe.', [], 500);
        }

        try {
            $validateExists = DB::table('S002V01TLINE')
                ->where('LINE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])
                ->where('LINE_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])
                ->where('LINE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN006: Ocurrió un error al verificar la línea de solicitud de compra.', $th->getMessage(), 500);
        }
        if (!$validateExists) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN007: La linea de solicitud de compra no existe.', [], 500);
        }

        try {
            $validateUpdate = DB::table('S002V01TLINE')
                ->where('LINE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])
                ->where('LINE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('LINE_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])
                ->update([
                    'LINE_ESTA' => 'Cancelado',
                    'LINE_USMO' => $user,
                    'LINE_FEMO' => $currentDate,
                    'LINE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN008: Ocurrió un error al modificar la línea de solicitud de compra.', $th->getMessage(), 500);
        }
        if (!$validateUpdate) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN009: No se pudo cancelar la solicitud de compra.', [], 500);
        }


        try {
            $validateUpdate = DB::table('S002V01TARSE')
                ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('ARSE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])
                ->where('ARSE_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])
                ->update([
                    'ARSE_ESTA' => 'Eliminado',
                    'ARSE_USMO' => $user,
                    'ARSE_FEMO' => $currentDate,
                    'ARSE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN010: Ocurrió un error al modificar la línea de solicitud de compra.', $th->getMessage(), 500);
        }
        if (!$validateUpdate) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_CAN011: No se pudo eliminar los artículos seleccionados.', [], 500);
        }


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

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

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

        $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
        if ($arrResponseCheckUser['error']) {
            return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD004:'.$arrResponseCheckUser['msg'], [], 401);
        }
        $user = $arrResponseCheckUser['response'];

        try {
            $requestData['NUMERO_INFORMACION'] = $this->encController->decrypt($requestData['NUMERO_INFORMACION']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL002: Ocurrió un error al obtener el número de información.", $th->getMessage(), 500);
        }
        try {
            $requestData['ID_LINEA_SOLICITUD'] = $this->encController->decrypt($requestData['ID_LINEA_SOLICITUD']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL003: Ocurrió un error al obtener la línea de solicitud de compra.", $th->getMessage(), 500);
        }
        try {
            $requestData['NUMERO_PROVEEDOR'] = $this->encController->decrypt($requestData['NUMERO_PROVEEDOR']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL004: Ocurrió un error al obtener el número del proveedor.", $th->getMessage(), 500);
        }
        try {
            $requestData['NUMERO_ARTICULO'] = $this->encController->decrypt($requestData['NUMERO_ARTICULO']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL005: Ocurrió un error al obtener el número del artículo.", $th->getMessage(), 500);
        }

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

        try {
            $validateExists = DB::table('S002V01TLINE')
                ->where('LINE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])  
                ->where('LINE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->exists();               
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL006: Ocurrió un error al verificar si existe la línea de solicitud de comrpa.", $th->getMessage(), 500); 
        }
        if (!$validateExists) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL007: El número de línea de solicitud de compra no existe.", [], 500);
        }

        
        try {
            $validateExists = DB::table('S002V01TARTI')
                ->where('ARTI_IDAR', '=', $requestData['NUMERO_ARTICULO'])  
                ->where('ARTI_NULI', '=', $requestData['NUMERO_LINEA'])  
                ->where('ARTI_ESTA', '=', 'Activo')
                ->exists();               
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL008: Ocurrió un error al verificar si existe el número del artículo.", $th->getMessage(), 500); 
        }
        if (!$validateExists) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL009: El número del artículo no existe.", [], 500);
        }

        
        try {
            $validateExists = DB::table('S002V01TPROV')
                ->where('PROV_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])  
                ->where('PROV_NULI', '=', $requestData['NUMERO_LINEA'])  
                ->where('PROV_ESTA', '=', 'Activo')
                ->exists();               
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL010: Ocurrió un error al verificar si existe el número de proveedor.", $th->getMessage(), 500); 
        }
        if (!$validateExists) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL011: El número de proveedor no existe.", [], 500);
        }

        
        try {
            $validateExists = DB::table('S002V01TINAR')
                ->where('INAR_IDIN', '=', $requestData['NUMERO_INFORMACION'])  
                ->where('INAR_NULI', '=', $requestData['NUMERO_LINEA'])  
                ->where('INAR_ESTA', '=', 'Activo')
                ->exists();               
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL012: Ocurrió un error al verificar si existe el numero de información del artículo.", $th->getMessage(), 500); 
        }
        if (!$validateExists) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL013: El número de información del artículo no existe.", [], 500);
        }

        


        try {
            $existsSelected = DB::table('S002V01TARSE')
                ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('ARSE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])
                ->where('ARSE_IDAR', '=', $requestData['NUMERO_ARTICULO'])
                ->where('ARSE_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])
                ->where('ARSE_IDIN', '=', $requestData['NUMERO_INFORMACION'])
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL014: Ocurrió un error al modificar los artículos seleccionados.", $th->getMessage(), 500);
        }
        if (!$existsSelected) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL015: No existen artículos asociados a la información obtenida.", [], 500);
        }
        
        try {
            $validateUpdate = DB::table('S002V01TARSE')
                ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('ARSE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])
                ->where('ARSE_IDAR', '=', $requestData['NUMERO_ARTICULO'])
                ->where('ARSE_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])
                ->where('ARSE_IDIN', '=', $requestData['NUMERO_INFORMACION'])
                ->update([
                    'ARSE_ESTA' => 'Eliminado',
                    'ARSE_USMO' => $user,
                    'ARSE_FEMO' => $currentDate,
                    'ARSE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL016: Ocurrió un error al modificar los artículos seleccionados.", $th->getMessage(), 500);
        }
        if (!$validateUpdate) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL017: Ocurrió un error al eliminar el artículo seleccionado.", [], 500);
        }

        
        try {
            $existsArtitles = DB::table('S002V01TARSE')
                ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->where('ARSE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])
                ->where('ARSE_ESTA', '=', 'Activo')
                ->exists();
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL018: Ocurrió un error al verificar los artículos disponibles.", $th->getMessage(), 500);
        }
        if (!$existsArtitles) {
            try {
                $validateUpdate = DB::table('S002V01TLINE')
                    ->where('LINE_IDLI', '=', $requestData['ID_LINEA_SOLICITUD'])
                    ->where('LINE_NULI', '=', $requestData['NUMERO_LINEA'])
                    ->where('LINE_NUPR', '=', $requestData['NUMERO_PROVEEDOR'])
                    ->update([
                        'LINE_ESTA' => 'Cancelado',
                        'LINE_USMO' => $user,
                        'LINE_FEMO' => $currentDate,
                        'LINE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                    ]);
            } catch (\Throwable $th) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL019: Ocurrió un error al cancelar la línea de solicitud de compra.", $th->getMessage(), 500);
            }
            if (!$validateUpdate) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_DEL020: No se pudo cancelar la línea de solicitud de compra.", [], 500);
            }   
        }

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

    public function updateStatusRequestLine(Request $request) {
        $validator = Validator::make($request->all(), [
            'NUMERO_SOLICITUD' => 'required|string',
            'ESTADO' => 'required|string',
            'USUARIO' => 'required|string',
            'METODO_PAGO' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
            // 'COMENTARIOS' => 'string',
        ]);

        if ($validator->fails()) {
            return $this->responseController->makeResponse(
                true,
                "ERR_ORDER_UPST000: 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_ORDER_UPST001: Ocurrió un error al obtener el usuario.", [], 500);
        }

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

        try {
            $validateUpdate = DB::table('S002V01TLINE')
                ->where('LINE_IDLI', '=', $requestData['NUMERO_SOLICITUD'])
                ->where('LINE_NULI', '=', $requestData['NUMERO_LINEA'])
                ->update([
                    'LINE_ESTA' => $requestData['ESTADO'],
                    'LINE_IDME' => $requestData['METODO_PAGO'],
                    'LINE_COME' => $requestData['COMENTARIOS'] === '' ? null : $requestData['COMENTARIOS'],
                    'LINE_USMO' => $user,
                    'LINE_FEMO' => $currentDate,
                    'LINE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
                ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_ORDER_UPST002: Ocurrió un error al modificar el estado.", $th->getMessage(), 500);
        }

        if ( !$validateUpdate ) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_ORDER_UPST003: No se pudo modificar el estado de la línea de solicitud.", [], 500);
        }

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

    }

    public function getArtitlesByRequestLine($requestLine, $user, $line) {
        try {
            $requestLine = $this->encController->decrypt($requestLine);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_GETBY000: Ocurrió un error al obtener la línea de solicitud.", $th->getMessage(), 500);
        }

        $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
        if ($arrResponseCheckUser['error']) {
            return $this->responseController->makeResponse(true, 'ERR_REQUESTLINE_GETBY001:'.$arrResponseCheckUser['msg'], [], 401);
        }


        try {
            $getArtitleSelected = DB::table('S002V01TARSE')
                ->where('ARSE_IDLI', '=', $requestLine)
                ->where('ARSE_NULI', '=', $line)
                ->where('INAR_NULI', '=', $line)
                ->where('DEAR_NULI', '=', $line)
                ->where('ARTI_NULI', '=', $line)
                ->where('FAMI_NULI', '=', $line)
                ->where('SUBF_NULI', '=', $line)
                ->where('UNID_NULI', '=', $line)
                ->where('ARSE_ESTA', '=', 'Activo')
                ->where('INAR_ESTA', '=', 'Activo')
                ->where('DEAR_ESTA', '=', 'Activo')
                ->where('ARTI_ESTA', '=', 'Activo')
                ->where('FAMI_ESTA', '=', 'Activo')
                ->where('SUBF_ESTA', '=', 'Activo')
                ->where('UNID_ESTA', '=', 'Activo')
                ->join('S002V01TINAR', 'INAR_IDIN', '=', 'ARSE_IDIN')
                ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
                ->join('S002V01TARTI', 'ARTI_IDAR', '=', 'DEAR_IDAR')
                ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'ARTI_COFA')
                ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'ARTI_COSU')
                ->join('S002V01TUNID', 'UNID_IDUN', '=', 'DEAR_IDUN')
                ->join('S002V01TCAMO', 'CAMO_COMO', '=', 'INAR_COMO')
                ->get([
                    'ARTI_IDAR AS NUMERO_ARTICULO',
                    'DEAR_IDDE AS NUMERO_DESCRIPCION',
                    'DEAR_NUPR AS NUMERO_PROVEEDOR',
                    'DEAR_IMAG AS IMAGENES',
                    'ARTI_NOMB AS ARTICULO',
                    'INAR_CARA AS CARACTERISTICAS',
                    'INAR_CODI AS CODIGO',
                    'INAR_MODE AS MODELO',
                    'CAMO_COMO AS MONEDA',
                    'CAMO_DESC AS MONEDA_DESCRIPCION',
                    'INAR_MOMI AS MONTO_MINIMO',
                    'INAR_IDIN AS NUMERO_INFORMACION',
                    'INAR_PREC AS PRECIO',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_GETBY002: Ocurrió un error al obtener la información.", $th->getMessage(), 500);
        }

        $arrArtitleSelected = json_decode(json_encode($getArtitleSelected), true);


        $index = 0;
        $arrArtitles = array();
        foreach ($arrArtitleSelected as $keyArtitle => $artitles) {
            if ($keyArtitle === 0) {
                $arrArtitles[$index] = $artitles;
                $arrArtitles[$index]['CANTIDAD'] = 1;
            } else {
                if (
                    in_array($artitles['NUMERO_INFORMACION'], array_column($arrArtitles, 'NUMERO_INFORMACION'))
                ) {
                    $indexArtitle = array_search($artitles['NUMERO_INFORMACION'], array_column($arrArtitles, 'NUMERO_INFORMACION'));
                    $arrArtitles[$indexArtitle]['CANTIDAD'] = $arrArtitles[$indexArtitle]['CANTIDAD'] + 1;
                } else {
                    $index = $index + 1;
                    $arrArtitles[$index] = $artitles;
                    $arrArtitles[$index]['CANTIDAD'] = 1;
                }
            }
        }
        $arrArtitleSelected = $arrArtitles;

        foreach ($arrArtitleSelected as $keyArtitleSelected => $artitleSelected) {

            $arrImage = json_decode($artitleSelected['IMAGENES']);
            $arrUrlImage = array();
            foreach ($arrImage as $key => $encImage) {
                $responseDocument = $this->documentManagementController->getPublicDocumentURL($encImage, $user, $line);
                $arrResponseDocument = json_decode($responseDocument->original, true);
                if ($arrResponseDocument['error']) {
                    return $this->responseController->makeResponse(true, "ERR_REQUESTLINE_GETBY003: Ocurrió un error al obtener la URL de la imágen.", [], 500);
                }
                $arrUrlImage[] = $arrResponseDocument['response']['public_uri'];
            }

            $artitleSelected['IMAGENES'] = $arrUrlImage;
            $arrArtitleSelected[$keyArtitleSelected] = $artitleSelected;
        }

        return $this->responseController->makeResponse(false, "ÉXITO", $arrArtitleSelected);
    }
}
