<?php

namespace App\Http\Controllers;

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

class ReviewController extends Controller
{
    public function create($code)
    {
        $booking = Booking::with('customer')->where('code', $code)->firstOrFail();
        $review = Review::where('booking_id', $booking->id)->first();

        return view('site.review', compact('booking', 'review'));
    }

    public function store(Request $request, $code)
    {
        $booking = Booking::with('customer')->where('code', $code)->firstOrFail();

        $data = $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'title' => 'nullable|string|max:120',
            'comment' => 'nullable|string|max:2000',
        ]);

        if (Review::where('booking_id', $booking->id)->exists()) {
            return back()->with('error', 'This stay has already been reviewed — thank you!');
        }

        Review::create([
            'booking_id' => $booking->id,
            'hotel_id' => $booking->hotel_id ?? null,
            'customer_name' => $booking->customer->name ?? 'Guest',
            'rating' => $data['rating'],
            'title' => $data['title'] ?? null,
            'comment' => $data['comment'] ?? null,
            'status' => 'pending',
        ]);

        return back()->with('success', 'Thank you! Your review is awaiting moderation.');
    }
}
