<?php

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

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Http\JsonResponse;
use Mtc\Plugins\MembersMessaging\Classes\Thread;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeConsultation;

/**
 * Class ConsultationController
 */
class MessageController extends ClinicController
{
    /**
     * Load entries
     *
     * @param $id
     * @return JsonResponse
     */
    public function load($id): JsonResponse
    {
        $threads = Thread::query()
            ->with('messages.member.addressBilling')
            ->with('messages.admin_user', function (BelongsTo $query): void {
                $query->select('id', 'name');
            })
            ->whereHas('messages')
            ->where('member_id', $id)
            ->get()
            ->map(function ($thread) {
                $firstMessage = $thread->messages->sortBy('created_at')->first();
                $thread->author = $firstMessage->authorName();
                $thread->date = $thread->created_at->format('d.m.Y H:i:s');
                $thread->viewUrl = '/plugins/MembersMessaging/admin/view_member_thread.php?url='.$thread->url;
                $thread->messages
                    ->map(function ($message) {
                        $message->date = $message->created_at->format('d.m.Y H:i:s');
                        $message->author = $message->authorName();

                        return $message;
                    });

                return $thread;
            });

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