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

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

class VendorOrderController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $vendorId = $request->user()->vendor->id;
        $orders = Order::with(['user:id,name,email,phone', 'items.product:id,name,thumbnail'])
            ->where('vendor_id', $vendorId)
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->when($request->search, fn($q) => $q->where('order_number', 'like', "%{$request->search}%"))
            ->latest()->paginate(15);
        return response()->json($orders);
    }

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

    public function updateStatus(Request $request, int $id): JsonResponse
    {
        $order = Order::where('vendor_id', $request->user()->vendor->id)->findOrFail($id);
        $data = $request->validate([
            'status'           => 'required|in:confirmed,processing,shipped,delivered,cancelled',
            'tracking_number'  => 'nullable|string',
            'shipping_carrier' => 'nullable|string',
        ]);

        $allowed = match ($order->status) {
            'pending'    => ['confirmed', 'cancelled'],
            'confirmed'  => ['processing', 'cancelled'],
            'processing' => ['shipped'],
            'shipped'    => ['delivered'],
            default      => [],
        };

        if (!in_array($data['status'], $allowed)) {
            return response()->json(['message' => "Cannot change status from {$order->status} to {$data['status']}."], 422);
        }

        $updates = ['status' => $data['status']];
        if ($data['status'] === 'shipped') {
            $updates['shipped_at'] = now();
            $updates['tracking_number'] = $data['tracking_number'] ?? null;
            $updates['shipping_carrier'] = $data['shipping_carrier'] ?? null;
        }
        if ($data['status'] === 'delivered') {
            $updates['delivered_at'] = now();
            // Credit vendor earnings
            $order->vendor->increment('balance', $order->vendor_earnings);
        }

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