<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\InternalMessage;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class InternalMessageController extends Controller
{
    public function index(): View
    {
        return view('admin.internal-messages', [
            'messages' => InternalMessage::query()->latest('id')->paginate(40),
            'users' => User::query()->whereIn('role', ['user', 'franchise'])->orderBy('name')->limit(300)->get(['id', 'name', 'member_code', 'role']),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'mode' => ['required', 'in:direct,broadcast'],
            'receiver_id' => ['nullable', 'exists:users,id'],
            'subject' => ['nullable', 'string', 'max:191'],
            'message' => ['required', 'string', 'max:5000'],
        ]);

        if ($validated['mode'] === 'broadcast') {
            InternalMessage::query()->create([
                'sender_id' => auth()->id(),
                'receiver_id' => null,
                'channel' => 'broadcast',
                'subject' => $validated['subject'] ?? 'Broadcast',
                'message' => $validated['message'],
            ]);

            return back()->with('status', 'Broadcast message posted.');
        }

        if (empty($validated['receiver_id'])) {
            return back()->withErrors(['receiver_id' => 'Receiver is required for direct message.']);
        }

        InternalMessage::query()->create([
            'sender_id' => auth()->id(),
            'receiver_id' => (int) $validated['receiver_id'],
            'channel' => 'direct',
            'subject' => $validated['subject'] ?? null,
            'message' => $validated['message'],
        ]);

        return back()->with('status', 'Direct message sent.');
    }
}
