<?php

namespace App\Http\Controllers;

use App\Models\Review;
use App\Models\Seller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

        // Check if buyer has already reviewed this seller (optional, but good practice)
        $existingReview = Review::where('buyer_id', Auth::user()->buyer->id)
            ->where('seller_id', $seller->id)
            ->first();

        if ($existingReview) {
            return redirect()->back()->with('error', 'You have already reviewed this seller.');
        }

        Review::create([
            'buyer_id' => Auth::user()->buyer->id,
            'seller_id' => $seller->id,
            'rating' => $request->rating,
            'comment' => $request->comment,
            'is_approved' => false, // Requires admin approval
        ]);

        return redirect()->back()->with('success', 'Review submitted successfully! It will be visible after approval.');
    }
}
