<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductReview;
use App\Models\User;
use Illuminate\Http\Request;

class AdminReviewController extends Controller
{
    public function index(Request $request)
    {
        $query = ProductReview::with(['product', 'user'])->latest();

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

        $reviews  = $query->paginate(20)->withQueryString();
        $products = Product::select('id', 'title')->orderBy('title')->get();

        $counts = [
            'pending'  => ProductReview::where('status', 'pending')->count(),
            'approved' => ProductReview::where('status', 'approved')->count(),
            'rejected' => ProductReview::where('status', 'rejected')->count(),
        ];

        return view('admin.reviews.index', compact('reviews', 'products', 'counts'));
    }

    public function create()
    {
        $products = Product::select('id', 'title')->where('is_active', true)->orderBy('title')->get();
        $users    = User::select('id', 'first_name', 'last_name', 'mobile')
            ->where('role', '!=', 'admin')
            ->orderBy('first_name')
            ->get();

        return view('admin.reviews.create', compact('products', 'users'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'user_id'    => 'required|exists:users,id',
            'rating'     => 'required|integer|min:1|max:5',
            'body'       => 'required|string|min:5|max:2000',
            'status'     => 'required|in:pending,approved,rejected',
            'pros'       => 'nullable|string|max:500',
            'cons'       => 'nullable|string|max:500',
        ]);

        ProductReview::updateOrCreate(
            ['product_id' => $request->product_id, 'user_id' => $request->user_id],
            [
                'rating' => $request->rating,
                'body'   => $request->body,
                'status' => $request->status,
                'pros'   => $this->parseTags($request->pros),
                'cons'   => $this->parseTags($request->cons),
            ]
        );

        if ($request->status === 'approved') {
            $this->recalcRating($request->product_id);
        }

        return redirect()->route('admin.reviews.index')
            ->with('success', 'دیدگاه با موفقیت ایجاد شد.');
    }

    public function edit(ProductReview $review)
    {
        $review->load(['product', 'user']);
        return view('admin.reviews.edit', compact('review'));
    }

    public function update(Request $request, ProductReview $review)
    {
        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'body'   => 'required|string|min:5|max:2000',
            'status' => 'required|in:pending,approved,rejected',
            'pros'   => 'nullable|string|max:500',
            'cons'   => 'nullable|string|max:500',
        ]);

        $review->update([
            'rating' => $request->rating,
            'body'   => $request->body,
            'status' => $request->status,
            'pros'   => $this->parseTags($request->pros),
            'cons'   => $this->parseTags($request->cons),
        ]);

        $this->recalcRating($review->product_id);

        return redirect()->route('admin.reviews.index')
            ->with('success', 'دیدگاه با موفقیت ویرایش شد.');
    }

    public function destroy(ProductReview $review)
    {
        $productId = $review->product_id;
        $review->delete();
        $this->recalcRating($productId);

        return redirect()->route('admin.reviews.index')
            ->with('success', 'دیدگاه حذف شد.');
    }

    public function approve(ProductReview $review)
    {
        $review->update(['status' => 'approved']);
        $this->recalcRating($review->product_id);
        return back()->with('success', 'دیدگاه تأیید شد.');
    }

    public function reject(ProductReview $review)
    {
        $review->update(['status' => 'rejected']);
        $this->recalcRating($review->product_id);
        return back()->with('success', 'دیدگاه رد شد.');
    }

    private function recalcRating(int $productId): void
    {
        $avg = ProductReview::where('product_id', $productId)
            ->where('status', 'approved')
            ->avg('rating');

        Product::where('id', $productId)->update(['rating' => $avg ? round($avg, 1) : 0]);
    }

    private function parseTags(?string $input): ?array
    {
        if (!$input || !trim($input)) {
            return null;
        }
        $tags = array_filter(array_map('trim', explode(',', $input)));
        return empty($tags) ? null : array_values($tags);
    }
}
