<?php

declare (strict_types = 1);

namespace SmsNotifier;

use Psr\Log\LogLevel;
use SmsNotifier\Facade\PluginNotifierFacade;
use SmsNotifier\Facade\PluginOxxoNotifierFacade;
use SmsNotifier\Facade\TwilioNotifierFacade;
use SmsNotifier\Factory\NotificationDataFactory;
use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\PluginDataValidator;
use Twilio\Exceptions\TwilioException;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;

class Plugin
{
    /**
     * @var Logger
     */
    private $logger;

    /**
     * @var OptionsManager
     */
    private $optionsManager;

    /**
     * @var PluginDataValidator
     */
    private $pluginDataValidator;

    /**
     * @var PluginNotifierFacade
     */
    private $pluginNotifierFacade;
    /**
     * @var PluginOxxoNotifierFacade
     */
    private $pluginOxxoNotifierFacade;
    /**
     * @var TwilioNotifierFacade
     */
    private $notifierFacade;

    /**
     * @var NotificationDataFactory
     */
    private $notificationDataFactory;

    /**
     * @var UcrmApi
     */
    protected $ucrmApi;

    public function __construct(
        Logger $logger,
        OptionsManager $optionsManager,
        PluginDataValidator $pluginDataValidator,
        TwilioNotifierFacade $notifierFacade,
        PluginNotifierFacade $pluginNotifierFacade,
        PluginOxxoNotifierFacade $pluginOxxoNotifierFacade,
        NotificationDataFactory $notificationDataFactory
    ) {
        $this->logger                   = $logger;
        $this->optionsManager           = $optionsManager;
        $this->pluginDataValidator      = $pluginDataValidator;
        $this->notifierFacade           = $notifierFacade;
        $this->pluginNotifierFacade     = $pluginNotifierFacade;
        $this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade;
        $this->notificationDataFactory  = $notificationDataFactory;
    }

    public function run(): void
    {
        // $hola = PHP_SAPI;
        // $this->logger->info('valor de PHP_SAPI: ' . $hola);
        if (PHP_SAPI === 'fpm-fcgi') {
            // $this->logger->debug('Whatsapp over HTTP started');
            $this->processHttpRequest();
            // $this->logger->debug('HTTP request processing ended.');
        } elseif (PHP_SAPI === 'cli') {
            // $this->logger->debug('Whatsapp over CLI started');
            $this->processCli();
            // $this->logger->debug('CLI process ended.');
        } else {
            throw new \UnexpectedValueException('Unknown PHP_SAPI type: ' . PHP_SAPI);
        }

    }

    private function processCli(): void
    {
        if ($this->pluginDataValidator->validate()) {
            $this->logger->info('Validating config');
            $this->optionsManager->load();
        }
    }

    private function processHttpRequest(): void
    {
        $pluginData = $this->optionsManager->load();
        if ($pluginData->logging_level) {
            $this->logger->setLogLevelThreshold(LogLevel::DEBUG);
        }

        $userInput = file_get_contents('php://input'); //se recibe el json del webhook
                                                       //imprimir el json del webhook
        $this->logger->debug('valor del webhook: ' . $userInput . PHP_EOL);

        if (! $userInput) {
            $this->logger->warning('no input');

            return;
        }

        $jsonData = @json_decode($userInput, true, 50);

        if (! isset($jsonData['uuid'])) {
            $this->logger->info('No UUID found in the webhook data');
            //$this->logger->error('JSON error: ' . json_last_error_msg());

            //return;

            // Maneja el evento del webhook externo
            if ($jsonData) {
                switch ($jsonData['type']) {
                    case 'customer_cash_balance_transaction.created':
                        if ($jsonData['data']['object']['type'] === 'funded') {
                            $this->logger->info('Evento de transferencia de un cliente recibido: ' . json_encode($jsonData) . PHP_EOL);
                            $this->pluginNotifierFacade->createPaymentIntent($jsonData);

                        }
                        
                        if ($jsonData['data']['object']['type'] === 'applied_to_payment') {
                            $this->logger->info('Se aplicó el saldo en Stripe de un pago: ' . json_encode($jsonData) . PHP_EOL);
                            
                        }elseif ($jsonData['data']['object']['type'] === 'unapplied_from_payment'){
                            //ejemplo de json para transferencia de dinero cancelada: {"id":"evt_1RlEGgEFY1WEUtgR6Bp2DzDP","object":"event","api_version":"2023-10-16","created":1752606717,"data":{"object":{"id":"ccsbtxn_1RlEGfEFY1WEUtgRv8jAUGmE","object":"customer_cash_balance_transaction","created":1752606717,"currency":"mxn","customer":"cus_PetN1dhr4rx0kX","ending_balance":18000,"livemode":false,"net_amount":18000,"type":"unapplied_from_payment","unapplied_from_payment":{"payment_intent":"pi_3RlDPdEFY1WEUtgR1JBgNhTQ"}}},"livemode":false,"pending_webhooks":2,"request":{"id":"req_954mskVBfAI0jn","idempotency_key":"749518f6-baa0-4ae9-99e4-8029a35719aa"},"type":"customer_cash_balance_transaction.created"}
                            $paymentIntentId = $jsonData['data']['object']['unapplied_from_payment']['payment_intent'];
                            //Se canceló una transferencia de dinero, imprimir que se canceló y además el monto neto
                            $this->logger->warning('Evento de transferencia cancelada para el pago: ' . $paymentIntentId . PHP_EOL);
                            $this->logger->warning('Monto neto de la transferencia cancelada: ' . $jsonData['data']['object']['net_amount'] . PHP_EOL);

                        }
                        break;
                    case 'payout.failed':
                        $this->logger->info('Evento de transferencia fallida encontrado: ' . json_encode($jsonData) . PHP_EOL);
                        //imprimir detalles del fallo
                        $this->logger->info('Detalles del fallo: ' . json_encode($jsonData));
                        break;
                    case 'payment_intent.partially_funded':
                        $this->logger->info('Evento de pago parcialmente financiado encontrado: ' . json_encode($jsonData) . PHP_EOL);
                        //imprimir detalles del evento o pago
                        $this->logger->info('Detalles del evento: ' . json_encode($jsonData));
                        break;
                    case 'inbound_payment.payment_attempt':
                        //$this->logger->info('Evento de Pago de OXXO recibido: ' . json_encode($jsonData) . PHP_EOL);
                        break;
                    case 'cash_balance.funds_available':
                        $this->logger->info('Evento de Pago de fondos disponibles recibido: ' . json_encode($jsonData) . PHP_EOL);
                        break;
                    case 'energy.alert':
                        $this->logger->info('Evento de Energía recibido: ' . $jsonData['message'] . PHP_EOL);
                        break;
                    case 'oxxo.request':
                        $this->logger->info('Evento de solicitud de referencia de oxxo recibido' . PHP_EOL);

                        // Construir la URL basada en el "client_id"
                        // $url = "https://siip.mx/wp/wp-content/uploads/img/voucher.png";
                        if (! empty($jsonData['amount'])) {
                            $this->logger->info('Referencia personalizada, Valor del monto: ' . $jsonData['amount'] . PHP_EOL);
                            $intentos = 0;
                            do {
                                // if ($intentos > 1) {
                                //     sleep(2);
                                // }
                                $responseOxxo = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($jsonData, $jsonData['amount']);
                                $this->logger->info('Referencia personalizada, Valor de la respuesta: ' . json_encode($responseOxxo) . PHP_EOL);
                                //El array asociativo $responseOxxo es un array asosiativo con los siguientes campos: oxxo_reference, error, failDescription, clientID, amount
                                $intentos++;
                            } while (strpos($responseOxxo['url'], 'https') !== 0 && $intentos < 3); //Mientras la url no contenga https y el número de intentos sea menor a 3
                        } else {
                            $intentos = 0;
                            do {
                                // if ($intentos > 1) {
                                //     sleep(2);
                                // }
                                $responseOxxo = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($jsonData);
                                //El array asociativo $responseOxxo es un array asosiativo con los siguientes campos: oxxo_reference, error, failDescription, clientID, amount
                                $intentos++;
                            } while (strpos($responseOxxo['url'], 'https') !== 0 && $intentos < 3); //Mientras la url no contenga https y el número de intentos sea menor a 3
                        }

                        //El array asociativo $responseOxxo es un array asosiativo con los siguientes campos: oxxo_reference, error, failDescription, clientID, amount
                        //Si la respuesta no contiene https, se genera un error
                        if (strpos($responseOxxo['url'], 'https') !== 0) {
                            //this->logger->error('Error al crear la referencia de OXXO: ' . $responseOxxo);
                            //crear un json con variable $response que contenga las claves y valores del array $responseOxxo los cuales son: oxxo_reference, error, failDescription, clientID, clientFullName amount
                            $response = '{' .
                                '"url": "' . $responseOxxo['url'] . '",' .
                                '"oxxo_reference": "' . $responseOxxo['oxxo_reference'] . '",' .
                                '"voucher_image_url": "' . $responseOxxo['voucher_image_url'] . '",' .
                                '"error": "' . $responseOxxo['error'] . '",' .
                                '"failDescription": "' . $responseOxxo['failDescription'] . '",' .
                                '"clientID": "' . $responseOxxo['clientID'] . '",' .
                                '"clientFullName": "' . $responseOxxo['clientFullName'] . '",' .
                                '"amount": "' . $responseOxxo['amount'] . '"' .
                                '}';

                            header('Content-Type: application/json');
                            echo $response;
                            break;
                        } else {
                            //crear un json con variable $response que contenga las claves y valores del array $responseOxxo los cuales son: oxxo_reference, error, failDescription, clientID, clientFullName, amount

                            $response = '{' .
                                '"url": "' . $responseOxxo['url'] . '",' .
                                '"oxxo_reference": "' . $responseOxxo['oxxo_reference'] . '",' .
                                '"voucher_image_url": "' . $responseOxxo['voucher_image_url'] . '",' .
                                '"error": "' . $responseOxxo['error'] . '",' .
                                '"failDescription": "' . $responseOxxo['failDescription'] . '",' .
                                '"clientID": "' . $responseOxxo['clientID'] . '",' .
                                '"clientFullName": "' . $responseOxxo['clientFullName'] . '",' .
                                '"amount": "' . $responseOxxo['amount'] . '"' .
                                '}';

                            $this->logger->debug('Reponse que se envía a CallBell: ' . $response);
                            // Enviar el encabezado de respuesta como JSON
                            header('Content-Type: application/json');

                            // Enviar la respuesta en formato JSON
                            //echo json_encode($response);
                            echo $response;

                            break;

                        }

                }
            }
            return;
        }

        // $event_json = json_decode($userInput);
        // $webhook_string = json_encode($event_json);
        // $this->logger->debug("El valor de webhook_string: " . $webhook_string . PHP_EOL);

        $notification = $this->notificationDataFactory->getObject($jsonData);
        $this->logger->debug('valor el evento recibido por webhook: ' . $notification->eventName . PHP_EOL);
        $this->logger->debug('Valor de JSON: ' . json_encode($jsonData) . PHP_EOL);

        if ($notification->changeType === 'test') {

            $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
            $config        = $configManager->loadConfig();

            $this->logger->info('Webhook test successful.');

            return;
        } else if ($notification->changeType === 'paperless.update') {
            //imprimir el webhook json
            $this->logger->info('Webhook de paperless update: ' . json_encode($jsonData) . PHP_EOL);
        }
        // if (!$notification->clientId) {
        //     $this->logger->warning('No client specified, cannot notify them.');

        //     return;
        // }

        $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
        $config        = $configManager->loadConfig();
        // the "exportFormat" key must be defined in plugin's manifest file, see the link above

        try {

            if ($notification->eventName === 'payment.add') {

                $result = json_encode($notification);
                $this->logger->debug('Notification encodificado en JSON:' . $result . PHP_EOL);

                $datos_payment = $notification->paymentData;
                $this->logger->debug('valor del payment data: ' . json_encode($datos_payment) . PHP_EOL);
                $payment_method_id = $notification->paymentData['methodId'];
                //$this->logger->debug('Metodo de pago: ' . $notification->paymentData['methodId'] . PHP_EOL);

                $payment_method = '';

                switch ($payment_method_id) {

                    case '11721cdf-a498-48be-903e-daa67552e4f6':
                        $payment_method = 'Cheque';
                        if ($config['checkPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '6efe0fa8-36b2-4dd1-b049-427bffc7d369':
                        $payment_method = 'Efectivo';
                        if ($config['cashPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '4145b5f5-3bbc-45e3-8fc5-9cda970c62fb':
                        $payment_method = 'Transferencia bancaria';
                        if ($config['bankTransferPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '78e84000-9b5b-44a4-8367-da43df86ce34':
                        $payment_method = 'PayPal';
                        if ($config['paypalPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '6da98bb9-6df7-4c41-8608-5cdd7fde7d5d':
                        $payment_method = 'Tarjeta de crédito PayPal';
                        if ($config['creditCardPaypalPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '1dd098fa-5d63-4c8d-88b7-3c27ffbbb6ae':
                        $payment_method = 'Tarjeta de crédito Stripe';
                        if ($config['creditCardStripePaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case 'b9e1e9d1-5c7b-41d2-b6b2-3e568d700290':
                        $payment_method = 'Suscripción de Stripe (tarjeta de crédito)';
                        if ($config['stripeSubscriptionCreditCardPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '939f7701-00b7-4676-9b1e-17afb268c8ba':
                        $payment_method = 'Suscripción de PayPal';
                        if ($config['paypalSubscriptionPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '1c963e35-df24-444d-95d2-12592d5107e8':
                        $payment_method = 'MercadoPago';
                        if ($config['mercadopagoPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case 'd8c1eae9-d41d-479f-aeaf-38497975d7b3':
                        $payment_method = 'Personalizado';
                        if ($config['customPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    case '72271b72-5c0a-45e2-94d1-cdf4d7cf10e2':
                        $payment_method = 'Cortesía';
                        if ($config['courtesyPaymentMethodId']) {
                            $this->notifierFacade->verifyPaymentActionToDo($notification);
                        }
                        break;
                    default:
                        $payment_method = 'Desconocido, revisar metodos de pago no contemplados';
                        break;

                }

            } else if ($notification->eventName === 'client.edit') {
                $this->logger->debug('Se actualiza a un cliente');
                $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
                //ejemplo de json_data: {"uuid":"aacaf5c5-2bf4-44ea-864f-a24121b453bb","changeType":"edit","entity":"client","entityId":"171","eventName":"client.edit","extraData":{"entity":{"id":171,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-05-21T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Archi","lastName":"Isalas","username":"mainstreamm2@gmail.com","contacts":[{"id":177,"clientId":171,"email":"mainstreamm2@gmail.com","phone":"4181878106","name":null,"isBilling":false,"isContact":false,"types":[]}],"attributes":[{"id":198,"clientId":171,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_SM2zH6IsjTz6ol","clientZoneVisible":true},{"id":199,"clientId":171,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"124180950530868794","clientZoneVisible":true}],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":true,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":171,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-05-21T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Archi","lastName":"Isalas","username":"mainstreamm2@gmail.com","contacts":[{"id":177,"clientId":171,"email":"mainstreamm2@gmail.com","phone":"4181878106","name":null,"isBilling":false,"isContact":false,"types":[{"id":1003,"name":"WhatsNotifica"}]}],"attributes":[{"id":198,"clientId":171,"customAttributeId":10,"name":"Stripe Customer ID","key":"stripeCustomerId","value":"cus_SM2zH6IsjTz6ol","clientZoneVisible":true},{"id":199,"clientId":171,"customAttributeId":11,"name":"Clabe Interbancaria","key":"clabeInterbancaria","value":"124180950530868794","clientZoneVisible":true}],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#f1df43","addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":true,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}


                $clientID         = $jsonData['entityId'];
                $this->ucrmApi    = UcrmApi::create();
                $customAttributes = $this->ucrmApi->get('custom-attributes/', ['attributeType' => 'client']); //Obtener los atributos del sistema que estén vinculados a la entidad "cliente"
                                                                                                              //$this->logger->info("result del custom Attributes: " . json_encode($customAttributes) . PHP_EOL);

                $idPasswordAntenaCliente = null;
                $passwordAntenaValue     = null;

                //ejemplo de $customAttributes: [{"id":1,"name":"ip","key":"ip","attributeType":"client","type":"string","clientZoneVisible":false},{"id":2,"name":"ubntpass","key":"ubntpass","attributeType":"client","type":"string","clientZoneVisible":false},{"id":3,"name":"adminpass","key":"adminpass","attributeType":"client","type":"string","clientZoneVisible":true},{"id":4,"name":"ssid","key":"ssid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":5,"name":"clavessid","key":"clavessid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":6,"name":"clave","key":"clave","attributeType":"client","type":"string","clientZoneVisible":true},{"id":11,"name":"latitud","key":"latitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":12,"name":"longitud","key":"longitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":16,"name":"instalador","key":"instalador","attributeType":"client","type":"string","clientZoneVisible":true},{"id":17,"name":"creado por","key":"creadoPor","attributeType":"client","type":"string","clientZoneVisible":true},{"id":21,"name":"Chat de CallBell","key":"chatDeCallbell","attributeType":"client","type":"string","clientZoneVisible":false},{"id":22,"name":"uuid","key":"uuid","attributeType":"client","type":"string","clientZoneVisible":false},{"id":23,"name":"zona","key":"zona","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":29,"name":"Stripe Customer ID","key":"stripeCustomerId","attributeType":"client","type":"string","clientZoneVisible":true},{"id":30,"name":"Clabe Interbancaria","key":"clabeInterbancaria","attributeType":"client","type":"string","clientZoneVisible":true},{"id":31,"name":"RUTA DE COBRANZA","key":"rutaDeCobranza","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":35,"name":"Site","key":"site","attributeType":"client","type":"string","clientZoneVisible":true},{"id":36,"name":"Antena/Sectorial","key":"antenaSectorial","attributeType":"client","type":"string","clientZoneVisible":true},{"id":37,"name":"Password Antena Cliente","key":"passwordAntenaCliente","attributeType":"client","type":"string","clientZoneVisible":false}]

                // Verificar si se obtuvieron los atributos
                if ($customAttributes && is_array($customAttributes)) {
                    foreach ($customAttributes as $attribute) {
                        // Verificar si 'name' contiene la palabra 'passwordAntenaCliente' sin distinguir mayúsculas y minúsculas
                        if (isset($attribute['key']) && stripos($attribute['key'], 'passwordAntenaCliente') !== false) {
                            $this->logger->info("ID correspondiente a 'passwordAntenaCliente': " . $attribute['id'] . PHP_EOL);
                            $idPasswordAntenaCliente = $attribute['id'];
                        }

                    }
                } else {
                    $this->logger->info("Error al obtener los atributos personalizados." . PHP_EOL);
                }

                //buscar en los attributes ($jsonData) del cliente el id del atributo personalizado 'passwordAntenaCliente' si no está o si está pero está en blanco se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);

                foreach ($jsonData['extraData']['entity']['attributes'] as $attribute) {
                    if ($attribute['customAttributeId'] === $idPasswordAntenaCliente) {
                        $this->logger->info("El valor de passwordAntenaValue es: " . $attribute['value'] . PHP_EOL);
                        $passwordAntenaValue = $attribute['value'];
                    }
                }

                //si el value de passwordAntenaValue es igual a null o cadena vacía se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
                if ($passwordAntenaValue === null || $passwordAntenaValue === '') {
                    $password = $this->notifierFacade->getVaultCredentials($clientID);
                    $this->logger->info("El valor de passwordAntenaValue es null o cadena vacía, se manda llamar la función getVaultCredentials" . PHP_EOL);
                    $this->logger->info("El valor de password es: " . $password . PHP_EOL);

                    if ($this->notifierFacade->patchClientCustomAttribute($clientID, $idPasswordAntenaCliente, $password)) {
                        $this->logger->info("Se actualizó el atributo personalizado passwordAntenaCliente con el valor: " . $password . PHP_EOL);
                    } else {
                        $this->logger->info("No se pudo actualizar el atributo personalizado passwordAntenaCliente" . PHP_EOL);
                    }
                } else {
                    $this->logger->info("Ya existe un valor de passwordAntenaValue: " . $passwordAntenaValue . PHP_EOL);
                }

                //ejemplo de json_data: {"uuid":"17e043a7-03b5-4312-ab81-a7818124a77e","changeType":"edit","entity":"client","entityId":"158","eventName":"client.edit","extraData":{"entity":{"id":158,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":"2025-02-09T03:15:49-0600","companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":158,"userIdent":null,"previousIsp":null,"isLead":true,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}

                // Validar que 'extraData' existe y contiene las claves necesarias
                if (
                    isset($jsonData['extraData']['entityBeforeEdit']) &&
                    isset($jsonData['extraData']['entity'])
                ) {
                    $entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
                    $entity           = $jsonData['extraData']['entity'];

                    //$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');

                    // Validar si 'isLead' esta en true en entityBeforeEdit y en false en entity
                    if (array_key_exists('isLead', $entityBeforeEdit) && array_key_exists('isLead', $entity)) {
                        //$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo isLead');

                        $isLeadBefore = $entityBeforeEdit['isLead'];
                        $isLeadAfter  = $entity['isLead'];

                        // Comprobar si 'isLead' cambió de true a false
                        if ($isLeadBefore === true && $isLeadAfter === false) {
                            $this->logger->debug('El cliente cambió de potencial a cliente');
                            //$this->pluginNotifierFacade->createStripeClient($notification); //Se comenta esta línea para que no se cree el cliente en Stripe al convertir el lead a cliente, ya que se hará al agregar la etiqueta 'CREAR CLABE STRIPE'
                        } else {
                            $this->logger->debug('El cliente no cambió de potencial a cliente');
                        }
                    } else {
                        $this->logger->warning('El campo isLead no existe en entityBeforeEdit o entity');
                    }

                    // buscar si existe la etiqueta 'STRIPE' en entity pero no en entityBeforeEdit
                    $tags       = $jsonData['extraData']['entity']['tags'];
                    $tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags'];

                    $this->logger->debug('Validando claves dentro de entity y entityBeforeEdit');

                    // Validar que 'tags' existe en ambas entidades
                    if (array_key_exists('tags', $jsonData['extraData']['entity']) && array_key_exists('tags', $jsonData['extraData']['entityBeforeEdit'])) {
                        $this->logger->debug('Los datos entity y entityBeforeEdit contienen el campo tags');

                        $tags       = $jsonData['extraData']['entity']['tags'];
                        $tagsBefore = $jsonData['extraData']['entityBeforeEdit']['tags'];

                        $this->logger->debug('Validando si la etiqueta STRIPE existe en entity pero no en entityBeforeEdit');

                        // Comprobar si la etiqueta 'CREAR CLABE STRIPE' existe en 'tags' pero no en 'tagsBefore'
                        $stripeTagExists       = false;
                        $stripeTagExistsBefore = false;
                        foreach ($tags as $tag) {
                            if ($tag['name'] === 'CREAR CLABE STRIPE') {
                                $stripeTagExists = true;
                                break;
                            }
                        }
                        foreach ($tagsBefore as $tag) {
                            if ($tag['name'] === 'CREAR CLABE STRIPE') {
                                $stripeTagExistsBefore = true;
                                break;
                            }
                        }

                        // Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore'
                        if ($stripeTagExists && ! $stripeTagExistsBefore) {
                            $this->logger->debug('La etiqueta CREAR CLABE STRIPE se agregará al cliente');
                            $this->pluginNotifierFacade->createStripeClient($notification, true);
                        }
                    } else {
                        $this->logger->warning('El campo tags no existe en entity o entityBeforeEdit');
                    }

                } else { 
                    $this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData');
                }

                $this->notifierFacade->verifyClientActionToDo($notification);

            } else if ($notification->eventName === 'client.add') {
                $this->logger->debug('Se agregó un nuevo cliente' . PHP_EOL);
                $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));

                // Verificar que existen tanto 'entityBeforeEdit' como 'entity'
                // if (isset($jsonData['extraData']['entity']['isLead'])) {
                //     $this->logger->debug('El campo isLead existe en los datos del evento');
                //     $isLead = $jsonData['extraData']['entity']['isLead'];

                //     // Comprobar si 'isLead' es true
                //     if ($isLead === true) {
                //         $this->logger->debug('El cliente es potencial');
                //         $this->pluginNotifierFacade->createStripeClient($notification);
                //     } else {
                //         $this->logger->debug('El cliente no es potencial');
                //         $this->pluginNotifierFacade->createStripeClient($notification);
                //     }
                // } else {
                //     $this->logger->warning('El campo isLead no existe en los datos del evento');
                // }

            } else if ($notification->eventName === 'service.edit') {
                $this->logger->debug('Se editó el servicio a un  cliente' . PHP_EOL);
                $this->notifierFacade->verifyServiceActionToDo($notification);
                //ejemplo de json_data: {"uuid":"06d281ca-d78e-4f0a-a282-3a6b77d25da0","changeType":"edit","entity":"service","entityId":"155","eventName":"service.edit","extraData":{"entity":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]},"entityBeforeEdit":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]}}}
                //obtener el clientID y asginarlo a la variable $clientID
                $clientID         = $jsonData['extraData']['entity']['clientId'];
                $this->ucrmApi    = UcrmApi::create();
                $customAttributes = $this->ucrmApi->get('custom-attributes/', ['attributeType' => 'client']); //Obtener los atributos del sistema que estén vinculados a la entidad "cliente"
                                                                                                              //$this->logger->info("result del custom Attributes: " . json_encode($customAttributes) . PHP_EOL);

                $idPasswordAntenaCliente = null;
                $passwordAntenaValue     = null;

                //ejemplo de $customAttributes: [{"id":1,"name":"ip","key":"ip","attributeType":"client","type":"string","clientZoneVisible":false},{"id":2,"name":"ubntpass","key":"ubntpass","attributeType":"client","type":"string","clientZoneVisible":false},{"id":3,"name":"adminpass","key":"adminpass","attributeType":"client","type":"string","clientZoneVisible":true},{"id":4,"name":"ssid","key":"ssid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":5,"name":"clavessid","key":"clavessid","attributeType":"client","type":"string","clientZoneVisible":true},{"id":6,"name":"clave","key":"clave","attributeType":"client","type":"string","clientZoneVisible":true},{"id":11,"name":"latitud","key":"latitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":12,"name":"longitud","key":"longitud","attributeType":"client","type":"string","clientZoneVisible":true},{"id":16,"name":"instalador","key":"instalador","attributeType":"client","type":"string","clientZoneVisible":true},{"id":17,"name":"creado por","key":"creadoPor","attributeType":"client","type":"string","clientZoneVisible":true},{"id":21,"name":"Chat de CallBell","key":"chatDeCallbell","attributeType":"client","type":"string","clientZoneVisible":false},{"id":22,"name":"uuid","key":"uuid","attributeType":"client","type":"string","clientZoneVisible":false},{"id":23,"name":"zona","key":"zona","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":29,"name":"Stripe Customer ID","key":"stripeCustomerId","attributeType":"client","type":"string","clientZoneVisible":true},{"id":30,"name":"Clabe Interbancaria","key":"clabeInterbancaria","attributeType":"client","type":"string","clientZoneVisible":true},{"id":31,"name":"RUTA DE COBRANZA","key":"rutaDeCobranza","attributeType":"client","type":"enum","clientZoneVisible":true},{"id":35,"name":"Site","key":"site","attributeType":"client","type":"string","clientZoneVisible":true},{"id":36,"name":"Antena/Sectorial","key":"antenaSectorial","attributeType":"client","type":"string","clientZoneVisible":true},{"id":37,"name":"Password Antena Cliente","key":"passwordAntenaCliente","attributeType":"client","type":"string","clientZoneVisible":false}]

                // Verificar si se obtuvieron los atributos
                if ($customAttributes && is_array($customAttributes)) {
                    foreach ($customAttributes as $attribute) {
                        // Verificar si 'name' contiene la palabra 'passwordAntenaCliente' sin distinguir mayúsculas y minúsculas
                        if (isset($attribute['key']) && stripos($attribute['key'], 'passwordAntenaCliente') !== false) {
                            $this->logger->info("ID correspondiente a 'passwordAntenaCliente': " . $attribute['id'] . PHP_EOL);
                            $idPasswordAntenaCliente = $attribute['id'];
                        }

                    }
                } else {
                    $this->logger->info("Error al obtener los atributos personalizados." . PHP_EOL);
                }

                //buscar en los attributes ($jsonData) del cliente el id del atributo personalizado 'passwordAntenaCliente' si no está o si está pero está en blanco se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);

                foreach ($jsonData['extraData']['entity']['attributes'] as $attribute) {
                    if ($attribute['customAttributeId'] === $idPasswordAntenaCliente) {
                        $this->logger->info("El valor de passwordAntenaValue es: " . $attribute['value'] . PHP_EOL);
                        $passwordAntenaValue = $attribute['value'];
                    }
                }

                //si el value de passwordAntenaValue es igual a null o cadena vacía se manda llamar la función $this->notifierFacade->getVaultCredentials($clientID);
                if ($passwordAntenaValue === null || $passwordAntenaValue === '') {
                    $password = $this->notifierFacade->getVaultCredentials($clientID);
                    $this->logger->info("El valor de passwordAntenaValue es null o cadena vacía, se manda llamar la función getVaultCredentials" . PHP_EOL);
                    $this->logger->info("El valor de password es: " . $password . PHP_EOL);

                    if ($this->notifierFacade->patchClientCustomAttribute($clientID, $idPasswordAntenaCliente, $password)) {
                        $this->logger->info("Se actualizó el atributo personalizado passwordAntenaCliente con el valor: " . $password . PHP_EOL);
                    } else {
                        $this->logger->info("No se pudo actualizar el atributo personalizado passwordAntenaCliente" . PHP_EOL);
                    }
                } else {
                    $this->logger->info("Ya existe un valor de passwordAntenaValue: " . $passwordAntenaValue . PHP_EOL);
                }

            } else if ($notification->eventName === 'service.suspend') {
                $this->logger->debug('Se suspendió el servicio a un  cliente' . PHP_EOL);
                $this->notifierFacade->verifyServiceActionToDo($notification);
            } else if ($notification->eventName === 'service.suspend_cancel') {
                $this->logger->debug('Se reactivó el servicio a un  cliente' . PHP_EOL);
                $this->notifierFacade->verifyServiceActionToDo($notification);
            } else if ($notification->eventName === 'service.postpone') {
                $this->logger->debug('Se pospuso la suspención del servicio a un  cliente' . PHP_EOL);
                $this->notifierFacade->verifyServiceActionToDo($notification);
            } else if ($notification->eventName === 'invoice.near_due') {
                $this->logger->debug('Factura casi por vencer' . PHP_EOL);
                $this->notifierFacade->notifyOverDue($notification);
            } else if ($notification->eventName === 'invoice.overdue') {
                $this->logger->debug('Factura vencida' . PHP_EOL);
                $result = json_encode($notification);
                $this->logger->debug('datos del notification para el invoice overdue:' . $result . PHP_EOL);
                $this->notifierFacade->notifyOverDue($notification);
            } else if ($notification->eventName === 'invoice.add') {
                $this->logger->debug('Adición de Factura' . PHP_EOL);
                $result = json_encode($notification);
                $this->logger->debug('datos del notification para el invoice add:' . $result . PHP_EOL);

                $accountBalance = $notification->clientData['accountBalance'];
                //$invoiceAmountPaid = $notification->invoiceData['amountPaid'];
                $this->logger->debug("Account Balance: " . $accountBalance . PHP_EOL);
                // $this->logger->debug("Pago hecho con la factura: " . $invoiceAmountPaid . PHP_EOL);
                $this->notifierFacade->verifyInvoiceActionToDo($notification);
            } else if ($notification->eventName === 'invoice.edit') {
                $this->logger->debug('Edición de Factura' . PHP_EOL);
                $this->notifierFacade->verifyInvoiceActionToDo($notification);
            } else if ($notification->eventName === 'invoice.add_draft') {
                $this->logger->debug('Adición de borrador de Factura' . PHP_EOL);
                $this->notifierFacade->verifyInvoiceActionToDo($notification);
            } else if ($notification->eventName === 'invoice.draft_approved') {
                $this->logger->debug('Aprobación de Factura' . PHP_EOL);
                $this->notifierFacade->verifyInvoiceActionToDo($notification);
            } else if ($notification->eventName === 'invoice.delete') {
                $this->logger->debug('Eliminación de Factura' . PHP_EOL);
                $this->notifierFacade->verifyInvoiceActionToDo($notification);
            } else if ($notification->eventName === 'job.add') {
                $this->logger->debug('Se ha agregado un nuevo trabajo' . PHP_EOL);
                $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
                //Ejemplo de json_data: {"uuid":"434b3da0-984a-4358-a1b6-2a4418bacc49","changeType":"insert","entity":"job","entityId":"38","eventName":"job.add","extraData":{"entity":{"id":38,"title":"Servicio","description":"Revisar Router","assignedUserId":null,"clientId":2,"date":null,"duration":60,"status":0,"address":"31 Chiapas, Dolores Hidalgo Cuna de la Independencia Nacional, 37800, Mexico","gpsLat":null,"gpsLon":null,"attachments":[],"tasks":[]},"entityBeforeEdit":null}}
                //Extraer el valor de title en una variable y concatenarle como prefijo la cadena "[SINENVIONOTIFICACION]" por ejemplo: "[NOTIFICACION-PENDIENTE]Servicio"
                $title         = $jsonData['extraData']['entity']['title'];
                $title         = '[NOTIFICACION-PENDIENTE]' . $title;
                $this->ucrmApi = UcrmApi::create();
                $responsePatch = $this->ucrmApi->patch('scheduling/jobs/' . $jsonData['entityId'], [
                    'title' => $title,
                ]);

                $this->logger->debug('Respuesta de la API al agregar el trabajo: ' . json_encode($responsePatch) . PHP_EOL);

            } else if ($notification->eventName === 'job.edit') {
                $this->logger->debug('Se actualiza un trabajo' . PHP_EOL);
                // $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));

                // Validar que 'extraData' existe y contiene las claves necesarias
                if (
                    isset($jsonData['extraData']['entityBeforeEdit']) &&
                    isset($jsonData['extraData']['entity'])
                ) {
                    $entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
                    $entity           = $jsonData['extraData']['entity'];

                    $this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');

                    // Validar que 'assignedUserId' existe en ambas entidades
                    if (array_key_exists('assignedUserId', $entityBeforeEdit) && array_key_exists('assignedUserId', $entity)) {
                        // $this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo assignedUserId');

                        $assignedUserIdBefore = $entityBeforeEdit['assignedUserId'];
                        $assignedUserIdAfter  = $entity['assignedUserId'];
                        $dateBefore           = $entityBeforeEdit['date'];
                        $dateAfter            = $entity['date'];
                        $statusBefore         = $entityBeforeEdit['status'];
                        $statusAfter          = $entity['status'];
                        $title                = $entityBeforeEdit['title'];
                        $pendingPrefix        = '[NOTIFICACION-PENDIENTE]'; // Prefijo para trabajos pendientes de notificación
                        $currentTitle         = $entity['title'] ?? '';     // Obtener el título actual

                        //Valores de status y su significado: 0 = abierto, 1= En curso, 2 = Cerrado

                        if ($statusAfter == 1) {
                            // Comprobar si 'assignedUserId' cambió
                            // if (($assignedUserIdBefore === null && $assignedUserIdAfter != null) || ($statusBefore == 0 && $statusAfter == 1)) { //Si el campo "assignedUserId" cambió de null a un valor
                            //     $this->logger->debug('El instalador cambió de null a un valor');

                            //     $this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado
                            // }

                                                                                                                                //Si el campo status cambió de 0 a 1 y title comienza con el prefijo [NOTIFICACION-PENDIENTE]
                            if (($statusBefore == 0 && $statusAfter == 1) && strpos($currentTitle, $pendingPrefix) !== false) { // Se envía notificación de trabajo asignado
                                $this->logger->debug('El instalador cambió de null a un valor');
                                $this->notifierFacade->verifyJobActionToDo($jsonData, false, false);
                            } else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore === $dateAfter)) { //Si el campo "assignedUserId" cambió de un valor a otro y la fecha no cambió
                                $this->logger->debug('No hay reprogramación de trabajo pero si hay cambio de instalador');
                                $this->notifierFacade->verifyJobActionToDo($jsonData, false, true);                                                            // Se envía notificación de trabajo reasignado
                            } else if (($assignedUserIdBefore != null && $assignedUserIdBefore === $assignedUserIdAfter) && ($dateBefore != $dateAfter)) { //Si el campo "assignedUserId" no cambió y la fecha cambió
                                $this->logger->debug('Se reprogramó el trabajo pero no hubo cambio de instalador');
                                $this->notifierFacade->verifyJobActionToDo($jsonData, true, false); // Se envía notificación de reprogramación de trabajo
                            } else if (($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore) && ($dateBefore != $dateAfter)) {
                                $this->logger->debug('Se reprogramó el trabajo y hubo cambio de instalador');
                                $this->notifierFacade->verifyJobActionToDo($jsonData, true, true);           // Se envía notificación de trabajo reasignado
                            } else if ($assignedUserIdBefore != null && $assignedUserIdAfter === null) { //Si el campo "assignedUserId" cambió de un valor a null
                                $this->logger->debug('El instalador cambió de un valor a null');
                                $this->notifierFacade->verifyJobActionToDo($jsonData, null, true); // Se envía notificación de trabajo desasignado
                            } else {
                                $this->logger->debug('No hubo cambio en el instalador ni en la fecha');
                                //$this->notifierFacade->verifyJobActionToDo($jsonData); // Se envía notificación de trabajo asignado
                            }
                        }

                    } else {
                        $this->logger->warning('El campo assignedUserId no existe en entityBeforeEdit o entity');
                    }
                } else {
                    $this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData');
                }

            }

            //$this->notifierFacade->update($notification);
        } catch (TwilioException $exception) {
            $this->logger->error($exception->getMessage());
        } catch (\Exception $ex) {
            $this->logger->error($ex->getMessage());
            $this->logger->info($ex->getTraceAsString());
        }
    }
}
