<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Review;
use Illuminate\Http\Request;

class ReviewController extends Controller
{
    public function index(int $id)
    {
        $reviews = Review::with('user:id,name,avatar')->where('product_id',$id)->approved()->latest()->paginate(10);
        return response()->json(['success'=>true,'data'=>$reviews]);
    }
    public function store(Request $request, int $id)
    {
        $data = $request->validate(['rating'=>'required|integer|between:1,5','title'=>'nullable|string|max:100','body'=>'required|string|max:1000']);
        $existing = Review::where(['product_id'=>$id,'user_id'=>$request->user()->id])->first();
        if($existing) return response()->json(['success'=>false,'message'=>'You already reviewed this product.'],422);
        $review = Review::create(['product_id'=>$id,'user_id'=>$request->user()->id,'is_approved'=>false]+$data);
        return response()->json(['success'=>true,'message'=>'Review submitted for approval.','data'=>$review],201);
    }
    public function update(Request $request, int $id)
    {
        $review = Review::where('user_id',$request->user()->id)->findOrFail($id);
        $review->update($request->validate(['rating'=>'integer|between:1,5','body'=>'string|max:1000']));
        return response()->json(['success'=>true,'data'=>$review]);
    }
    public function destroy(Request $request, int $id)
    {
        Review::where('user_id',$request->user()->id)->findOrFail($id)->delete();
        return response()->json(['success'=>true,'message'=>'Review deleted.']);
    }
}
