<?php

namespace App\Http\Controllers\Api;

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

class ReviewController extends Controller
{
    /**
     * Product reviews (approved only), paginated.
     */
    public function index(Request $request, Product $product)
    {
        $reviews = $product->reviews()
            ->where('status', 'approved')
            ->with(['customer:id,name'])
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 10));

        return response()->json($reviews);
    }

    /**
     * Create a review for a product.
     */
    public function store(Request $request, Product $product)
    {
        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string|max:1000',
        ]);

        $customer = $request->user();

        // Check if customer already reviewed this product
        $existing = Review::where('customer_id', $customer->id)
            ->where('product_id', $product->id)
            ->first();

        if ($existing) {
            return response()->json([
                'message' => 'لقد قمت بتقييم هذا المنتج مسبقاً',
            ], 422);
        }

        $review = Review::create([
            'customer_id' => $customer->id,
            'product_id' => $product->id,
            'rating' => $request->rating,
            'comment' => $request->comment,
            'status' => 'pending', // requires admin approval
        ]);

        return response()->json([
            'message' => 'تم إرسال التقييم وسيتم مراجعته',
            'data' => $review,
        ], 201);
    }
}
