HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/qas.sports-crowd.com/app/Core/PagoPass/Application/PagoPassService.php
<?php

declare(strict_types=1);

namespace App\Core\PagoPass\Application;

use App\Core\PagoPass\Entities\IncomeTypeEnum;
use App\Core\PagoPass\Entities\OperationTypeEnum;
use App\Core\Ticket\TicketStatusEnum;
use App\DocumentType;
use App\IntegrationProvider;
use App\TicketMain;
use App\User;
use Carbon\Carbon;
use App\Http\Controllers\UtilController;
use App\Http\Controllers\TicketsController;
use App\Services\TicketParametersService;
use Illuminate\Http\Request;

class PagoPassService
{
    private $utilController;
    private $ticketController;
    private $ticketParametersService;
    protected $timeout = 30; // Response timeout
    protected $connect_timeout = 30; // Connection timeout

    function __construct()
    {
        $this->utilController = new UtilController();
        $this->ticketController = new TicketsController();
        $this->ticketParametersService = new TicketParametersService();
    }

    public function billingPayment(Request $request)
    {
        $validProviderData = $this->validateProviderData();
        if (!$validProviderData['r']) {
            return $validProviderData;
        }
        $providerData = $validProviderData['providerData'];

        $validPaymentData = $this->validatePaymentData($request);
        if (!$validPaymentData['r']) {
            return $validPaymentData;
        }
        $ticketData = $validPaymentData['ticket'];

        $token = $this->login($providerData);
        if (!$token['r']) {
            return $token;
        }

        $data = $this->mapDataBilling($providerData, $ticketData);
        if (!$data['r']) {
            return $data;
        }

        $billing = $this->billing($providerData, $token['data'], $data['data']);
        if (!$billing['r']) {
            $billing['data'] = $data['data'];
            return $billing;
        }
        $this->utilController->logFile(json_encode($billing), "billing");
        $this->updateProviderDataBilling($providerData);
        return $this->updateTicketBilling($ticketData, $billing['data'], $providerData);
    }

    public function notePayment(Request $request)
    {
        $validProviderData = $this->validateProviderData();
        if (!$validProviderData['r']) {
            return $validProviderData;
        }
        $providerData = $validProviderData['providerData'];

        $validPaymentData = $this->validateNotePaymentData($request);
        if (!$validPaymentData['r']) {
            return $validPaymentData;
        }
        $ticketData = $validPaymentData['ticket'];

        $token = $this->login($providerData);
        if (!$token['r']) {
            return $token;
        }

        $data = $this->mapDataNote($providerData, $ticketData);
        if (!$data['r']) {
            return $data;
        }

        $notes = $this->creditNote($providerData, $token['data'], $data['data']);
        if (!$notes['r']) {
            $notes['data'] = $data['data'];
            return $notes;
        }
        $this->utilController->logFile(json_encode($notes), "notes");
        $this->updateProviderDataNote($providerData);
        return $this->updateTicketNote($ticketData, $notes['data'], $providerData);
    }

    private function validateProviderData()
    {
        $providerData = $this->providerData();
        if (!$providerData) {
            return array("r" => false, "m" => __('messages.integrations.provider_not_found'));
        } else if (!$providerData->active) {
            return array("r" => false, "m" => __('messages.integrations.provider_not_active'));
        }
        return array("r" => true, "m" => __('messages.integrations.validate_data_successfully'), 'providerData' => $providerData);
    }

    private function validatePaymentData($request)
    {
        $paymentId = $request->paymentId;
        if (!$paymentId) {
            return array("r" => false, "m" => "PaymentId not found");
        }
        $ticketMain = $this->ticketMain($paymentId);
        if (!$ticketMain) {
            return array("r" => false, "m" => "Purchase not found");
        } else if ($ticketMain->cufe) {
            return array("r" => false, "m" => "Purchase already billed");
        } else if (!$ticketMain->tickets->count()) {
            return array("r" => false, "m" => "Purchase without tickets");
        }

        return array("r" => true, "m" => __('messages.integrations.validate_data_successfully'), "ticket" => $ticketMain);
    }

    private function validateNotePaymentData($request)
    {
        $paymentId = $request->paymentId;
        if (!$paymentId) {
            return array("r" => false, "m" => "PaymentId not found");
        }
        $ticketMain = $this->ticketMain($paymentId);
        if (!$ticketMain) {
            return array("r" => false, "m" => "Purchase not found");
        } else if (!$ticketMain->cufe) {
            return array("r" => false, "m" => "Purchase not billed");
        } else if (!$ticketMain->invoice_number) {
            return array("r" => false, "m" => "Purchase not invoice number");
        } else if (!$ticketMain->tickets->count()) {
            return array("r" => false, "m" => "Purchase without tickets");
        }

        return array("r" => true, "m" => __('messages.integrations.validate_data_successfully'), "ticket" => $ticketMain);
    }

    private function login($providerData)
    {
        try {
            if ($providerData->token && Carbon::parse($providerData->token_expiration)->gt(Carbon::now())) {
                return array("r" => true, "m" => 'Token valid', "data" => $providerData->token);
            }

            $client = new \GuzzleHttp\Client();
            $response = $client->post($providerData->endpoint . "/login", [
                'headers'           => ['Content-type' => 'application/x-www-form-urlencoded'],
                'form_params'       => [
                    'email'         => $providerData->username,
                    'password'      => $providerData->password,
                ],
                'timeout'           => $this->timeout,
                'connect_timeout'   => $this->connect_timeout,
            ]);

            $body = $response->getBody()->getContents();
            $body = json_decode($body, true);
            return $this->mapResponse($providerData, $body);
        } catch (\Exception $e) {
            return array("r" => false, "m" => $e->getMessage());
        }
    }

    private function billing($providerData, $token, $data)
    {
        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->post($providerData->endpoint . "/importar/facturas", [
                'headers'           => ['Content-type' => 'application/x-www-form-urlencoded'],
                'form_params'       => [
                    'tokenOperacion'    => $token,
                    'facturas'          => $data,
                ],
                'timeout'           => $this->timeout,
                'connect_timeout'   => $this->connect_timeout,
            ]);

            $body = $response->getBody()->getContents();
            $body = json_decode($body, true);
            if (!in_array($this->utilController->findValueByKey($body, "code"), [200, 201])) {
                $error = $this->utilController->findValueByKey($body, "error");
                if (!$error || $error == "") {
                    $error = $this->utilController->findValueByKey($body, "mensaje");
                }
                return array("r" => false, "m" => $error);
            }
            return array("r" => true, "m" => 'Billing successfully', "data" => $body);
        } catch (\Exception $e) {
            return array("r" => false, "m" => $e->getMessage());
        }
    }

    private function creditNote($providerData, $token, $data)
    {
        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->post($providerData->endpoint . "/importar/notas", [
                'headers'           => ['Content-type' => 'application/x-www-form-urlencoded'],
                'form_params'       => [
                    'tokenOperacion'    => $token,
                    'facturas'          => $data,
                ],
                'timeout'           => $this->timeout,
                'connect_timeout'   => $this->connect_timeout,
            ]);

            $body = $response->getBody()->getContents();
            $body = json_decode($body, true);
            if (!in_array($this->utilController->findValueByKey($body, "code"), [200, 201])) {
                $error = $this->utilController->findValueByKey($body, "error");
                if (!$error || $error == "") {
                    $error = $this->utilController->findValueByKey($body, "mensaje");
                }
                return array("r" => false, "m" => $error);
            }
            return array("r" => true, "m" => 'Billing successfully', "data" => $body);
        } catch (\Exception $e) {
            return array("r" => false, "m" => $e->getMessage());
        }
    }

    private function updateProviderDataBilling($providerData)
    {
        $providerData->consecutive = $providerData->invoice_consecutive;
        $providerData->last_load_date = Carbon::now();
        $providerData->update();
    }

    private function updateProviderDataNote($providerData)
    {
        $providerData->consecutive = $providerData->credit_note_consecutive;
        $providerData->last_load_date = Carbon::now();
        $providerData->update();
    }

    private function updateTicketBilling($ticketMain, $billing, $providerData)
    {
        $ticketMainId = $this->utilController->findValueByKey($billing, "id_transaction");
        if ($ticketMainId && $ticketMain->id != intval($ticketMainId)) {
            $ticketMain = $this->ticketMain($ticketMainId);
        }

        $invoiceNumber = $this->utilController->findValueByKey($billing, "numFac");
        if ($invoiceNumber) {
            $ticketMain->invoice_number = $invoiceNumber;
        } else if ($numFac = $this->getNumFac($this->utilController->findValueByKey($billing, "QR"))) {
            $ticketMain->invoice_number = $numFac;
        }

        $invoiceLink = $this->utilController->findValueByKey($billing, "pdf_base64");
        if ($invoiceLink) {
            $ticketMain->invoice_link = $invoiceLink;
        }

        $cufe = $this->utilController->findValueByKey($billing, "cufe");
        if ($cufe) {
            $ticketMain->cufe = $cufe;
        }

        $ticketMain->update();
        return array("r" => true, "m" => 'Update billing successfully', "data" => $billing);
    }

    private function updateTicketNote($ticketMain, $creditNote)
    {
        $ticketMainId = $this->utilController->findValueByKey($creditNote, "id_transaction");
        if ($ticketMainId && $ticketMain->id != intval($ticketMainId)) {
            $ticketMain = $this->ticketMain($ticketMainId);
        }

        $noteCreditNumber = $this->utilController->findValueByKey($creditNote, "numNota");
        if ($noteCreditNumber) {
            $ticketMain->credit_note_invoice_number = $noteCreditNumber;
        } else if ($numFac = $this->getNumFac($this->utilController->findValueByKey($creditNote, "QR"))) {
            $ticketMain->credit_note_invoice_number = $numFac;
        }

        $noteCreditLink = $this->utilController->findValueByKey($creditNote, "pdf_base64");
        if ($noteCreditLink) {
            $ticketMain->credit_note_invoice_link = $noteCreditLink;
        }

        // Por retorno del servicio del proveedor se utiliza misma variable cufe para nota de credito "cude"
        $cude = $this->utilController->findValueByKey($creditNote, "cufe");
        if ($cude) {
            $ticketMain->cude = $cude;
        }

        $ticketMain->update();
        return array("r" => true, "m" => 'Update credit note successfully', "data" => $creditNote);
    }

    private function providerData()
    {
        return IntegrationProvider::where('alias', 'pago-pass')->where('active', 1)->first();
    }

    private function mapResponse($providerData, $body)
    {
        $token = $this->utilController->findValueByKey($body, "tokenOperacion");
        if ($token) {
            $tokenExpiration = $this->utilController->findValueByKey($body, "expire");
            $this->refreshToken($providerData, $token, $tokenExpiration);
            return array("r" => true, "m" => 'token successfully', "data" => $token);
        } else {
            return array("r" => false, "m" => 'token not found');
        }
    }

    private function refreshToken($providerData, $token, $tokenExpiration)
    {
        $providerData->token = $token;
        $providerData->token_expiration = Carbon::parse($tokenExpiration);
        $providerData->update();
    }

    private function mapDataBilling($providerData, $ticketMain)
    {
        $user           = $this->user($ticketMain);
        $defaultData    = $this->defaultData($providerData);
        $this->incrementInvoiceConsecutive($providerData);
        $documentUser   = $this->documentUser($user);

        $purchaseOrder                  = $this->purchaseOrder($ticketMain);
        $letter                         = $providerData->invoice_letter;
        $resolution                     = $providerData->invoice_resolution;
        $identification                 = strval($documentUser ? $user->document : $defaultData->identification);
        $documentType                   = strval($this->documentType($user->document_type_id));
        $typePerson                     = 2;
        $businessName                   = strtoupper($documentUser ? $user->first_name . " " . $user->last_name : $defaultData->businessName);
        $tradeName                      = strtoupper($documentUser ? $user->first_name . " " . $user->last_name : $defaultData->tradeName);
        $address                        = strtoupper(count($user->addresses) > 0 ? $user->addresses[0]->direction : $defaultData->address);
        $city                           = $defaultData->city;
        $phone                          = $documentUser ? $user->phone : $defaultData->phone;
        $email                          = $documentUser ? $user->email : $defaultData->email;
        $responsability                 = $this->responsability();
        $transactionDate                = $this->date();
        $percentageRteSource            = 0.0;
        $rteSource                      = 0;
        $percentageRteIVA               = null;
        $rteIVA                         = null;
        $percentageRteICA               = null;
        $rteICA                         = null;
        $voucherType                    = "INVOIC";
        $invoiceType                    = "01";
        $currency                       = $providerData->currency ?? $defaultData->currency;
        $dueDate                        = $this->date();
        $notes                          = strtoupper("Boleteria con referencia/pin: " . $purchaseOrder);
        $transactionType                = "1";
        $paymentMethodType              = $this->paymentMethodType($ticketMain);
        $productServiceQuantity         = "1";
        $productServiceUnitType         = "WSD";
        $taxType                        = "01";
        $taxValue                       = $this->taxValue();
        $discountPercentage             = 0;
        $discountDescription            = "NO DISCOUNT";
        $updateProduct                  = "NO";
        $publicPrice                    = "0";
        $shippingGuide                  = $ticketMain->pin;
        $seller                         = config('app.name');
        $lineNumber                     = count($ticketMain->tickets);
        $deliveryNote                   = "";
        $operationType                  = OperationTypeEnum::INVOICE;

        $mandateInvoice = $this->ticketParametersService->enableElectronicBillingByMandate();
        $commissionMandate = $this->ticketParametersService->electronicBillingByMandateCommission();
        $taxValueMandate = $this->ticketParametersService->electronicBillingByMandateIvaPercentage();
        $identificationMandante = $this->ticketParametersService->electronicBillingByMandateIdentificationClientOrganization();
        $identificationOwner = $this->ticketParametersService->electronicBillingByMandateIdentificationOwnerOrganization();

        $data = [];
        $taxValueServiceCharge = 0;
        if ($this->enableElectronicInvoiceServiceCharge() && $ticketMain->service_charge) {
            $taxValueServiceCharge = $this->taxServiceChargeValue();
        }
        foreach ($ticketMain->tickets as $ticket) {
            if (!in_array($ticket->ticket_status_id, [TicketStatusEnum::PURCHASED, TicketStatusEnum::CREATED])) {
                continue;
            }

            $ticketPrice = $ticket->price;
            $ownPrice = 0;
            $incomeType = IncomeTypeEnum::CLIENT;
            if ($mandateInvoice) {
                $operationType = OperationTypeEnum::MANDATE_INVOICE;
                $commission = $ticket->price * ($commissionMandate / 100);
                $ticketPrice = $ticket->price - $commission;
                $ownPrice = $commission;
                $incomeType = IncomeTypeEnum::THIRD_PARTY;
            }
            $item = [
                "id_transaction"                    => $ticketMain->id,
                "LetraFactura"                      => $letter,
                "ResolucionFacturacionElectronica"  => $resolution,
                "Identificacion"                    => $identification,
                "TipoDocumento"                     => $documentType,
                "TipoPersona"                       => $typePerson,
                "RazonSocial"                       => $businessName,
                "NombreComercial"                   => $tradeName,
                "Direccion"                         => $address,
                "Ciudad"                            => $city,
                "Telefono"                          => $phone,
                "Correo"                            => $email,
                "TipoResponsabilidad"               => $responsability,
                "FechaTransaccionCartera"           => $transactionDate,
                "Porcentaje_RTE_FUENTE"             => $percentageRteSource,
                "RTE_FUENTE"                        => $rteSource,
                "Porcentaje_RTE_IVA"                => $percentageRteIVA,
                "RTE_IVA"                           => $rteIVA,
                "Porcentaje_RTE_ICA"                => $percentageRteICA,
                "RTE_ICA"                           => $rteICA,
                "TipoComprobante"                   => $voucherType,
                "TipoFactura"                       => $invoiceType,
                "TipoMoneda"                        => $currency,
                "FechaVencimiento"                  => $dueDate,
                "Notas"                             => $notes,
                "TipoTransaccion"                   => $transactionType,
                "TipoMedioPago"                     => $paymentMethodType,
                "IdProductoServicio"                => $ticket->id,
                "CantidadProductoServicio"          => $productServiceQuantity,
                "NombreProductoServicio"            => $this->nameProductService($ticket),
                "TipoUnidadMedidaProductoServicio"  => $productServiceUnitType,
                "InfoAdicionalProductoServicio"     => strtoupper($this->ticketController->ticketDoor($ticket) . " - Evento " . $this->ticketController->ticketCodeEvent($ticket)),
                "ValorProductoServicio"             => strval($ticketPrice - ($ownPrice * ($taxValueMandate / 100)) - (($ticketMain->service_charge / count($ticketMain->tickets)) * ($taxValueServiceCharge / 100))),
                "TipoImpuesto"                      => $taxType,
                "ValorImpuesto"                     => $taxValue,
                "Porcentaje_Dcto"                   => $discountPercentage,
                "Descripcion_Dcto"                  => $discountDescription,
                "ActualizarProducto"                => $updateProduct,
                "guia_envio"                        => $shippingGuide,
                "p_publico"                         => $publicPrice,
                "vendedor"                          => $seller,
                "numero_lineas"                     => $lineNumber,
                "remision"                          => $deliveryNote,
                "Orden_compra"                      => $purchaseOrder,
                "TipoOperacion"                     => $operationType,
                "TipoIngreso"                       => $incomeType,
                "IdentificacionMandante"            => $identificationMandante,
            ];
            $data[] = $item;

            if ($mandateInvoice) {
                if ($ownPrice > 0) {
                    $item["NombreProductoServicio"] = strtoupper("Comisión");
                    $item["InfoAdicionalProductoServicio"] = '';
                    $item["ValorProductoServicio"] = $ownPrice;
                    $item["ValorImpuesto"] = $taxValueMandate;
                    $item["TipoIngreso"] = IncomeTypeEnum::OWN;
                    $item["IdentificacionMandante"] = $identificationOwner;
                    $data[] = $item;
                }
            }
        }
        if ($this->enableElectronicInvoiceServiceCharge() && $ticketMain->service_charge) {
            $data[] = [
                "id_transaction"                    => $ticketMain->id,
                "LetraFactura"                      => $letter,
                "ResolucionFacturacionElectronica"  => $resolution,
                "Identificacion"                    => $identification,
                "TipoDocumento"                     => $documentType,
                "TipoPersona"                       => $typePerson,
                "RazonSocial"                       => $businessName,
                "NombreComercial"                   => $tradeName,
                "Direccion"                         => $address,
                "Ciudad"                            => $city,
                "Telefono"                          => $phone,
                "Correo"                            => $email,
                "TipoResponsabilidad"               => $responsability,
                "FechaTransaccionCartera"           => $transactionDate,
                "Porcentaje_RTE_FUENTE"             => $percentageRteSource,
                "RTE_FUENTE"                        => $rteSource,
                "Porcentaje_RTE_IVA"                => $percentageRteIVA,
                "RTE_IVA"                           => $rteIVA,
                "Porcentaje_RTE_ICA"                => $percentageRteICA,
                "RTE_ICA"                           => $rteICA,
                "TipoComprobante"                   => $voucherType,
                "TipoFactura"                       => $invoiceType,
                "TipoMoneda"                        => $currency,
                "FechaVencimiento"                  => $dueDate,
                "Notas"                             => $notes,
                "TipoTransaccion"                   => $transactionType,
                "TipoMedioPago"                     => $paymentMethodType,
                "IdProductoServicio"                => $ticketMain->id,
                "CantidadProductoServicio"          => $productServiceQuantity,
                "NombreProductoServicio"            => strtoupper("Cobro de Servicio u/o Impresión"),
                "TipoUnidadMedidaProductoServicio"  => $productServiceUnitType,
                "InfoAdicionalProductoServicio"     => '',
                "ValorProductoServicio"             => $ticketMain->service_charge,
                "TipoImpuesto"                      => $taxType,
                "ValorImpuesto"                     => $taxValueServiceCharge,
                "Porcentaje_Dcto"                   => $discountPercentage,
                "Descripcion_Dcto"                  => $discountDescription,
                "ActualizarProducto"                => $updateProduct,
                "guia_envio"                        => $shippingGuide,
                "p_publico"                         => $publicPrice,
                "vendedor"                          => $seller,
                "numero_lineas"                     => $lineNumber,
                "remision"                          => $deliveryNote,
                "Orden_compra"                      => $purchaseOrder,
                "TipoOperacion"                     => $operationType,
                "TipoIngreso"                       => IncomeTypeEnum::OWN,
                "IdentificacionMandante"            => $identificationOwner,
            ];
        }
        $data = json_encode([$data]);
        return array("r" => true, "m" => "Data successfully", "data" => $data);
    }

    private function mapDataNote($providerData, $ticketMain)
    {
        $user           = $this->user($ticketMain);
        $defaultData    = $this->defaultData($providerData);
        $this->incrementCreditNoteConsecutive($providerData);
        $documentUser   = $this->documentUser($user);

        $purchaseOrder                  = $this->purchaseOrder($ticketMain);
        $letter                         = $providerData->credit_note_letter;
        $resolution                     = $providerData->credit_note_resolution;
        $billingNumber                  = $this->billingNumber($ticketMain);
        $identification                 = strval($documentUser ? $user->document : $defaultData->identification);
        $documentType                   = $this->documentType($user->document_type_id);
        $typePerson                     = 2;
        $businessName                   = strtoupper($documentUser ? $user->first_name . " " . $user->last_name : $defaultData->businessName);
        $tradeName                      = strtoupper($documentUser ? $user->first_name . " " . $user->last_name : $defaultData->tradeName);
        $address                        = strtoupper(count($user->addresses) > 0 ? $user->addresses[0]->direction : $defaultData->address);
        $city                           = $defaultData->city;
        $phone                          = $documentUser ? $user->phone : $defaultData->phone;
        $email                          = $documentUser ? $user->email : $defaultData->email;
        $responsability                 = $this->responsability();
        $transactionDate                = $this->date();
        $percentageRteSource            = 0.0;
        $rteSource                      = 0;
        $percentageRteIVA               = null;
        $rteIVA                         = null;
        $percentageRteICA               = null;
        $rteICA                         = null;
        $voucherType                    = $letter;
        $type                           = "91";
        $currency                       = $providerData->currency ?? $defaultData->currency;
        $dueDate                        = $this->date();
        $notes                          = strtoupper("Boleteria con referencia/pin: " . $purchaseOrder);
        $transactionType                = "1";
        $codeConcept                    = "6";
        $productServiceQuantity         = "1";
        $productServiceUnitType         = "WSD";
        $taxType                        = "01";
        $taxValue                       = $this->taxValue();
        $discountPercentage             = 0;
        $discountDescription            = "NO DISCOUNT";
        $seller                         = config('app.name');
        $lineNumber                     = count($ticketMain->tickets);
        $deliveryNote                   = "";
        $operationType                  = OperationTypeEnum::CREDIT_NOTE;

        $data = [];
        foreach ($ticketMain->tickets as $ticket) {
            $data[] = [
                "id_transaction"                    => $ticketMain->id,
                "LetraNota"                         => $letter,
                "ResolucionFacturacionElectronica"  => $resolution,
                "numeroFactura"                     => $billingNumber,
                "Identificacion"                    => $identification,
                "TipoDocumento"                     => $documentType,
                "TipoPersona"                       => $typePerson,
                "RazonSocial"                       => $businessName,
                "NombreComercial"                   => $tradeName,
                "Direccion"                         => $address,
                "Ciudad"                            => $city,
                "Telefono"                          => $phone,
                "Correo"                            => $email,
                "TipoResponsabilidad"               => $responsability,
                "FechaTransaccionCartera"           => $transactionDate,
                "Porcentaje_RTE_FUENTE"             => $percentageRteSource,
                "RTE_FUENTE"                        => $rteSource,
                "Porcentaje_RTE_IVA"                => $percentageRteIVA,
                "RTE_IVA"                           => $rteIVA,
                "Porcentaje_RTE_ICA"                => $percentageRteICA,
                "RTE_ICA"                           => $rteICA,
                "TipoComprobante"                   => $voucherType,
                "TipoNota"                          => $type,
                "TipoMoneda"                        => $currency,
                "FechaVencimiento"                  => $dueDate,
                "TipoOperacion"                     => $operationType,
                "CodigoConceptoNot"                 => $codeConcept,
                "Notas"                             => $notes,
                "TipoTransaccion"                   => $transactionType,
                "IdProductoServicio"                => $ticket->id,
                "CantidadProductoServicio"          => $productServiceQuantity,
                "NombreProductoServicio"            => $this->nameProductService($ticket),
                "TipoUnidadMedidaProductoServicio"  => $productServiceUnitType,
                "InfoAdicionalProductoServicio"     => strtoupper($this->ticketController->ticketDoor($ticket) . " - Evento " . $this->ticketController->ticketCodeEvent($ticket)),
                "vendedor"                          => $seller,
                "ValorProductoServicio"             => strval($ticket->price / (1 + ($taxValue / 100))),
                "TipoImpuesto"                      => $taxType,
                "ValorImpuesto"                     => $taxValue,
                "Porcentaje_Dcto"                   => $discountPercentage,
                "Descripcion_Dcto"                  => $discountDescription,
                "numero_lineas"                     => $lineNumber,
                "remision"                          => $deliveryNote,
                "Orden_compra"                      => $purchaseOrder
            ];
        }
        $data = json_encode([$data]);
        return array("r" => true, "m" => "Data successfully", "data" => $data);
    }

    private function user($ticket)
    {
        return User::withTrashed()->with('addresses')->find($ticket->user_id_log);
    }

    private function ticketMain($ticketMainId)
    {
        return TicketMain::with('tickets')->find($ticketMainId);
    }

    private function defaultData($providerData)
    {
        return $providerData->default_data ? json_decode($providerData->default_data) : [];
    }

    private function incrementInvoiceConsecutive($providerData)
    {
        if (!$providerData->invoice_consecutive) {
            $providerData->invoice_consecutive = 1;
        } else {
            $providerData->invoice_consecutive = $providerData->invoice_consecutive + 1;
        }
    }

    private function incrementCreditNoteConsecutive($providerData)
    {
        if (!$providerData->credit_note_consecutive) {
            $providerData->credit_note_consecutive = 1;
        } else {
            $providerData->credit_note_consecutive = $providerData->credit_note_consecutive + 1;
        }
    }

    private function billingNumber($ticket)
    {
        $billingNumber = $ticket->invoice_number;
        return $billingNumber;
    }

    private function paymentMethodType($ticket)
    {
        // 10 Efetivo, 47 PSE y 48 Tarjeta Credito
        $paymentMethodType = 47;
        if ($ticket->seller_user_id) {
            $paymentMethodType = 10;
        } else if ($ticket->gateway_response && str_contains($ticket->gateway_response, "CARD")) {
            $paymentMethodType = 48;
        }

        return $paymentMethodType;
    }

    private function documentType($documentTypeId)
    {
        // 13 persona natural y 15 persona juridica
        $documentType = 13;
        if ($documentTypeId && DocumentType::find($documentTypeId)->alias == "NIT") {
            $documentType = 15;
        }
        return $documentType;
    }

    private function purchaseOrder($ticket)
    {
        $purchaseOrder = $ticket->id;
        if ($ticket->payment_reference) {
            $purchaseOrder = $ticket->payment_reference;
        } else if ($ticket->reference_tercero) {
            $purchaseOrder = $ticket->reference_tercero;
        } else if ($ticket->pin_internal) {
            $purchaseOrder = $ticket->pin_internal;
        } else if ($ticket->pin_tercero) {
            $purchaseOrder = $ticket->pin_tercero;
        }
        return $purchaseOrder;
    }

    private function taxValue()
    {
        return $this->ticketParametersService->ivaPercentageTickets();
    }

    private function taxServiceChargeValue()
    {
        return $this->ticketParametersService->ivaPercentageServiceCharge();
    }

    private function enableElectronicInvoiceServiceCharge()
    {
        return $this->ticketParametersService->enableElectronicInvoiceServiceCharge();
    }

    private function responsability()
    {
        return 'R-99-PN';
    }

    private function date()
    {
        return Carbon::now()->format('Y-m-d H:i:s');
    }

    private function getNumFac($qr)
    {
        preg_match('/NumFac:([^\n]+)/', $qr, $matches);
        if (isset($matches[1])) {
            $numFac = $matches[1];
            return $numFac;
        }
        return null;
    }

    private function nameProductService($ticket)
    {
        if (!$ticket) {
            return "";
        }
        $type = $this->ticketController->ticketTypeName($ticket);
        $locationTicket = $this->ticketController->ticketSeatLocationFullText($ticket);
        $name = strtoupper($type . ' ' . $locationTicket);
        return $name;
    }

    private function documentUser($user)
    {
        $validDocumentUser = true;
        if (!$user->document || strlen($user->document) < 6) {
            $validDocumentUser = false;
        } else if ($user->email == 'webticketing@gmail.com') {
            $validDocumentUser = false;
        }
        return $validDocumentUser;
    }
}