<?php
namespace App\Http\Controllers\API\Vendor;

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

class VendorReviewController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $vendorId = $request->user()->vendor->id;
        $reviews = Review::with(['user:id,name,avatar', 'product:id,name,thumbnail'])
            ->whereHas('product', fn($q) => $q->where('vendor_id', $vendorId))
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->when($request->rating, fn($q) => $q->where('rating', $request->rating))
            ->latest()->paginate(15);
        return response()->json($reviews);
    }
    public function show(Request $request, int $id): JsonResponse
    {
        $review = Review::with(['user', 'product'])->findOrFail($id);
        return response()->json(['review' => $review]);
    }
    public function reply(Request $request, int $id): JsonResponse
    {
        $review = Review::findOrFail($id);
        $data = $request->validate(['reply' => 'required|string|max:1000']);
        $review->update(['vendor_reply' => $data['reply'], 'vendor_replied_at' => now()]);
        return response()->json(['message' => 'Reply posted.']);
    }
}
