<?php

namespace Modules\Wpbox\Http\Controllers;

use App\Models\Config;
use App\Models\RegistroConversacion;
use App\Models\RespuestaEncuesta;
use App\Models\User;
use Carbon\Carbon;
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\Contacts\Models\Group;
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 Registro extends Controller
{
    use Whatsapp;
    public static function iniciarRegistro(Contact $contact)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccessToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            $contact->proceso_realizando = "PIDIENDO_CODIGO_POSTAL";
            $contact->save();
            $texto = "📋 Para registrarte, por favor compártenos el nombre de tu colonia 🏡 para completar el registro. ¡Gracias! 😊";


            // Enviar mensaje a través de la API de WhatsApp
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccessToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $contact->phone,
                        "type" => "text",
                        "text" => [
                            "body" => $texto
                        ]
                    ]);

            $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 en la base de datos
            $clean_message = str_replace("\n", ' ', $texto); // Limpiar saltos de línea para almacenamiento
            $message->created_at = now();
            $message->contact_id = $contact->id;
            $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 guardar_cp_pedir_colonia(Contact $contact, $message)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccessToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            $contact->proceso_realizando = null;
            $texto = "Gracias por compartirnos tu codigo postal, si pudieras seleccionar la colonia";
            \Log::debug($message);
            $groups = Group::whereRaw("
                SOUNDEX(name) like concat('%',SOUNDEX(?),'%')
                ", [$message])->first();
            if (!$groups) {
                $texto = "❌ No encontramos tu colonia en nuestros registros. 🏡 Por favor, verifica que esté correctamente escrita y vuelve a enviarnos el nombre. ¡Estamos aquí para ayudarte! 😊";
                $buttons = [
                    [
                        "type" => "reply",
                        "reply" => [
                            "id" => "TERMINAR_PROCESO",
                            "title" => "Cancelar suscripción"
                        ]
                    ]
                ];
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . $whatsappPermanentAccessToken,
                    'Content-Type' => 'application/json',
                ])->post($url, [
                            "messaging_product" => "whatsapp",
                            "recipient_type" => "individual",
                            "to" => $contact->phone,
                            "type" => "interactive",
                            "interactive" => [
                                "type" => "button",
                                "body" => [
                                    "text" => $texto
                                ],
                                "action" => [
                                    "buttons" => $buttons
                                ]
                            ]
                        ]);
                $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 en la base de datos
                $clean_message = str_replace("\n", ' ', $texto); // Limpiar saltos de línea para almacenamiento
                $message->created_at = now();
                $message->contact_id = $contact->id;
                $message->components = "";
                $message->buttons = json_encode($buttons);
                $message->status = 1;
                $message->value = $clean_message;
                $message->save();
                return $message;
            }
            if (!$contact->groups->contains($groups->id)) {
                // Agregar el grupo al contacto sin eliminar los existentes
                $contact->groups()->attach($groups->id);
            }
            $contact->ultimo_grupo_registrado = $groups->id;
            $contact->update();
            $texto = "🎉 Te registramos en la colonia {$groups->name}  📢📬 ¿Estás de acuerdo?";
            $buttons = [
                [
                    "type" => "reply",
                    "reply" => [
                        "id" => "agree_group",
                        "title" => "Estoy de acuerdo"
                    ]
                ],
                [
                    "type" => "reply",
                    "reply" => [
                        "id" => "not_agree_group",
                        "title" => "No estoy de acuerdo"
                    ]
                ],
                [
                    "type" => "reply",
                    "reply" => [
                        "id" => "TERMINAR_PROCESO",
                        "title" => "Cancelar suscripción"
                    ]
                ]
            ];
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccessToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $contact->phone,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "button",
                            "body" => [
                                "text" => $texto
                            ],
                            "action" => [
                                "buttons" => $buttons
                            ]
                        ]
                    ]);


            $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 en la base de datos
            $clean_message = str_replace("\n", ' ', $texto); // Limpiar saltos de línea para almacenamiento
            $message->created_at = now();
            $message->contact_id = $contact->id;
            $message->components = "";
            $message->buttons = json_encode($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 gracias_registrarte_volver_comenzar(Contact $contact, $message)
    {
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccessToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            if ($message == 'agree_group') {
                $texto = "🎉📢 Muchas gracias por registrarte estaras recibiendo todas las notificaciones acerca de tu colonia 📬 😊";
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . $whatsappPermanentAccessToken,
                    'Content-Type' => 'application/json',
                ])->post($url, [
                            "messaging_product" => "whatsapp",
                            "recipient_type" => "individual",
                            "to" => $contact->phone,
                            "type" => "text",
                            "text" => [
                                "body" => $texto
                            ]
                        ]);
                $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 en la base de datos
                $clean_message = str_replace("\n", ' ', $texto); // Limpiar saltos de línea para almacenamiento
                $message->created_at = now();
                $message->contact_id = $contact->id;
                $message->components = "";
                $message->buttons = "";
                $message->status = 1;
                $message->value = $clean_message;
                $message->save();

                return $message;

            } else {

                $contact->proceso_realizando = "PIDIENDO_CODIGO_POSTAL";
                if ($contact->ultimo_grupo_registrado) {
                    $contact->groups()->detach($contact->ultimo_grupo_registrado);
                    $contact->ultimo_grupo_registrado = null; // Limpiar el campo
                }
                $contact->save();
                $texto = "📋 Para registrarte vuelve a enviarnos el nombre de tu colonia 🏡 para completar el registro. ¡Gracias! 😊";
                $buttons = [
                    [
                        "type" => "reply",
                        "reply" => [
                            "id" => "TERMINAR_PROCESO",
                            "title" => "Cancelar suscripción"
                        ]
                    ]
                ];

                // Enviar mensaje a través de la API de WhatsApp
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . $whatsappPermanentAccessToken,
                    'Content-Type' => 'application/json',
                ])->post($url, [
                            "messaging_product" => "whatsapp",
                            "recipient_type" => "individual",
                            "to" => $contact->phone,
                            "type" => "interactive",
                            "interactive" => [
                                "type" => "button",
                                "body" => [
                                    "text" => $texto
                                ],
                                "action" => [
                                    "buttons" => $buttons
                                ]
                            ]
                        ]);

            }


            $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 en la base de datos
            $clean_message = str_replace("\n", ' ', $texto); // Limpiar saltos de línea para almacenamiento
            $message->created_at = now();
            $message->contact_id = $contact->id;
            $message->components = "";
            $message->buttons = json_encode($buttons);
            $message->status = 1;
            $message->value = $clean_message;
            $message->save();

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

    }

}
