<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Admin\PageController;
use App\Models\MessageRecipient;
use App\Services\Comms\MessageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MessageController extends PageController
{
    public function __construct(private readonly MessageService $messages) {}

    public function index(): View
    {
        $messages = MessageRecipient::query()
            ->with(['message.sender'])
            ->where('recipient_id', auth()->id())
            ->latest()
            ->paginate(20);

        return $this->page('parent.messages.index', [
            'crumbTitle' => 'Messages',
            'crumbSub' => 'Communications from the school',
            'messages' => $messages,
        ]);
    }

    public function create(): View
    {
        return $this->page('parent.messages.create', [
            'crumbTitle' => 'Messages',
            'crumbSub' => 'Contact the school',
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'subject' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string'],
        ]);

        $this->messages->send(auth()->user(), [
            ...$validated,
            'audience_type' => 'role',
            'audience_targets' => ['Registrar', 'Front Desk'],
        ]);

        return redirect()
            ->route('parent.messages.index')
            ->with('success', 'Message sent to the school office.');
    }

    public function show(MessageRecipient $messageRecipient): View
    {
        abort_unless($messageRecipient->recipient_id === auth()->id(), 403);

        $messageRecipient->update(['read_at' => now()]);

        return $this->page('parent.messages.show', [
            'crumbTitle' => 'Messages',
            'crumbSub' => $messageRecipient->message->subject,
            'messageRecipient' => $messageRecipient->load('message.sender'),
        ]);
    }

    public function markRead(MessageRecipient $messageRecipient): RedirectResponse
    {
        abort_unless($messageRecipient->recipient_id === auth()->id(), 403);

        $messageRecipient->update(['read_at' => now()]);

        return back()->with('success', 'Message marked as read.');
    }
}
