<?php

namespace App\Http\Controllers\Api;

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

class ReviewController extends Controller
{
    public function my(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unauthenticated',
            ], 401);
        }

        $query = Review::with(['product'])
            ->where('user_id', $user->id);

        if ($request->filled('order_id')) {
            $orderId = (int) $request->order_id;
            $itemIds = \App\Models\OrderItem::where('order_id', $orderId)->pluck('id');
            $query->whereIn('order_item_id', $itemIds);
        }

        $reviews = $query->get()->map(function ($r) {
            return [
                'id' => $r->id,
                'order_item_id' => $r->order_item_id,
                'product_id' => $r->product_id,
                'rating' => (int)$r->rating,
                'comment' => $r->comment,
                'created_at' => $r->created_at,
            ];
        });

        return response()->json([
            'status' => 'success',
            'data' => $reviews
        ]);
    }

    public function index(Request $request)
    {
        // Admin-selected IDs take precedence
        if ($request->filled('ids')) {
            $ids = collect(explode(',', (string) $request->ids))
                ->map(fn ($v) => (int) trim($v))
                ->filter(fn ($v) => $v > 0)
                ->values()
                ->all();

            if (!empty($ids)) {
                $placeholders = implode(',', $ids);
                $rows = Review::with(['user', 'product'])
                    ->whereIn('id', $ids)
                    ->orderByRaw("FIELD(id, $placeholders)")
                    ->get();

                $reviews = $rows->map(function ($r) {
                    return [
                        'id' => $r->id,
                        'product_id' => $r->product_id,
                        'user' => [
                            'id' => $r->user->id ?? null,
                            'name' => $r->user->name ?? 'User',
                        ],
                        'rating' => (int) $r->rating,
                        'comment' => $r->comment,
                        'created_at' => $r->created_at,
                    ];
                });

                return response()->json([
                    'status' => 'success',
                    'data' => $reviews
                ]);
            }
        }

        $query = Review::with(['user', 'product']);
        if ($request->filled('product_id')) {
            $query->where('product_id', $request->product_id);
        }
        $reviews = $query->latest()->take(50)->get()->map(function ($r) {
            return [
                'id' => $r->id,
                'product_id' => $r->product_id,
                'user' => [
                    'id' => $r->user->id ?? null,
                    'name' => $r->user->name ?? 'User',
                ],
                'rating' => (int)$r->rating,
                'comment' => $r->comment,
                'created_at' => $r->created_at,
            ];
        });
        return response()->json([
            'status' => 'success',
            'data' => $reviews
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|integer',
            'order_item_id' => 'required|integer',
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string|max:1000',
        ]);

        $user = $request->user();
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unauthenticated',
            ], 401);
        }

        $item = OrderItem::with('order')->findOrFail($request->order_item_id);
        if ($item->order->user_id !== $user->id) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unauthorized',
            ], 403);
        }

        $status = strtolower($item->order->status ?? '');
        if (!in_array($status, ['delivered', 'completed'])) {
            return response()->json([
                'status' => 'error',
                'message' => 'You can only review delivered orders',
            ], 400);
        }

        $exists = Review::where('user_id', $user->id)
            ->where('order_item_id', $item->id)
            ->exists();
        if ($exists) {
            return response()->json([
                'status' => 'error',
                'message' => 'You have already reviewed this item',
            ], 400);
        }

        $review = Review::create([
            'user_id' => $user->id,
            'product_id' => $request->product_id,
            'order_item_id' => $item->id,
            'rating' => $request->rating,
            'comment' => $request->comment,
        ]);

        return response()->json([
            'status' => 'success',
            'message' => 'Review submitted',
            'data' => [
                'id' => $review->id,
                'rating' => (int)$review->rating,
                'comment' => $review->comment,
            ],
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string|max:1000',
        ]);

        $user = $request->user();
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unauthenticated',
            ], 401);
        }

        $review = Review::findOrFail($id);
        if ($review->user_id !== $user->id) {
            return response()->json([
                'status' => 'error',
                'message' => 'Unauthorized',
            ], 403);
        }

        $review->update([
            'rating' => $request->rating,
            'comment' => $request->comment,
        ]);

        return response()->json([
            'status' => 'success',
            'message' => 'Review updated',
            'data' => [
                'id' => $review->id,
                'rating' => (int)$review->rating,
                'comment' => $review->comment,
            ],
        ]);
    }
}
