<?php

namespace Modules\Wpbox\Http\Controllers;

use App\Models\Config;
use App\Models\RegistroConversacion;
use App\Models\RespuestaEncuesta;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use Modules\Contacts\Models\Contact;
use Modules\Wpbox\Models\Message;
use Illuminate\Support\Facades\Storage;
use Modules\Wpbox\Models\Reply;
use Modules\Wpbox\Models\Template;
use Modules\Wpbox\Traits\Whatsapp;
use Illuminate\Support\Facades\Validator;
use Modules\Wpbox\Events\Chatlistchange;

class HelpersChatController extends Controller
{
    use Whatsapp;
    public static function enviarMensajeRandom($id_contact, $texto)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $sendPhoneNumber = Contact::where('id', $id_contact)->get()->first()->phone;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "text",
                        "text" => [
                            "body" => $texto
                        ]
                    ]);


            $statusCode = $response->status();
            $content = json_decode($response->body(), true);
            $message = new Message();
            // $message->update_at = now();
            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
                //dd($content);
            }
            // Guardar el mensaje
            $clean_message = str_replace("\n", '', $texto);
            $message->created_at = now();
            $message->contact_id = $id_contact;
            $message->components = "";
            $message->buttons = "";
            $message->status = 1;
            $message->value = $clean_message;
            $message->save();

            return $message;
        } catch (\Exception $e) {
            \Log::error("=============== Error ==============");
            \Log::error(json_encode($e));
        }
    }
    public static function enviarConsultores($id_contact)
    {
        // if (VerificarHorariosController::enviarDisponibilidad($id_contact)) {
        //     return;
        // }
        try {
            $whatsappPhoneId = Config::where('key', 'whatsapp_phone_number_id')->get()->first()->value;

            $whatsappPermanentAccesToken = Config::where('key', 'whatsapp_permanent_access_token')->get()->first()->value;

            $sendPhoneNumber = Contact::where('id', $id_contact)->get()->first()->phone;

            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';

            $consultores = \DB::select("
                SELECT u.id,u.name,u.descripcion
                FROM users u
                join model_has_roles mhr on mhr.model_id = u.id
                join users_permissions_staffs ups on ups.user_id = u.id
                WHERE mhr.role_id = 4
                and ups.status = 0;
            ");
            $rows = array_map(function ($consultor) {
                if ($consultor->descripcion) {
                    return [
                        "id" => $consultor->id,
                        "title" => $consultor->name,
                        "description" => $consultor->descripcion
                    ];
                } else {
                    return [
                        "id" => $consultor->id,
                        "title" => $consultor->name
                    ];
                }
            }, $consultores);
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "list",
                            "header" => [
                                "type" => "text",
                                "text" => "JMAS 👋"
                            ],
                            "body" => [
                                "text" => " Hola, soy el asistente virtual de JMAS. 🛠
Estoy aquí para ayudarte con soporte técnico 🤖 y  consultas sobre nuestros servicios. 📋 Esta es la información que puedo proporcionarte ✅"
                            ],
                            "action" => [
                                "button" => "Seleccionar",
                                "sections" => [
                                    [
                                        "rows" => $rows
                                    ],
                                ]
                            ]
                        ]
                    ]);
            $content = json_decode($response->body(), true);
            $message = new Message();
            // $message->update_at = now();
            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
                //dd($content);
            }
            // Guardar el mensaje
            $message->created_at = now();
            $message->header_text = "Sidev";
            $message->contact_id = $id_contact;
            $message->components = json_encode($rows);
            $message->buttons = "";
            $message->status = 1;
            $message->value = "Mensaje automatico, selecciona un consultor";
            $message->save();

        } catch (\Exception $e) {
            \Log::error($e);
        }
    }
    public static function volverEnviarConsultores($id_contact)
    {
        // if (VerificarHorariosController::enviarDisponibilidad($id_contact)) {
        //     return;
        // }
        try {

            $whatsappPhoneId = Config::where('key', 'whatsapp_phone_number_id')->get()->first()->value;

            $whatsappPermanentAccesToken = Config::where('key', 'whatsapp_permanent_access_token')->get()->first()->value;

            $sendPhoneNumber = Contact::where('id', $id_contact)->get()->first()->phone;

            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';

            $consultores = \DB::select("
                SELECT u.id,u.name,u.descripcion
                FROM users u
                join model_has_roles mhr on mhr.model_id = u.id
                join users_permissions_staffs ups on ups.user_id = u.id
                WHERE mhr.role_id = 4
                and ups.status = 0
                and u.id !=
                (select user_id from contacts c where c.id = ?);
            ", [$id_contact]);
            $rows = array_map(function ($consultor) {
                if ($consultor->descripcion) {
                    return [
                        "id" => $consultor->id,
                        "title" => $consultor->name,
                        "description" => $consultor->descripcion
                    ];
                } else {
                    return [
                        "id" => $consultor->id,
                        "title" => $consultor->name
                    ];
                }
            }, $consultores);
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "list",
                            "header" => [
                                "type" => "text",
                                "text" => "Sidev"
                            ],
                            "body" => [
                                "text" => "Elige un nuevo consultor de la lista para ser atendido."
                            ],
                            "action" => [
                                "button" => "Seleccionar",
                                "sections" => [
                                    [
                                        "rows" => $rows
                                    ],
                                ]
                            ]
                        ]
                    ]);
            $content = json_decode($response->body(), true);
            $message = new Message();
            // $message->update_at = now();
            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
                //dd($content);
            }
            // Guardar el mensaje
            $message->created_at = now();
            $message->header_text = "Sidev";
            $message->contact_id = $id_contact;
            $message->components = json_encode($rows);
            $message->buttons = "";
            $message->status = 1;
            $message->value = "Mensaje automatico, reasignar consultor,Elige un nuevo consultor de la lista para ser atendido.";
            $message->save();

        } catch (\Exception $e) {
            \Log::error($e);
        }
    }

    public static function enviarOpciones($id_contact)
    {
        try {
            $whatsappPhoneId = Config::where('key', 'whatsapp_phone_number_id')->get()->first()->value;

            $whatsappPermanentAccesToken = Config::where('key', 'whatsapp_permanent_access_token')->get()->first()->value;

            $sendPhoneNumber = Contact::where('id', $id_contact)->get()->first()->phone;

            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';

            $rows = [
                [
                    "id" => "informes",
                    "title" => "1️⃣ Informes 📄",
                    "description" => "Consulta información general."
                ],
                [
                    "id" => "solicitudes",
                    "title" => "2️⃣ Solicitudes ✍️",
                    "description" => "Envía una solicitud específica."
                ],
                [
                    "id" => "problema",
                    "title" => "3️⃣ Reportar un problema ⚠️",
                    "description" => "Informa sobre un problema que haya."
                ],
                [
                    "id" => "registrarse",
                    "title" => "4️⃣ Registrarse ✨🔔",
                    "description" => "Recibe notificaciones sobre eventos en tu colonia. 📢"
                ],
                [
                    "id" => "terminos_condiciones",
                    "title" => "5️⃣ Términos 🔔",
                    "description" => "Ver los términos y condiciones de este bot."
                ],
            ];

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "list",
                            "header" => [
                                "type" => "text",
                                "text" => "JMAS 👋🤖"
                            ],
                            "body" => [
                                "text" => "💧 JMAS | Asistente Virtual 🤖\n\n"
                                    . "🌟 ¡Bienvenido! Soy el asistente virtual de JMAS, tu canal de soporte y atención.\n\n"
                                    . "📌 Estoy aquí para brindarte asistencia técnica 🛠️ y responder tus dudas sobre nuestros servicios 📋.\n\n"
                                    . "✅ Para continuar, selecciona una opción del menú a continuación.\n\n"
                                    . "🔹 Importante: Al continuar usando este chat, aceptas nuestros Términos y Condiciones, los cuales puedes consultar en la opción correspondiente del menú."
                            ],
                            "action" => [
                                "button" => "Seleccionar opción",
                                "sections" => [
                                    [
                                        "rows" => $rows
                                    ],
                                ]
                            ]
                        ]
                    ]);


            $content = json_decode($response->body(), true);
            $message = new Message();
            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
            }

            $message->created_at = now();
            $message->header_text = "JMAS";
            $message->contact_id = $id_contact;
            $message->components = json_encode($rows);
            $message->buttons = "";
            $message->status = 1;
            $message->value = "Mensaje automático, selecciona una opción";
            $message->save();

        } catch (\Exception $e) {
            \Log::error($e);
        }
    }


    public static function advertenciaFlujoChat($id_contact)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $contact = Contact::where('id', $id_contact)->get()->first();
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $contact->phone,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "button",
                            "body" => [
                                "text" => "📌 Tienes un proceso en curso. Por favor, sigue las opciones en este chat para completarlo y podamos ayudarte lo mas pronto posible o cancela el proceso. 😊"
                            ],
                            "action" => [
                                "buttons" => [
                                    [
                                        "type" => "reply",
                                        "reply" => [
                                            "id" => "TERMINAR_PROCESO",
                                            "title" => "Cancelar proceso"
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]);
            $statusCode = $response->status();
            $content = json_decode($response->body(), true);
        } catch (\Exception $e) {
            \Log::error("============= error ===========");
            \Log::error(json_encode($e));
        }
    }





    public static function enviarReportarProblema($id_contact)
    {
        try {
            $whatsappPhoneId = Config::where('key', 'whatsapp_phone_number_id')->value('value');
            $whatsappPermanentAccessToken = Config::where('key', 'whatsapp_permanent_access_token')->value('value');
            $sendPhoneNumber = Contact::where('id', $id_contact)->value('phone');
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';

            $rows = [
                [
                    "id" => "fugas",
                    "title" => "🚰 Fugas",
                    "description" => "Reporta fugas de agua en tu zona."
                ],
                [
                    "id" => "falta_de_agua",
                    "title" => "💧 Falta de Agua",
                    "description" => "Informa sobre la ausencia de suministro de agua."
                ],
                [
                    "id" => "drenaje",
                    "title" => "🛠️ Drenaje",
                    "description" => "Reporta problemas en el drenaje."
                ],
                [
                    "id" => "alcantarillado",
                    "title" => "🚦 Alcantarillado",
                    "description" => "Informa sobre problemas en el alcantarillado."
                ],
                [
                    "id" => "baches",
                    "title" => "🕳️ Baches",
                    "description" => "Reporta baches en las calles."
                ],
                [
                    "id" => "alto_consumo_inspeccion",
                    "title" => "📊 Alto Consumo",
                    "description" => "Solicita una inspección por alto consumo."
                ],
                [
                    "id" => "otros_especifique",
                    "title" => "❓ Otros (Especifique)",
                    "description" => "Describe otro tipo de problema."
                ]
            ];

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccessToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "list",
                            "header" => [
                                "type" => "text",
                                "text" => "JMAS"
                            ],
                            "body" => [
                                "text" => "🔧 Selecciona una opción para reportar un problema y asegúrate de que sea atendido lo antes posible. 😊"
                            ],
                            "action" => [
                                "button" => "Seleccionar",
                                "sections" => [
                                    [
                                        "title" => "Reportar Problema",
                                        "rows" => $rows
                                    ]
                                ]
                            ]
                        ]
                    ]);

            $content = json_decode($response->body(), true);

            $message = new Message();
            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = $content['error']['message'] ?? "Unknown error";
            }

            $message->created_at = now();
            $message->header_text = "JMAS";
            $message->contact_id = $id_contact;
            $message->components = json_encode($rows);
            $message->buttons = "";
            $message->status = 1;
            $message->value = "Mensaje automático, selecciona una opción para reportar un problema";
            $message->save();

            return $message;

        } catch (\Exception $e) {
            \Log::error("Error al enviar mensaje: " . $e->getMessage());
        }
    }

    public static function enviarGraciasPorSeleccionar($id_contact)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $sendPhoneNumber = Contact::where('id', $id_contact)->get()->first()->phone;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';

            $cantidadContactosFila = \DB::selectOne("SELECT COUNT(*) AS count FROM contacts c WHERE c.user_id = (SELECT user_id FROM contacts co WHERE co.id = ?);", [$id_contact])->count;
            $promedioConversaciones = RegistroConversacion::promedioConversaciones(
                \DB::selectOne("SELECT user_id FROM contacts co WHERE co.id = ?", [$id_contact])->user_id
            );
            $promedioConversaciones->avgTime = round($promedioConversaciones->avgTime);
            $texto = null;

            if ($cantidadContactosFila <= 1) {
                $texto = "Sidev | Faesa \n\nGracias por contactarnos. Gracias por contactarnos. Nuestro consultor te atenderá en aproximadamente 15 minutos. Disculpe cualquier demora.\n\nPara seleccionar otro consultor, presione el botón *Reasignar*.";
            } else {
                $cantidadContactosFila--;
                $tiempoMultiplicado = round($promedioConversaciones->avgTime * $cantidadContactosFila);
                $texto = "Sidev | Faesa \n\nGracias por contactarnos. Nuestro consultor te atenderá en aproximadamente 15 minutos. Disculpe cualquier demora.\n\nPara seleccionar otro consultor, presione el botón *Reasignar*.";

            }

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "button",
                            "body" => [
                                "text" => $texto
                            ],
                            "action" => [
                                "buttons" => [
                                    [
                                        "type" => "reply",
                                        "reply" => [
                                            "id" => "reasignar_consultor",
                                            "title" => "Reasignar"
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]);

            $statusCode = $response->status();
            $content = json_decode($response->body(), true);
            $message = new Message();

            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
            }

            $clean_message = str_replace("\n", '', $texto);
            $message->created_at = now();
            $message->contact_id = $id_contact;
            $message->components = "";
            $message->buttons = "";
            $message->status = 1;
            $message->value = $clean_message;
            $message->save();
        } catch (\Exception $e) {
            \Log::error("============= error ===========");
            \Log::error(json_encode($e));
        }
    }

    public static function enviarGraciasPorContestarEncuesta($id_contact)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->first()->value;
            $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->first()->value;
            $sendPhoneNumber = Contact::where('id', $id_contact)->first()->phone;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';

            // Define los componentes sin el footer

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "text",
                        "text" => [
                            "body" => "¡Gracias por completar nuestra encuesta! Tu opinión es muy valiosa para nosotros y nos ayudará a mejorar nuestros servicios."
                        ]
                    ]);

            $statusCode = $response->status();
            $content = json_decode($response->body(), true);
            $message = new Message();

            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
            }

            // Guardar el mensaje
            $message->created_at = now();
            $message->contact_id = $id_contact;
            $message->components = "";
            $message->buttons = "";
            $message->status = 1;
            $message->value = "Sidev | Faesa Gracias por contestar la encuesta";
            $message->save();

        } catch (\Exception $e) {
            \Log::error("=============== Error ==============");
            \Log::error(json_encode($e));
        }
    }

    public static function enviarMensajeMotivoReasignacion($id_contact, $message, $user_id)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $sendPhoneNumber = Contact::where('id', $id_contact)->get()->first()->phone;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            $user = User::find($user_id);
            if ($message != '') {
                $message = "Una disculpa se asingo tu soporte a " . $user->name . " por el siguiente motivo:\n\n" . $message;
            } else {
                $message = "Una disculpa se asingo tu soporte a " . $user->name . " debido a que el consultor no esta disponible";
            }
            $clean_message = str_replace("\n", '', $message);
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "text",
                        "text" => [
                            "body" => $message
                        ]
                    ]);


            $statusCode = $response->status();
            $content = json_decode($response->body(), true);
            $message = new Message();
            // $message->update_at = now();
            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
                //dd($content);
            }
            // Guardar el mensaje
            $message->created_at = now();
            $message->contact_id = $id_contact;
            $message->components = "";
            $message->buttons = "";
            $message->status = 1;
            $message->value = $clean_message;
            $message->save();
            event(new Chatlistchange($id_contact, 1));
        } catch (\Exception $e) {
            \Log::error("=============== Error ==============");
            \Log::error(json_encode($e));
        }
    }


    public static function enviarEncuesta($id_contact)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $contact = Contact::where('id', $id_contact)->get()->first();
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            $componentes = [
                [
                    "type" => "button",
                    "sub_type" => "flow",
                    "index" => "0",
                    "parameters" => [
                        [
                            "type" => "action",
                            "action" => [
                                "flow_token" => "FLOW_TOKEN"
                            ]
                        ]
                    ]
                ]
            ];
            $buttons = json_encode([["type" => "FLOW", "text" => "Encuesta de usuario", "flow_id" => 458187683576814, "flow_action" => "NAVIGATE", "navigate_screen" => "QUESTION_ONE"]]);
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "to" => $contact->phone,
                        "type" => "template",
                        "template" => [
                            "name" => "encuesta_servicio",
                            "language" => [
                                "code" => "en"
                            ],
                            "components" => $componentes
                        ]
                    ]);

            $statusCode = $response->status();
            $content = json_decode($response->body(), true);
            $message = new Message();
            // $message->update_at = now();
            if (isset($content['messages'])) {
                $message->fb_message_id = $content['messages'][0]['id'];
                $message->error = "";
            } else {
                $message->error = isset($content['error']) ? $content['error']['message'] : "Unknown error";
                //dd($content);
            }
            if (isset($message->fb_message_id)) {
                RespuestaEncuesta::create(
                    [
                        'id_contacto' => $contact->id,
                        'id_campaing' => NULL,
                        'id_usuario' => $contact->user_id,
                        'fb_message_id_encuesta' => $message->fb_message_id,
                        'respuesta_encuesta' => NULL,
                        'created_at' => now(),
                    ]
                );
            }
            // Guardar el mensaje
            $message->created_at = now();
            $message->contact_id = $id_contact;
            $message->components = json_encode($componentes);
            $message->buttons = "";
            $message->status = 1;
            $message->value = "Encuesta de satisfacción";
            $message->save();
            // Actualizar el usuario para que siga respondiendo el bot

            return true;
            // Handle the response as needed based on $statusCode and $content
        } catch (\Exception $e) {
            \Log::error("============= error ===========");
            \Log::error(json_encode($e));
            //dd($e);
            // Handle the exception
        }
    }
}
