<?php

namespace Modules\Wpbox\Http\Controllers;

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

class ChatController extends Controller
{
    use Whatsapp;

    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        if ($this->getCompany()->getConfig('whatsapp_webhook_verified', 'no') != 'yes' || $this->getCompany()->getConfig('whatsapp_settings_done', 'no') != 'yes') {
            return redirect(route('whatsapp.setup'));
        }
        $templates = Template::where('status', 'APPROVED')->select('name', 'id', 'language')->get();
        $replies = Reply::where('type', 1)->get();

        //Find the users of the company
        $users = $this->getCompany()->users()->pluck('name', 'id');
        $usuario = auth()->user();
        $permisos = null;
        if ($usuario['roles'][0]['name'] == 'staff') {
            $permisos = UserPermissionStaff::where('user_id', $usuario->id)->first()->permiso;
        }

        return view('wpbox::chat.master', [
            'templates' => $templates->toArray(),
            'replies' => $replies->toArray(),
            'users' => $users->toArray(),
            'permisosChat' => $permisos,
            'userName' => $usuario->name,
        ]);
    }






    /**
     * API
     */
    public function chatlist($lastmessagetime)
    {
        $shouldWeReturnChats = $lastmessagetime == "none";

        if (!$shouldWeReturnChats) {
            //Check for updated chats
            $data = Contact::where('has_chat', 1)->orderBy('last_reply_at', 'DESC')->first()->last_reply_at . "";
            if ($data == $lastmessagetime) {
                //Front end last message, is same as backedn last message time
                $shouldWeReturnChats = false;
            } else {
                $shouldWeReturnChats = true;
            }
        }

        if ($shouldWeReturnChats) {
            //Return list of contacts that have chat actives
            //check if current user in agent
            if (auth()->user()->hasRole('staff') && $this->getCompany()->getConfig('agent_assigned_only', 'false') != 'false') {
                $chatList = Contact::where('has_chat', 1)->where('user_id', auth()->user()->id)->with(['messages', 'country'])->orderBy('last_reply_at', 'DESC')->limit(30)->get();
            } else {
                $chatList = Contact::where('has_chat', 1)
                    ->with(['messages', 'country'])
                    ->orderBy('last_reply_at', 'DESC')
                    ->limit(30)
                    ->get();

            }

            return response()->json([
                'data' => $chatList,
                'status' => true,
                'errMsg' => '',
            ]);
        } else {
            return response()->json([
                'status' => false,
                'errMsg' => 'No changes',
            ]);
        }

    }
    public function getContact($contact_id)
    {
        $chat = Contact::where('contacts.id', $contact_id)
            ->with(['messages', 'country'])
            ->get();

        return response()->json([
            'data' => $chat,
            'status' => true,
            'errMsg' => '',
        ]);

    }
    public function searchContacts($busqueda)
    {

        $contacts = Contact::where('has_chat', 1)
            ->with(['messages', 'country'])
            ->where(function ($query) use ($busqueda) {
                $query->where('contacts.name', 'like', "%{$busqueda}%")
                    ->orWhere('contacts.phone', 'like', "%{$busqueda}%");
            })
            ->orderBy('last_reply_at', 'DESC')
            ->limit(30)
            ->get();

        return $contacts;

    }

    public function assignContact(Request $request, Contact $contact)
    {
        // Validate the request...
        $validatedData = $request->validate([
            'user_id' => 'required|exists:users,id',
            "message" => 'nullable|string'
        ]);

        // Assign the contact to the user
        $contact->user_id = $validatedData['user_id'];
        $contact->save();
        HelpersChatController::enviarMensajeMotivoReasignacion($contact->id, $validatedData['message'], $validatedData['user_id']);
        event(new Chatlistchange($contact->id, 1));

        return response()->json([
            'status' => true,
            'message' => 'Contact assigned successfully',
        ]);
    }

    public function chatmessages($contact)
    {
        $usuario = auth()->user()->id;
        $messages = Message::where('contact_id', $contact)->where('status', '>', 0)->orderBy('id', 'desc')->limit(50)->get();
        $tiempo = RegistroConversacion::GetConversation($contact);
        return response()->json([
            'data' => [
                'messages' => $messages,
                'timer' => $tiempo
            ],
            'status' => true,
            'errMsg' => '',
        ]);
    }
    public function cerrarconversacion($id_contact)
    {
        $contact = Contact::find($id_contact);
        RegistroConversacion::finishConversation($id_contact);

        if (HelpersChatController::enviarEncuesta($id_contact)) {
            $contact->user_id = null;
            $contact->eneable_auto_responses = 1;
            $contact->save();
            event(new Chatlistchange($id_contact, 1));
            return response()->json([
                'status' => true,
                'message' => 'Se termino la conversacion correctamente',
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => 'Error al terminar la conversación',
            ]);
        }
    }
    public function verifyProcessPendingJMAS()
    {
        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';

            // Botones para las opciones con iconos
            $buttons = [
                [
                    "type" => "reply",
                    "reply" => [
                        "id" => "FUGA_AGUA_MEDIDOR",
                        "title" => "💧🔧 Fuga en Medidor"
                    ]
                ],
                [
                    "type" => "reply",
                    "reply" => [
                        "id" => "FUGA_AGUA_CASA",
                        "title" => "🏠💧 Fuga en Casa"
                    ]
                ],
                [
                    "type" => "reply",
                    "reply" => [
                        "id" => "FUGA_AGUA_CALLE",
                        "title" => "🚧💧 Fuga en Calle"
                    ]
                ]
            ];

            // Enviar mensaje con botones interactivos
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => 5216255846799,//$sendPhoneNumber,
                        "type" => "interactive",
                        "interactive" => [
                            "type" => "button",
                            "body" => [
                                "text" => "💦 *Reporte de Fugas*\n\nSelecciona el tipo de fuga que deseas reportar:"
                            ],
                            "action" => [
                                "buttons" => $buttons
                            ]
                        ]
                    ]);

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

            // Manejo opcional de respuesta
            if ($response->successful()) {
                \Log::info("Mensaje enviado correctamente.");
            } else {
                \Log::error("Error al enviar el mensaje: " . json_encode($content));
            }

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

    }


    public function sendMessageToContact(Request $request, Contact $contact)
    {
        /**
         * Contact id
         * Message
         */

        // Create a validator instance
        $validator = Validator::make($request->all(), [
            'message' => 'required|string|max:500'
        ]);

        // Check if validation fails
        if ($validator->fails()) {
            $errorsText = $validator->errors()->all();
            // Convert the array of error messages to a single string
            $errorsString = implode("\n", $errorsText);
            return response()->json([
                'status' => false,
                'errMsg' => $errorsString,
            ]);
        } else if (strip_tags($request->message) != $request->message) {
            return response()->json([
                'status' => false,
                'errMsg' => __('Only text is allowed!'),
            ]);
        } else {
            //OK, we can send the message

            try {
                $messageSend = $contact->sendMessage(strip_tags($request->message), false);

                return response()->json([
                    'message' => $messageSend,
                    'messagetime' => $messageSend->created_at->format('Y-m-d H:i:s'),
                    'status' => true,
                    'errMsg' => '',
                ]);
            } catch (Exception $e) {
                if ($e->getMessage() === "[contact]")
                    return response()->json([
                        'status' => false,
                        'errMsg' => 'No puedes enviar un mensaje a un contacto asociado a otro consultor',
                    ]);
                else
                    return response()->json([
                        'status' => false,
                        'errMsg' => 'Ocurrió un error',
                    ]);
            }
        }
    }

    public function sendImageMessageToContact(Request $request, Contact $contact)
    {
        /**
         * Contact id
         * Message
         */
        $imageUrl = "";
        if (config('settings.use_s3_as_storage', false)) {
            //S3 - store per company
            $path = $request->image->storePublicly('uploads/media/send/' . $contact->company_id, 's3');
            $imageUrl = Storage::disk('s3')->url($path);
        } else {
            //Regular
            $path = $request->image->store(null, 'public_media_upload', );
            $imageUrl = Storage::disk('public_media_upload')->url($path);
        }

        $fileType = $request->file('image')->getMimeType();
        if (str_contains($fileType, 'image')) {
            // It's an image
            $messageType = "IMAGE";
        } elseif (str_contains($fileType, 'video')) {
            // It's a video
            $messageType = "VIDEO";
        } elseif (str_contains($fileType, 'audio')) {
            // It's audio
            $messageType = "VIDEO";
        } else {
            // Handle other types or show an error message
            $messageType = "IMAGE";
        }

        $messageSend = $contact->sendMessage($imageUrl, false, false, $messageType);
        return response()->json([
            'message' => $messageSend,
            'messagetime' => $messageSend->created_at->format('Y-m-d H:i:s'),
            'status' => true,
            'errMsg' => '',
        ]);
    }

    public function sendDocumentMessageToContact(Request $request, Contact $contact)
    {
        /**
         * Contact id
         * Message
         */
        $fileURL = "";
        if (config('settings.use_s3_as_storage', false)) {
            //S3 - store per company
            $path = $request->file->storePublicly('uploads/media/send/' . $contact->company_id, 's3', );
            $fileURL = Storage::disk('s3')->url($path);
        } else {
            //Regular
            $path = $request->file->store(null, 'public_media_upload', );
            $fileURL = Storage::disk('public_media_upload')->url($path);
        }

        $messageSend = $contact->sendMessage($fileURL, false, false, "DOCUMENT");
        return response()->json([
            'message' => $messageSend,
            'messagetime' => $messageSend->created_at->format('Y-m-d H:i:s'),
            'status' => true,
            'errMsg' => '',
        ]);
    }
}
