<?php

namespace App\Http\Controllers\Marketplace;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Review;
use App\Models\Order; 
use Illuminate\Http\Request;

class ReviewController extends Controller
{
    public function store(Request $request, Product $product)
    {
        $userId = auth()->id();

        // --- Cast to int ---
        if ((int) $userId === (int) $product->seller_id) {
            return back()->withErrors(['error' => 'You cannot review your own product.']);
        }

        $hasReviewed = Review::where('user_id', $userId)->where('product_id', $product->id)->exists();
        if ($hasReviewed) {
            return back()->withErrors(['error' => 'You have already reviewed this product.']);
        }

        $hasPurchased = Order::where('buyer_id', $userId)
            ->where('status', 'completed')
            ->whereHas('items', function ($q) use ($product) {
                $q->where('product_id', $product->id);
            })->exists();

        if (!$hasPurchased) {
            return back()->withErrors(['error' => 'You can only review products you have purchased and received.']);
        }

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

        Review::create([
            'user_id' => $userId,
            'product_id' => $product->id,
            'rating' => $request->rating,
            'comment' => $request->comment
        ]);

        return back()->with('success', 'Your review has been submitted!');
    }
}