<?php
/*
    Desarrollador: Ing. Jean Jairo Benitez Meza
    Ultima Modificación: 11/04/2023
    Módulo: Gestión de Adquisiciones
*/
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 ProviderController extends Controller{

    private $responseController;
    private $encController;

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

    public function getAllProvider($line){
        try {
            $arrProvider = DB::table('S002V01TPROV')
                ->where('PROV_NULI', '=', $line)
                ->get([
                    'PROV_NUPR AS NUMERO_PROVEEDOR',
                    'PROV_NOCO AS RAZON_SOCIAL',
                    'PROV_NOMB AS NOMBRE',
                    'PROV_APPA AS PRIMER_APELLIDO',
                    'PROV_APMA AS SEGUNDO_APELLIDO',
                    'PROV_CORR AS CORREO',
                    'PROV_LAD1 AS LADA1',
                    'PROV_TEL1 AS TELEFONO1',
                    'PROV_LAD2 AS LADA2',
                    'PROV_TEL2 AS TELEFONO2',
                    'PROV_XRFC AS RFC',
                    'PROV_XTAX AS TAXID',
                    'PROV_GIRO AS GIRO_EMPRESA',
                    'PROV_TIPO AS TIPO_EMPRESA',
                    'PROV_SIWE AS SITIO_WEB',
                    'PROV_MEPA AS METODO_PAGO',
                    'PROV_ESTA AS ESTADO',
                    'PROV_USRE AS USUARIO_REGISTRA',
                    'PROV_FERE AS FECHA_REGISTRA',
                    'PROV_USMO AS USUARIO_MODIFICA',
                    'PROV_FEMO AS FECHA_MODIFICA',
                ]);


            $arrResponse = array();
            foreach ($arrProvider as $provider) {
                $provider = (array) $provider;
                $provider['SEGUNDO_APELLIDO'] = $provider['SEGUNDO_APELLIDO'] == null ? '' : $provider['SEGUNDO_APELLIDO'];

                $arrReferences = DB::table('S002V01TPRRE')
                    ->where('PRRE_NULI', '=', $line)
                    ->where('PRRE_ESTA', '=', 'Activo')
                    ->where('PRRE_NUPR', '=', $provider['NUMERO_PROVEEDOR'])
                    ->get([
                        'PRRE_IDRE AS NUMERO_REFERENCIA',
                        'PRRE_EMPR AS EMPRESA',
                        'PRRE_CORR AS CORREO',
                        'PRRE_LADA AS LADA',
                        'PRRE_TELE AS TELEFONO',
                        'PRRE_XRFC AS RFC',
                        'PRRE_DIRE AS DIRECCION',
                        'PRRE_ESTA AS ESTADO',
                        'PRRE_USRE AS USUARIO_REGISTRA',
                        'PRRE_FERE AS FECHA_REGISTRA',
                        'PRRE_USMO AS USUARIO_MODIFICA',
                        'PRRE_FEMO AS FECHA_MODIFICA',
                    ]);

                $arrContacts = DB::table('S002V01TPRCO')
                    ->where('PRCO_NULI', '=', $line)
                    ->where('PRCO_ESTA', '=', 'Activo')
                    ->where('PRCO_NUPR', '=', $provider['NUMERO_PROVEEDOR'])
                    ->get([
                        'PRCO_IDCP AS NUMERO_CONTACTO',
                        'PRCO_NOMB AS NOMBRE_CONTACTO',
                        'PRCO_TIPO AS TIPO_CONTACTO',
                        'PRCO_CALL AS CALLE',
                        'PRCO_NUEX AS NUMERO_EXTERIOR',
                        'PRCO_NUIN AS NUMERO_INTERIOR',
                        'PRCO_COPO AS CODIGO_POSTAL',
                        'PRCO_MUNI AS MUNICIPIO',
                        'PRCO_ENTI AS ENTIDAD',
                        'PRCO_PAIS AS PAIS',
                        'PRCO_LAD1 AS LADA1',
                        'PRCO_TEL1 AS TELEFONO1',
                        'PRCO_LAD2 AS LADA2',
                        'PRCO_TEL2 AS TELEFONO2',
                        'PRCO_COR1 AS CORREO1',
                        'PRCO_COR2 AS CORREO2',
                        'PRCO_OBSE AS OBSERVACIONES',
                        'PRCO_ESTA AS ESTADO',
                        'PRCO_USRE AS USUARIO_REGISTRA',
                        'PRCO_FERE AS FECHA_REGISTRA',
                        'PRCO_USMO AS USUARIO_MODIFICA',
                        'PRCO_FEMO AS FECHA_MODIFICA',
                    ]);

                $arrConditions = DB::table('S002V01TPRCN')
                    ->where('PRCN_NULI', '=', $line)
                    ->where('PRCN_ESTA', '=', 'Activo')
                    ->where('PRCN_NUPR', '=', $provider['NUMERO_PROVEEDOR'])
                    ->get([
                        'PRCN_IDCM AS NUMERO_CONDICION',
                        'PRCN_TIPO AS TIPO_CONDICION',
                        'PRCN_INFO AS INFORMACION',
                        'PRCN_ESTA AS ESTADO',
                        'PRCN_USRE AS USUARIO_REGISTRA',
                        'PRCN_FERE AS FECHA_REGISTRA',
                        'PRCN_USMO AS USUARIO_MODIFICA',
                        'PRCN_FEMO AS FECHA_MODIFICA',
                    ]);

                $arrCatalogs = DB::table('S002V01TPRCE')
                    ->where('PRCE_NULI', '=', $line)
                    ->where('PRCE_ESTA', '=', 'Activo')
                    ->where('PRCE_NUPR', '=', $provider['NUMERO_PROVEEDOR'])
                    ->get([
                        'PRCE_IDCE AS NUMERO_CATALAGO',
                        'PRCE_CATA AS CATALAGO',
                        'PRCE_DESC AS DESCRIPCION',
                        'PRCE_XURL AS URL_CATALAGO',
                        'PRCE_ESTA AS ESTADO',
                        'PRCE_USRE AS USUARIO_REGISTRA',
                        'PRCE_FERE AS FECHA_REGISTRA',
                        'PRCE_USMO AS USUARIO_MODIFICA',
                        'PRCE_FEMO AS FECHA_MODIFICA',
                    ]);


                $arrPayment = json_decode($provider['METODO_PAGO']);

                $arrPaymentFormat = array();
                foreach ($arrPayment as $key => $payment) {
                    $arrPaymentFormat[] = [
                        'name' => $key,
                        'completed' => $payment,
                    ];
                }

                $provider['REFERENCIAS'] = $arrReferences;
                $provider['CONTACTOS'] = $arrContacts;
                $provider['CONDICIONES'] = $arrConditions;
                $provider['CATALAGOS'] = $arrCatalogs;
                $provider['METODOS_PAGO'] = $arrPaymentFormat;

                $arrResponse[] = $provider;
            }


        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }

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

    public function getProvidersActives($line) {
        try {
            $arrProvider = DB::table('S002V01TPROV')
                ->where('PROV_ESTA', '=', 'Activo')
                ->where('PROV_NULI', '=', $line)
                ->get([
                    'PROV_NUPR AS NUMERO_PROVEEDOR',
                    'PROV_NOCO AS RAZON_SOCIAL',
                    'PROV_NOMB AS NOMBRE',
                    'PROV_APPA AS PRIMER_APELLIDO',
                    'PROV_APMA AS SEGUNDO_APELLIDO',
                    'PROV_CORR AS CORREO',
                    'PROV_LAD1 AS LADA1',
                    'PROV_TEL1 AS TELEFONO1',
                    'PROV_LAD2 AS LADA2',
                    'PROV_TEL2 AS TELEFONO2',
                    'PROV_XRFC AS RFC',
                    'PROV_XTAX AS TAXID',
                    'PROV_GIRO AS GIRO_EMPRESA',
                    'PROV_TIPO AS TIPO_EMPRESA',
                    'PROV_SIWE AS SITIO_WEB',
                    'PROV_MEPA AS METODO_PAGO',
                    'PROV_USRE AS USUARIO_REGISTRA',
                    'PROV_FERE AS FECHA_REGISTRA',
                    'PROV_USMO AS USUARIO_MODIFICA',
                    'PROV_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrProvider);
    }

    public function getProvidersByNumber($provider, $line) {
        try {
            $arrProvider = DB::table('S002V01TPROV')
                ->where('PROV_NUPR', '=', $provider)
                ->where('PROV_ESTA', '=', 'Activo')
                ->where('PROV_NULI', '=', $line)
                ->first([
                    'PROV_NUPR AS NUMERO_PROVEEDOR',
                    'PROV_NOCO AS RAZON_SOCIAL',
                    'PROV_NOMB AS NOMBRE',
                    'PROV_APPA AS PRIMER_APELLIDO',
                    'PROV_APMA AS SEGUNDO_APELLIDO',
                    'PROV_CORR AS CORREO',
                    'PROV_LAD1 AS LADA1',
                    'PROV_TEL1 AS TELEFONO1',
                    'PROV_LAD2 AS LADA2',
                    'PROV_TEL2 AS TELEFONO2',
                    'PROV_XRFC AS RFC',
                    'PROV_XTAX AS TAXID',
                    'PROV_GIRO AS GIRO_EMPRESA',
                    'PROV_TIPO AS TIPO_EMPRESA',
                    'PROV_SIWE AS SITIO_WEB',
                    'PROV_MEPA AS METODO_PAGO',
                    'PROV_USRE AS USUARIO_REGISTRA',
                    'PROV_FERE AS FECHA_REGISTRA',
                    'PROV_USMO AS USUARIO_MODIFICA',
                    'PROV_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }
        return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrProvider);

    }

    public function updateProvider(Request $request) {
        $validator = Validator::make($request->all(), [
            'line' => 'required|string',
            'user' => 'required|string',
            'obj_response' => 'required|string',
        ]);

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

        DB::beginTransaction();
        $requestData = $request->all();
        $line = $requestData['line'];

        try {
            $user = $this->encController->decrypt($request['user']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD001: No se pudo obtener el usuario.", [], 500);
        }
        try {
            $obj_response = json_decode($requestData['obj_response']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD002: Ocurrió un error al obtener los datos del proveedor.", $th, 500);
        }

        $arrInformationPersonal = (array) $obj_response->INFORMACION;
        $arrReferences = (array) $obj_response->REFERENCIAS;
        $arrContacts = (array) $obj_response->CONTACTOS;
        $arrConditions = (array) $obj_response->CONDICIONES;
        $arrPaymentMedia = (array) $obj_response->METODOS_PAGO;
        $arrCatalogs = (array) $obj_response->CATALAGOS;

        $numeroProveedor = $arrInformationPersonal['NUMERO_PROVEEDOR'];
        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();

        $arrPaymentTemp = array();
        foreach ($arrPaymentMedia as $payment) {
            $arrPaymentTemp[$payment->name] = $payment->completed;
        }
        try {
            $strPayment = json_encode($arrPaymentTemp);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD003: Ocurrió un error al obtener los datos del método de pago.", $th, 500);
        }

        $updatePersonal = [
            'PROV_NOCO' => $arrInformationPersonal['RAZON_SOCIAL'],
            'PROV_NOMB' => $arrInformationPersonal['NOMBRE'],
            'PROV_APPA' => $arrInformationPersonal['PRIMER_APELLIDO'],
            'PROV_APMA' => $arrInformationPersonal['SEGUNDO_APELLIDO'] != '' ? $arrInformationPersonal['SEGUNDO_APELLIDO'] : null,
            'PROV_CORR' => $arrInformationPersonal['CORREO'],
            'PROV_LAD1' => $arrInformationPersonal['LADA1'],
            'PROV_TEL1' => $arrInformationPersonal['TELEFONO1'],
            'PROV_LAD2' => $arrInformationPersonal['LADA2'] != '' ? $arrInformationPersonal['LADA2'] : null,
            'PROV_TEL2' => $arrInformationPersonal['TELEFONO2'] != '' ? $arrInformationPersonal['TELEFONO2'] : null,
            'PROV_XRFC' => $arrInformationPersonal['RFC'],
            'PROV_XTAX' => $arrInformationPersonal['TAXID'] != '' ? $arrInformationPersonal['TAXID'] : null,
            'PROV_GIRO' => $arrInformationPersonal['GIRO_EMPRESA'],
            'PROV_TIPO' => $arrInformationPersonal['TIPO_EMPRESA'],
            'PROV_SIWE' => $arrInformationPersonal['SITIO_WEB'],
            'PROV_MEPA' => $strPayment,
            'PROV_USMO' => $user,
            'PROV_FEMO' => $currentDate,
            'PROV_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];
        try {
            $resp = DB::table('S002V01TPROV')->where('PROV_NUPR', '=', $numeroProveedor)->where('PROV_NULI', '=', $line)->update($updatePersonal);
            if (!$resp) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD004: Ocurrió un error al obtener el contenido.", [], 500);
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD005: Ocurrió un error al obtener el contenido.", $th->getMessage(), 500);
        }

        foreach ($arrReferences as $references) {
            if ($references->ESTADO == 'Activo' || $references->ESTADO == 'Modificado') {
                $updateReferences = [
                    'PRRE_EMPR' => $references->EMPRESA,
                    'PRRE_CORR' => $references->CORREO,
                    'PRRE_LADA' => $references->LADA,
                    'PRRE_TELE' => $references->TELEFONO,
                    'PRRE_XRFC' => $references->RFC,
                    'PRRE_DIRE' => $references->DIRECCION,
                    'PRRE_USMO' => $user,
                    'PRRE_FEMO' => $currentDate,
                    'PRRE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRRE')
                        ->where('PRRE_IDRE', '=', $references->NUMERO_REFERENCIA)
                        ->where('PRRE_NUPR', '=', $numeroProveedor)
                        ->where('PRRE_NULI', '=', $line)
                        ->update($updateReferences);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD006: Ocurrió un error al obtener el contenido. ", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD007: Ocurrió un error al obtener el contenido.", $th->getMessage(), 500);
                }
            }else if($references->ESTADO == 'Nuevo') {
                $insertReferences = [
                    'PRRE_NUPR' => $numeroProveedor,
                    'PRRE_EMPR' => $references->EMPRESA,
                    'PRRE_CORR' => $references->CORREO,
                    'PRRE_LADA' => $references->LADA,
                    'PRRE_TELE' => $references->TELEFONO,
                    'PRRE_XRFC' => $references->RFC,
                    'PRRE_DIRE' => $references->DIRECCION,
                    'PRRE_NULI' => $line,
                    'PRRE_USRE' => $user,
                    'PRRE_FERE' => $currentDate,
                    'PRRE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRRE')->insert($insertReferences);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD008: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD009: Ocurrió un error al obtener el contenido.", $th->getMessage(), 500);
                }
            } else if($references->ESTADO == 'Eliminado'){
                $updateReferences = [
                    'PRRE_ESTA' => 'Eliminado',
                    'PRRE_USMO' => $user,
                    'PRRE_FEMO' => $currentDate,
                    'PRRE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRRE')
                        ->where('PRRE_IDRE', '=', $references->NUMERO_REFERENCIA)
                        ->where('PRRE_NUPR', '=', $numeroProveedor)
                        ->where('PRRE_NULI', '=', $line)
                        ->update($updateReferences);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD010: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD011: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }
        }

        foreach ($arrContacts as $contacts) {
            if ($contacts->ESTADO == 'Activo' && $contacts->ESTADO == 'Modificado') {
                $updateContacts = [
                    'PRCO_NOMB' => $contacts->NOMBRE_CONTACTO,
                    'PRCO_TIPO' => $contacts->TIPO_CONTACTO,
                    'PRCO_CALL' => $contacts->CALLE,
                    'PRCO_NUEX' => $contacts->NUMERO_EXTERIOR,
                    'PRCO_NUIN' => $contacts->NUMERO_INTERIOR != '' ? $contacts->NUMERO_INTERIOR : null,
                    'PRCO_COPO' => $contacts->CODIGO_POSTAL,
                    'PRCO_MUNI' => $contacts->MUNICIPIO,
                    'PRCO_ENTI' => $contacts->ENTIDAD,
                    'PRCO_PAIS' => $contacts->PAIS,
                    'PRCO_TEL1' => $contacts->TELEFONO1,
                    'PRCO_TEL2' => $contacts->TELEFONO2 != '' ? $contacts->TELEFONO2 : null,
                    'PRCO_COR1' => $contacts->CORREO1,
                    'PRCO_COR2' => $contacts->CORREO2 != '' ? $contacts->CORREO2 : null,
                    'PRCO_OBSE' => $contacts->OBSERVACIONES,
                    'PRCO_USMO' => $user,
                    'PRCO_FEMO' => $currentDate,
                    'PRCO_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCO')
                        ->where('PRCO_IDCP', '=', $contacts->NUMERO_CONTACTO)
                        ->where('PRCO_NUPR', '=', $numeroProveedor)
                        ->where('PRCO_NULI', '=', $line)
                        ->update($updateContacts);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD012: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD013: Ocurrió un error al obtener el contenido.", $th, 500);
                }

            }else if($contacts->ESTADO == 'Nuevo'){
                $insertContacts = [
                    'PRCO_NUPR' => $numeroProveedor,
                    'PRCO_NOMB' => $contacts->NOMBRE_CONTACTO,
                    'PRCO_TIPO' => $contacts->TIPO_CONTACTO,
                    'PRCO_CALL' => $contacts->CALLE,
                    'PRCO_NUEX' => $contacts->NUMERO_EXTERIOR,
                    'PRCO_NUIN' => $contacts->NUMERO_INTERIOR != '' ? $contacts->NUMERO_INTERIOR : null,
                    'PRCO_COPO' => $contacts->CODIGO_POSTAL,
                    'PRCO_MUNI' => $contacts->MUNICIPIO,
                    'PRCO_ENTI' => $contacts->ENTIDAD,
                    'PRCO_PAIS' => $contacts->PAIS,
                    'PRCO_LAD1' => $contacts->LADA1,
                    'PRCO_TEL1' => $contacts->TELEFONO1,
                    'PRCO_LAD2' => $contacts->LADA2 != '' ? $contacts->LADA2 : null,
                    'PRCO_TEL2' => $contacts->TELEFONO2 != '' ? $contacts->TELEFONO2 : null,
                    'PRCO_COR1' => $contacts->CORREO1,
                    'PRCO_COR2' => $contacts->CORREO2 != '' ? $contacts->CORREO2 : null,
                    'PRCO_OBSE' => $contacts->OBSERVACIONES,
                    'PRCO_NULI' => $line,
                    'PRCO_USRE' => $user,
                    'PRCO_FERE' => $currentDate,
                    'PRCO_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCO')->insert($insertContacts);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD014: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD015: Ocurrió un error al obtener el contenido.", $th->getMessage(), 500);
                }
            }else if($contacts->ESTADO == 'Eliminado'){
                $updateContacts = [
                    'PRCO_ESTA' => 'Eliminado',
                    'PRCO_USMO' => $user,
                    'PRCO_FEMO' => $currentDate,
                    'PRCO_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCO')
                        ->where('PRCO_IDCP', '=', $contacts->NUMERO_CONTACTO)
                        ->where('PRCO_NUPR', '=', $numeroProveedor)
                        ->where('PRCO_NULI', '=', $line)
                        ->update($updateContacts);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD016: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD017: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }
        }

        foreach ($arrConditions as $conditions) {
            if ($conditions->ESTADO == 'Activo' && $conditions->ESTADO == 'Modificado') {
                $updateConditions = [
                    'PRCN_TIPO' => $conditions->TIPO_CONDICION,
                    'PRCN_INFO' => $conditions->INFORMACION,
                    'PRCN_USMO' => $user,
                    'PRCN_FEMO' => $currentDate,
                    'PRCN_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCN')
                        ->where('PRCN_IDCM', '=', $conditions->NUMERO_CONDICION)
                        ->where('PRCN_NUPR', '=', $numeroProveedor)
                        ->where('PRCN_NULI', '=', $line)
                        ->update($updateConditions);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD018: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD019: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }else if($conditions->ESTADO == 'Nuevo'){
                $insertConditions = [
                    'PRCN_NUPR' => $numeroProveedor,
                    'PRCN_TIPO' => $conditions->TIPO_CONDICION,
                    'PRCN_INFO' => $conditions->INFORMACION,
                    'PRCN_NULI' => $line,
                    'PRCN_USRE' => $user,
                    'PRCN_FERE' => $currentDate,
                    'PRCN_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCN')->insert($insertConditions);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD020: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD021: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }else if ($conditions->ESTADO == 'Eliminado'){
                $updateConditions = [
                    'PRCN_ESTA' => 'Eliminado',
                    'PRCN_USMO' => $user,
                    'PRCN_FEMO' => $currentDate,
                    'PRCN_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCN')
                        ->where('PRCN_IDCM', '=', $conditions->NUMERO_CONDICION)
                        ->where('PRCN_NUPR', '=', $numeroProveedor)
                        ->where('PRCN_NULI', '=', $line)
                        ->update($updateConditions);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD022: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD023: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }
        }

        foreach ($arrCatalogs as $catalogs) {
            if ($catalogs->ESTADO == 'Activo' || $catalogs->ESTADO == 'Modificado') {
                $updateCatalogs = [
                    'PRCE_CATA' => $catalogs->CATALAGO,
                    'PRCE_DESC' => $catalogs->DESCRIPCION,
                    'PRCE_XURL' => $catalogs->URL_CATALAGO,
                    'PRCE_USMO' => $user,
                    'PRCE_FEMO' => $currentDate,
                    'PRCE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCE')
                        ->where('PRCE_IDCE', '=', $catalogs->NUMERO_CATALAGO)
                        ->where('PRCE_NUPR', '=', $numeroProveedor)
                        ->where('PRCE_NULI', '=', $line)
                        ->update($updateCatalogs);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD024: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD025: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }else if($catalogs->ESTADO == 'Nuevo'){
                $insertCatalogs = [
                    'PRCE_NUPR' => $numeroProveedor,
                    'PRCE_CATA' => $catalogs->CATALAGO,
                    'PRCE_DESC' => $catalogs->DESCRIPCION,
                    'PRCE_XURL' => $catalogs->URL_CATALAGO,
                    'PRCE_NULI' => $line,
                    'PRCE_USRE' => $user,
                    'PRCE_FERE' => $currentDate,
                    'PRCE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCE')->insert($insertCatalogs);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD026: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD027: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }else if($catalogs->ESTADO == 'Eliminado'){
                $updateCatalogs = [
                    'PRCE_ESTA' => 'Eliminado',
                    'PRCE_USMO' => $user,
                    'PRCE_FEMO' => $currentDate,
                    'PRCE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCE')
                        ->where('PRCE_IDCE', '=', $catalogs->NUMERO_CATALAGO)
                        ->where('PRCE_NUPR', '=', $numeroProveedor)
                        ->where('PRCE_NULI', '=', $line)
                        ->update($updateCatalogs);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD028: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_MOD029: Ocurrió un error al obtener el contenido.", $th, 500);
                }
            }
        }

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

    public function registerProvider(Request $request) {
        $validator = Validator::make($request->all(), [
            'line' => 'required|string',
            'user' => 'required|string',
            'obj_response' => 'required|string',
        ]);

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

        DB::beginTransaction();
        $requestData = $request->all();
        $line = $requestData['line'];

        try {
            $user = $this->encController->decrypt($requestData['user']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG001: Ocurrió un error al obtener el usuario.", [], 500);
        }
        try {
            $obj_response = json_decode($requestData['obj_response']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG002: Ocurrió un error al obtener los datos del proveedor.", [], 500);
        }

        $arrInformationPersonal = (array) $obj_response->INFORMACION;
        $arrReferences = (array) $obj_response->REFERENCIAS;
        $arrContacts = (array) $obj_response->CONTACTOS;
        $arrConditions = (array) $obj_response->CONDICIONES;
        $arrPaymentMedia = (array) $obj_response->METODOS_PAGO;
        $arrCatalogs = (array) $obj_response->CATALAGOS;

        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();

        $arrPaymentTemp = array();
        foreach ($arrPaymentMedia as $payment) {
            $arrPaymentTemp[$payment->name] = $payment->completed;
        }

        try {
            $strPayment = json_encode($arrPaymentTemp);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG003: Ocurrió un error al obtener los métodos de pago del proveedor.", [], 500);
        }

        $insertPersonal = [
            'PROV_NOCO' => $arrInformationPersonal['RAZON_SOCIAL'],
            'PROV_NOMB' => $arrInformationPersonal['NOMBRE'],
            'PROV_APPA' => $arrInformationPersonal['PRIMER_APELLIDO'],
            'PROV_APMA' => $arrInformationPersonal['SEGUNDO_APELLIDO'] != '' ? $arrInformationPersonal['SEGUNDO_APELLIDO'] : null,
            'PROV_CORR' => $arrInformationPersonal['CORREO'],
            'PROV_LAD1' => $arrInformationPersonal['LADA1'],
            'PROV_TEL1' => $arrInformationPersonal['TELEFONO1'],
            'PROV_LAD2' => $arrInformationPersonal['LADA2'] != '' ? $arrInformationPersonal['LADA2'] : null,
            'PROV_TEL2' => $arrInformationPersonal['TELEFONO2'] != '' ? $arrInformationPersonal['TELEFONO2'] : null,
            'PROV_XRFC' => $arrInformationPersonal['RFC'],
            'PROV_XTAX' => $arrInformationPersonal['TAXID'] != '' ? $arrInformationPersonal['TAXID'] : null,
            'PROV_GIRO' => $arrInformationPersonal['GIRO_EMPRESA'],
            'PROV_TIPO' => $arrInformationPersonal['TIPO_EMPRESA'],
            'PROV_SIWE' => $arrInformationPersonal['SITIO_WEB'],
            'PROV_MEPA' => $strPayment,
            'PROV_NULI' => $line,
            'PROV_USRE' => $user,
            'PROV_FERE' => $currentDate,
            'PROV_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];
        try {
            $idProdiver = DB::table('S002V01TPROV')->insertGetId($insertPersonal);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG004: Ocurrió un error al obtener el contenido.", [], 500);
        }

        foreach ($arrReferences as $references) {
            if ($references->ESTADO == 'Activo') {
                $insertReferences = [
                    'PRRE_NUPR' => $idProdiver,
                    'PRRE_EMPR' => $references->EMPRESA,
                    'PRRE_CORR' => $references->CORREO,
                    'PRRE_LADA' => $references->LADA,
                    'PRRE_TELE' => $references->TELEFONO,
                    'PRRE_XRFC' => $references->RFC,
                    'PRRE_DIRE' => $references->DIRECCION,
                    'PRRE_NULI' => $line,
                    'PRRE_USRE' => $user,
                    'PRRE_FERE' => $currentDate,
                    'PRRE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRRE')->insert($insertReferences);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG005: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG006: Ocurrió un error al obtener el contenido.", $th->getMessage(), 500);
                }
            }
        }

        foreach ($arrContacts as $contacts) {
            if ($contacts->ESTADO == 'Activo') {
                $insertContacts = [
                    'PRCO_NUPR' => $idProdiver,
                    'PRCO_NOMB' => $contacts->NOMBRE_CONTACTO,
                    'PRCO_TIPO' => $contacts->TIPO_CONTACTO,
                    'PRCO_CALL' => $contacts->CALLE,
                    'PRCO_NUEX' => $contacts->NUMERO_EXTERIOR,
                    'PRCO_NUIN' => $contacts->NUMERO_INTERIOR != '' ? $contacts->NUMERO_INTERIOR : null,
                    'PRCO_COPO' => $contacts->CODIGO_POSTAL,
                    'PRCO_MUNI' => $contacts->MUNICIPIO,
                    'PRCO_ENTI' => $contacts->ENTIDAD,
                    'PRCO_PAIS' => $contacts->PAIS,
                    'PRCO_LAD1' => $contacts->LADA1,
                    'PRCO_TEL1' => $contacts->TELEFONO1,
                    'PRCO_LAD2' => $contacts->LADA2 != '' ? $contacts->LADA2 : null,
                    'PRCO_TEL2' => $contacts->TELEFONO2 != '' ? $contacts->TELEFONO2 : null,
                    'PRCO_COR1' => $contacts->CORREO1,
                    'PRCO_COR2' => $contacts->CORREO2 != '' ? $contacts->CORREO2 : null,
                    'PRCO_OBSE' => $contacts->OBSERVACIONES,
                    'PRCO_NULI' => $line,
                    'PRCO_USRE' => $user,
                    'PRCO_FERE' => $currentDate,
                    'PRCO_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCO')->insert($insertContacts);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG007: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG008: Ocurrió un error al obtener el contenido.", $th->getMessage(), 500);
                }
            }
        }

        foreach ($arrConditions as $conditions) {
            if ($conditions->ESTADO == 'Activo') {
                $insertConditions = [
                    'PRCN_NUPR' => $idProdiver,
                    'PRCN_TIPO' => $conditions->TIPO_CONDICION,
                    'PRCN_INFO' => $conditions->INFORMACION,
                    'PRCN_NULI' => $line,
                    'PRCN_USRE' => $user,
                    'PRCN_FERE' => $currentDate,
                    'PRCN_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCN')->insert($insertConditions);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG009: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG010: Ocurrió un error al obtener el contenido.", [], 500);
                }
            }
        }

        foreach ($arrCatalogs as $catalogs) {
            if ($catalogs->ESTADO == 'Activo') {
                $insertCatalogs = [
                    'PRCE_NUPR' => $idProdiver,
                    'PRCE_CATA' => $catalogs->CATALAGO,
                    'PRCE_DESC' => $catalogs->DESCRIPCION,
                    'PRCE_XURL' => $catalogs->URL_CATALAGO,
                    'PRCE_NULI' => $line,
                    'PRCE_USRE' => $user,
                    'PRCE_FERE' => $currentDate,
                    'PRCE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
                ];
                try {
                    $resp = DB::table('S002V01TPRCE')->insert($insertCatalogs);
                    if (!$resp) {
                        DB::rollBack();
                        return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG011: Ocurrió un error al obtener el contenido.", [], 500);
                    }
                } catch (\Throwable $th) {
                    DB::rollBack();
                    return $this->responseController->makeResponse(true, "ERR_PROVIDER_REG012: Ocurrió un error al obtener el contenido.", [], 500);
                }
            }
        }

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

    public function deleteProvider(Request $request) {
        $validator = Validator::make($request->all(), [
            'line' => 'required|string',
            'user' => 'required|string',
            'numero_proveedor' => 'required|string'
        ]);

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

        DB::beginTransaction();
        $requestData = $request->all();
        $currentDate = Carbon::now()->timezone('America/Mazatlan')->toDateTimeString();
        $line = $requestData['line'];

        try {
            $numeroProveedor = $this->encController->decrypt($requestData['numero_proveedor']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL001: Ocurrió un error al obtener el número del proveedor.", [], 500);
        }
        try {
            $user = $this->encController->decrypt($requestData['user']);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL002: Ocurrió un error al obtener el contenido.", [], 500);
        }

        $update = [
            'PROV_ESTA' => 'Eliminado',
            'PROV_USMO' => $user,
            'PROV_FEMO' => $currentDate,
            'PROV_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];
        try {
            $resp = DB::table('S002V01TPROV')->where('PROV_NUPR', '=', $numeroProveedor)->where('PROV_NULI', '=', $line)->update($update);
            if (!$resp) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL003: Ocurrió un error al obtener el contenido. ", [], 500);
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL004: Ocurrió un error al obtener el contenido.", [], 500);
        }

        $update = [
            'PRRE_ESTA' => 'Eliminado',
            'PRRE_USMO' => $user,
            'PRRE_FEMO' => $currentDate,
            'PRRE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];
        try {
            $resp = DB::table('S002V01TPRRE')->where('PRRE_NUPR', '=', $numeroProveedor)->where('PRRE_NULI', '=', $line)->update($update);
            if (!$resp) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL005: Ocurrió un error al obtener el contenido. ", [], 500);
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL006: Ocurrió un error al obtener el contenido.", [], 500);
        }

        $update = [
            'PRCO_ESTA' => 'Eliminado',
            'PRCO_USMO' => $user,
            'PRCO_FEMO' => $currentDate,
            'PRCO_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];
        try {
            $resp = DB::table('S002V01TPRCO')->where('PRCO_NUPR', '=', $numeroProveedor)->where('PRCO_NULI', '=', $line)->update($update);
            if (!$resp) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL007: Ocurrió un error al obtener el contenido. ", [], 500);
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL008: Ocurrió un error al obtener el contenido.", [], 500);
        }

        $update = [
            'PRCN_ESTA' => 'Eliminado',
            'PRCN_USMO' => $user,
            'PRCN_FEMO' => $currentDate,
            'PRCN_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];
        try {
            $resp = DB::table('S002V01TPRCN')->where('PRCN_NUPR', '=', $numeroProveedor)->where('PRCN_NULI', '=', $line)->update($update);
            if (!$resp) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL009: Ocurrió un error al obtener el contenido. ", [], 500);
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL010: Ocurrió un error al obtener el contenido.", [], 500);
        }

        $update = [
            'PRCE_ESTA' => 'Eliminado',
            'PRCE_USMO' => $user,
            'PRCE_FEMO' => $currentDate,
            'PRCE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
        ];
        try {
            $resp = DB::table('S002V01TPRCE')->where('PRCE_NUPR', '=', $numeroProveedor)->where('PRCE_NULI', '=', $line)->update($update);
            if (!$resp) {
                DB::rollBack();
                return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL011: Ocurrió un error al obtener el contenido. ", [], 500);
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_DEL012: Ocurrió un error al obtener el contenido.", [], 500);
        }

        DB::commit();
        return $this->responseController->makeResponse(false, "EXITO: Eliminación correcta",);

    }

    public function getProviderByArtitle(Request $request) {
        $validator = Validator::make($request->all(), [
            'NUMERO_ARTICULO' => 'required|string',
            'NUMERO_LINEA' => 'required|string',
        ]);

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

        $response = $request->all();
        $numeroArticulo = $this->encController->decrypt($response['NUMERO_ARTICULO']);
        try {
            $arrDescription = DB::table('S002V01TDEAR')
                ->where('DEAR_ESTA', '=', 'Activo')
                ->where('DEAR_IDAR', '=', $numeroArticulo)
                ->join('S002V01TPROV', 'DEAR_NUPR', '=', 'PROV_NUPR')
                ->get([
                    'DEAR_IDDE AS NUMERO_DESCRIPTION',
                    'PROV_NUPR AS NUMERO_PROVEEDOR',
                    'PROV_NOCO AS RAZON_SOCIAL',
                    'PROV_NOMB AS NOMBRE',
                    'PROV_APPA AS PRIMER_APELLIDO',
                    'PROV_APMA AS SEGUNDO_APELLIDO',
                    'PROV_CORR AS CORREO',
                    'PROV_LAD1 AS LADA1',
                    'PROV_TEL1 AS TELEFONO1',
                    'PROV_LAD2 AS LADA2',
                    'PROV_TEL2 AS TELEFONO2',
                    'PROV_XRFC AS RFC',
                    'PROV_XTAX AS TAXID',
                    'PROV_GIRO AS GIRO_EMPRESA',
                    'PROV_TIPO AS TIPO_EMPRESA',
                    'PROV_SIWE AS SITIO_WEB',
                    'PROV_MEPA AS METODO_PAGO',
                    'PROV_ESTA AS ESTADO',
                    'PROV_USRE AS USUARIO_REGISTRA',
                    'PROV_FERE AS FECHA_REGISTRA',
                    'PROV_USMO AS USUARIO_MODIFICA',
                    'PROV_FEMO AS FECHA_MODIFICA',
                ]);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(true, "ERR_PROVIDER_GET000: No se pudo realizar la consulta a la base.", [], 500);
        }

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

    }
}
