<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Message;
use Illuminate\Support\Facades\Auth;

class MessageSend extends Controller
{
    public function index()
    {
        $users = User::where('role', '!=', 'admin')->get(); // Exclude admins or adjust as needed
        return view('messages.send', compact('users'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'receiver_id' => 'required|exists:users,id',
            'message' => 'required|string|max:1000',
        ]);

        Message::create([
            'sender_id' => Auth::id(),
            'receiver_id' => $request->receiver_id,
            'message' => $request->message,
        ]);

        return redirect()->route('messages.index')->with('success', 'Message sent successfully.');
    }

    public function bulkStore(Request $request)
    {
        $request->validate([
            'receiver_ids' => 'required|array',
            'receiver_ids.*' => 'exists:users,id',
            'message' => 'required|string|max:1000',
        ]);

        foreach ($request->receiver_ids as $receiverId) {
            Message::create([
                'sender_id' => Auth::id(),
                'receiver_id' => $receiverId,
                'message' => $request->message,
            ]);
        }

        return redirect()->route('messages.index')->with('success', 'Bulk message sent successfully.');
    }

    public function memberMessages($userId)
    {
        $member = User::findOrFail($userId);
        $messages = Message::where(function ($query) use ($userId) {
            $query->where('sender_id', Auth::id())
                  ->where('receiver_id', $userId);
        })->orWhere(function ($query) use ($userId) {
            $query->where('sender_id', $userId)
                  ->where('receiver_id', Auth::id());
        })->orderBy('sent_at', 'asc')->get();

        return view('messages.member-messages', compact('member', 'messages'));
    }
}
