<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\API\StoreOrderRequest;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function index(): JsonResponse
    {
        $orders = auth()->user()->orders()->with('items.product')->latest()->paginate(10);

        return response()->json([
            'data' => $orders->items(),
            'meta' => [
                'total'        => $orders->total(),
                'per_page'     => $orders->perPage(),
                'current_page' => $orders->currentPage(),
                'last_page'    => $orders->lastPage(),
            ],
        ]);
    }

    public function store(StoreOrderRequest $request): JsonResponse
    {
        return DB::transaction(function () use ($request) {
            $total = 0;

            // Validate cart items and calculate total
            $cartItems = collect($request->items)->map(function ($item) use (&$total) {
                $product = Product::findOrFail($item['product_id']);
                $lineTotal = $product->price * $item['quantity'];
                $total += $lineTotal;

                return [
                    'product_id'        => $product->id,
                    'quantity'          => $item['quantity'],
                    'price_at_purchase' => $product->price,
                ];
            });

            $order = Order::create([
                'user_id'          => auth()->id(),
                'total_amount'     => $total,
                'shipping_address' => $request->shipping_address,
                'payment_method'   => $request->payment_method ?? 'card',
                'status'           => 'pending',
            ]);

            $order->items()->createMany($cartItems->toArray());

            return response()->json([
                'data'    => $order->load('items.product'),
                'message' => 'Order placed successfully.',
            ], 201);
        });
    }

    public function show(Order $order): JsonResponse
    {
        // Ensure users can only view their own orders
        abort_unless($order->user_id === auth()->id() || auth()->user()->is_admin, 403, 'Forbidden.');

        return response()->json(['data' => $order->load('items.product')]);
    }

    // Admin: Get all orders
    public function adminIndex(Request $request): JsonResponse
    {
        $orders = Order::with('user', 'items.product')
            ->when($request->status, fn ($q) => $q->where('status', $request->status))
            ->latest()
            ->paginate(20);

        return response()->json([
            'data' => $orders->items(),
            'meta' => [
                'total'        => $orders->total(),
                'per_page'     => $orders->perPage(),
                'current_page' => $orders->currentPage(),
                'last_page'    => $orders->lastPage(),
            ],
        ]);
    }

    // Admin: Update order status
    public function updateStatus(Request $request, Order $order): JsonResponse
    {
        $request->validate([
            'status' => 'required|in:pending,processing,shipped,delivered,cancelled',
        ]);

        $order->update(['status' => $request->status]);

        return response()->json(['data' => $order, 'message' => 'Order status updated.']);
    }
}
