<?php

namespace Mtc\Plugins\MembersMessaging\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\MembersMessaging\Models\Thread;
use Mtc\Core\AdminUser;

class AdminMessagesController extends Controller
{
    // Considering just invoking this
    public function store(Request $request)
    {
        $validated = $request->validate([
            'text' => 'required|string',
            'url' => 'required|exists:messenger_threads,url'
        ]);
        
        $thread = Thread::whereUrl($validated['url'])
            ->first();

        if($thread->isClosedOrArchived()) {
            return response()->json([
                'success' => false,
                'message' => 'Thread is closed or archived.'
            ], 400);
        }
        
        if(!$thread) {
            return response()->json([
                'success' => false,
                'message' => 'Thread not found.'
            ], 400);
        }
        
        $message = $thread->messages()->create([
            'admin_id' => AdminUser::getCurrent()->id,
            'text' => $validated['text'],
            'private' => $request->private ? 1 :  0,
        ]);

        if ($request->private == 0) {
            $member = Member::find($thread->member_id);

            $emailBody = app('twig')->render('emails/new_message.twig', [
                'member' => $member->id,
                'message_text' => $message->text,
                'thread_url' => route('messaging.view_thread', $thread->url)
            ]);

            email($member->email, "You've received a new message on " . config('app.name'), $emailBody, ['dev_copy' => DEV_MODE]);
        }

        $thread->response_time = $thread->calculateResponseTime();

        $thread->save();

        return response()->json([
            'success' => true,
            'message' => 'Message has been successfully sent.',
        ], 200);
    }
}
