<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Message;
use Illuminate\Http\Request;

class MessageController extends Controller
{
    public function index(Booking $booking)
    {
        $this->authorize('view', $booking);
        $messages = $booking->messages()->with(['sender', 'receiver'])->latest()->get();

        return view('messages.index', compact('booking', 'messages'));
    }

    public function store(Booking $booking, Request $request)
    {
        $this->authorize('view', $booking);
        $data = $request->validate(['body' => 'required|string']);
        $user = $request->user();
        $receiverId = $user->id === $booking->customer_id ? $booking->provider_id : $booking->customer_id;

        Message::create([
            'booking_id' => $booking->id,
            'sender_id' => $user->id,
            'receiver_id' => $receiverId,
            'body' => $data['body'],
        ]);

        return back()->with('status', 'Message sent');
    }
}
