<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestimonialController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'content' => 'required|string|max:500',
        ]);

        $user = auth()->user();

        // Check if user has a completed booking
        $hasCompletedBooking = \App\Models\Booking::where('user_id', $user->id)
            ->where('status', 'confirmed')
            ->where('check_out', '<', now())
            ->exists();

        if (!$hasCompletedBooking) {
            return back()->with('error', 'You can only review after completing a stay.');
        }

        // Check if user already reviewed (optional, but good practice to prevent spam)
        // For now allowing multiple reviews for multiple stays, but could limit here.

        \App\Models\Testimonial::create([
            'user_id' => $user->id,
            'name' => $user->name,
            'content' => $request->content,
            'rating' => $request->rating,
            'is_approved' => false, // Requires admin approval
        ]);

        return back()->with('success', 'Thank you! Your review has been submitted for approval.');
    }
}
