<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        $orders = Order::with('user','items')->when($request->status,fn($q)=>$q->where('status',$request->status))->latest()->paginate(20);
        return response()->json(['success'=>true,'data'=>$orders]);
    }
    public function updateStatus(Request $request, int $id)
    {
        $request->validate(['status'=>'required|in:pending,confirmed,packed,shipped,delivered,cancelled','tracking_number'=>'nullable|string','courier'=>'nullable|string']);
        $order = Order::findOrFail($id);
        $order->update($request->only('status','tracking_number','courier'));
        if($request->status === 'delivered') $order->update(['payment_status'=>'paid']);
        return response()->json(['success'=>true,'data'=>$order]);
    }
}
