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

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

class AdminOrderController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $orders = Order::with(['user:id,name,email', 'vendor:id,store_name'])
            ->when($request->search, fn($q) => $q->where('order_number', 'like', "%{$request->search}%"))
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->when($request->payment_status, fn($q) => $q->where('payment_status', $request->payment_status))
            ->when($request->vendor_id, fn($q) => $q->where('vendor_id', $request->vendor_id))
            ->latest()
            ->paginate(15);

        return response()->json($orders);
    }

    public function show(int $id): JsonResponse
    {
        $order = Order::with(['user', 'vendor', 'items.product', 'coupon'])->findOrFail($id);
        return response()->json(['order' => $order]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $order = Order::findOrFail($id);
        $data = $request->validate([
            'status'           => 'sometimes|in:pending,confirmed,processing,shipped,delivered,cancelled,refunded',
            'tracking_number'  => 'sometimes|nullable|string',
            'shipping_carrier' => 'sometimes|nullable|string',
        ]);
        $order->update($data);
        return response()->json(['message' => 'Order updated.', 'order' => $order]);
    }

    public function destroy(int $id): JsonResponse
    {
        return response()->json(['message' => 'Orders cannot be deleted.'], 403);
    }

    public function store(Request $request): JsonResponse
    {
        return response()->json(['message' => 'Orders are placed by customers.'], 405);
    }
}
