<?php

namespace Mtc\Plugins\Clinic\Http\Controllers\Admin;

use Illuminate\Http\JsonResponse;
use Mtc\Plugins\MembersMessaging\Models\Message;
use Mtc\Plugins\MembersMessaging\Models\Thread;

/**
 * Class ConsultationController
 */
class MessageController extends ClinicController
{

    /**
     * Load entries
     *
     * @param $id
     * @return JsonResponse
     */
    public function load($id): JsonResponse
    {
        $threads = Thread::query()
            ->with([
                'messages' => function ($query) {
                    $query->orderBy('created_at');
                },
                'messages.member',
                'messages.admin_user:id,name',
            ])
            ->whereHas('messages')
            ->where('member_id', $id)
            ->orderByDesc('created_at')
            ->get()
            ->map(function (Thread $thread) {
                $messages = $thread->messages->map(function (Message $message) {
                    return [
                        'id' => $message->id,
                        'author' => $message->authorName(),
                        'authorType' => $message->authorType(),
                        'date' => optional($message->created_at)->format('d.m.Y H:i:s'),
                        'text' => $message->text,
                        'private' => (int)$message->private,
                    ];
                })->values();

                $firstMessage = $messages->first();

                return [
                    'id' => $thread->id,
                    'author' => $firstMessage['author'] ?? 'Unknown Author',
                    'date' => optional($thread->created_at)->format('d.m.Y H:i:s'),
                    'viewUrl' => route('admin.messaging.view_thread', ['url' => $thread->url]),
                    'messages' => $messages,
                ];
            })
            ->values();

        return response()->json([
            'threads' => $threads,
        ]);
    }
}
