<?php

namespace Wave\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\ServiceChat;
use App\Models\ServiceChatMessage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

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

    public function getChatMessages(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'service_type' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        $user = JWTAuth::user();
        $newCollection = collect();
        $chat = ServiceChat::where('company_id', $user->company_id)
            ->where('user_id', $user->id)
            ->where('service_type', $request->service_type)
            ->first();
        $messages = $chat ? $chat->messages : null;
        if ($messages) {
            $newCollection = $messages->map(function ($message) use ($user) {
                $message->date = $message->created_at->format('Y-m-d');
                $message->is_own_message = $user->id == $message->from_user_id ? true : false;
                $message->elapsed_time = $message->elapsed_time;
                $message->message = $message->is_file ? '<a href="' . $message->file_url . '" target="_blank">' . $message->file_name . '</a>' : $message->message;

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

        return response()->json([
            'message' => 'Chat messages has successfully retrieved!',
            'data' => $newCollection,
        ]);
    }

    public function sendChat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'chat_service_type' => 'required',
            'chat_message' => 'required_without:chat_message_file',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        $user = JWTAuth::user();
        $chat = ServiceChat::where('company_id', $user->company_id)
            ->where('user_id', $user->id)
            ->where('service_type', $request->chat_service_type)
            ->first();
        if (! $chat) {
            $chat = new ServiceChat();
            $chat->company_id = $user->company_id;
            $chat->user_id = $user->id;
            $chat->service_type = $request->chat_service_type;
            $chat->save();
        }

        $messageFileName = '';
        if ($request->hasFile('chat_message_file')) {
            $file = $request->file('chat_message_file');
            $messageFileName = $request->file('chat_message_file')->getClientOriginalName();
            $file->storePubliclyAs($chat->folder_path, $messageFileName);
        }

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

        return response()->json([
            'message' => 'Chat message has successfully sent!',
        ]);
    }
}
