<?php

namespace Wave\Http\Controllers\CMS;

use App\Events\ChatEvent;
use App\Http\Controllers\Controller;
use App\Models\ServiceChat;
use App\Models\ServiceChatMessage;
use App\Models\User;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ChatController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application cms dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('theme::cms.chats.index');
    }
    
    public function getChats(Request $request)
    {
        $chats = ServiceChat::latest()
            ->select('service_chats.*')
            ->leftJoin('users', 'service_chats.user_id', '=', 'users.id')
            ->whereNull('users.deleted_at')
            ->get()
            ->groupBy('user_id', 'company_id')
            ->map(static function ($chat) {
                $unreadCount = 0;
                $chat->map(static function ($item) use (&$unreadCount) {
                    $unreadCount += $item->messages->where('to_admin', true)->where('is_read', false)->count();
                });

                $chat = $chat->first();
                $chat->unread_count = $unreadCount;
                $chat->user_id = $chat->user->id;
                $chat->user_first_name = $chat->user->first_name;
                $chat->user_last_name = $chat->user->last_name;
                $chat->company_id = $chat->company->id;
                $chat->company_name = $chat->company->name;

                unset($chat->user);
                unset($chat->company);
                
                return $chat;
            })
            ->values()
            ->all();

        return response()->json([
            'success' => true,
            'chats' => $chats,
        ]);
    }

    public function getTopics(Request $request)
    {
        $chats = ServiceChat::latest()
            ->select('service_chats.*')
            ->leftJoin('users', 'service_chats.user_id', '=', 'users.id')
            ->whereNull('users.deleted_at')
            ->where('service_chats.user_id', $request->userId)
            ->where('service_chats.company_id', $request->companyId)
            ->get()
            ->map(static function ($chat) {
                $chat->topic = $chat->service_type == 'bookkeeping' ? __("Bookkeeping Service") : __("Company Secretary Service");
                $chat->date = $chat->created_at->format('d/m/Y');
                $chat->first_message = $chat->messages->count() ? $chat->messages->first()->message : '';
                $chat->unread_count = $chat->messages->where('to_admin', true)->where('is_read', false)->count();

                unset($chat->messages);
                
                return $chat;
            });
        $user = User::find($request->userId);
        $company = Company::find($request->companyId);
        $company->adderss = $company->address;

        return response()->json([
            'success' => true,
            'chats' => $chats,
            'user' => $user,
            'company' => $company,
        ]);
    }

    public function getMessages(ServiceChat $serviceChat)
    {
        $newCollection = collect();
        $messages = $serviceChat ? $serviceChat->messages : null;
        if ($messages) {
            $newCollection = $messages->map(function ($message) use ($serviceChat) {
                $message->date = $message->created_at->format('Y-m-d');
                $message->is_own_message = request()->user()->id == $message->from_user_id ? true : false;
                $message->elapsed_time = $message->elapsed_time;
                $message->is_today = $message->created_at->format('Y-m-d') == date('Y-m-d') ? true : false;
                $message->message = $message->is_file ? '<a href="' . $message->file_url . '" target="_blank">' . $message->file_name . '</a>' : $message->message;

                $userFirstName = $serviceChat->user->first_name ? ucfirst($serviceChat->user->first_name) : '';
                $userLastName = $serviceChat->user->last_name ? ucfirst($serviceChat->user->last_name) : '';
                $userInitial = ($userFirstName ? $userFirstName[0] : '') . ($userLastName ? $userLastName[0] : '');
                $message->initials = $message->is_own_message ? 'CS' : ($userInitial ? $userInitial : '-');

                return $message;
            })
            ->groupBy('date')
            ->map(function ($message) {
                return $message->flatmap(function ($item) use ($message) {
                    return [
                        'date' => $item->created_at->format('d F, Y'),
                        'is_today' => $item->is_today,
                        'messages' => $message,
                    ];
                });
            })
            ->values()
            ->all();

            ServiceChatMessage::whereIn('id', $messages->pluck('id')->toArray())
                ->where('to_admin', true)
                ->update(['is_read' => true]);
        }

        return response()->json([
            'success' => true,
            'data' => $newCollection,
        ]);
    }

    public function sendMessage(ServiceChat $serviceChat, Request $request)
    {
        $messageFileName = '';
        if ($request->hasFile('chat_message_file')) {
            $file = $request->file('chat_message_file');
            $messageFileName = $request->file('chat_message_file')->getClientOriginalName();
            $file->storePubliclyAs($serviceChat->folder_path, $messageFileName);
        }

        ServiceChatMessage::create([
            'service_chat_id' => $serviceChat->id,
            'message' => $request->chat_message,
            'from_user_id' => $request->user()->id,
            'to_user_id' => $serviceChat->user_id,
            'is_file' => $messageFileName ? true : false,
            'file_name' => $messageFileName,
        ]);

        ChatEvent::dispatch($serviceChat->id, false, $serviceChat->user_id);

        return response()->json([
            'success' => true,
        ]);
    }
}
