<?php

namespace App\Http\Controllers\Api\Admin;

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

class ReviewController extends Controller
{
    /**
     * List all reviews.
     */
    public function index(Request $request)
    {
        $query = Review::with(['customer:id,name,phone', 'product:id,name_ar,name_en,slug']);

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('product_id')) {
            $query->where('product_id', $request->product_id);
        }

        if ($request->filled('rating')) {
            $query->where('rating', $request->rating);
        }

        return response()->json(
            $query->orderBy('created_at', 'desc')
                ->paginate($request->get('per_page', 20))
        );
    }

    /**
     * Approve a review.
     */
    public function approve(Review $review)
    {
        $review->update(['status' => 'approved']);

        // Update product average rating
        $this->updateProductRating($review->product_id);

        return response()->json([
            'message' => 'تم قبول التقييم',
            'data' => $review,
        ]);
    }

    /**
     * Reject a review.
     */
    public function reject(Review $review)
    {
        $review->update(['status' => 'rejected']);

        // Update product average rating
        $this->updateProductRating($review->product_id);

        return response()->json([
            'message' => 'تم رفض التقييم',
            'data' => $review,
        ]);
    }

    /**
     * Reply to a review.
     */
    public function reply(Request $request, Review $review)
    {
        $request->validate([
            'reply' => 'required|string|max:1000',
        ]);

        $review->update([
            'admin_reply' => $request->reply,
            'replied_at' => now(),
        ]);

        return response()->json([
            'message' => 'تم الرد على التقييم',
            'data' => $review,
        ]);
    }

    /**
     * Update product average rating after review approval/rejection.
     */
    private function updateProductRating(int $productId): void
    {
        $stats = Review::where('product_id', $productId)
            ->where('status', 'approved')
            ->selectRaw('AVG(rating) as avg_rating, COUNT(*) as count')
            ->first();

        \App\Models\Product::where('id', $productId)->update([
            'avg_rating' => round($stats->avg_rating ?? 0, 2),
            'reviews_count' => $stats->count ?? 0,
        ]);
    }
}
