<?php

namespace App\Http\Controllers\Vendor;

use App\Http\Controllers\Controller;
use App\Models\OrderItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VendorOrderController extends Controller
{
    protected function vendor()
    {
        return Auth::user()->vendor;
    }

    public function index(Request $request)
    {
        $vendor = $this->vendor();
        $orderItems = $vendor->orderItems()
            ->with(['order.user', 'product'])
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->latest()
            ->paginate(20);

        return view('vendor.orders.index', compact('orderItems'));
    }

    public function show($id)
    {
        $vendor = $this->vendor();
        $orderItem = $vendor->orderItems()
            ->with(['order.user', 'product'])
            ->findOrFail($id);

        return view('vendor.orders.show', compact('orderItem'));
    }

    public function updateStatus(Request $request, $id)
    {
        $vendor = $this->vendor();
        $orderItem = $vendor->orderItems()->with('order')->findOrFail($id);

        $request->validate([
            'status' => 'required|in:processing,shipped,delivered,cancelled',
            'tracking_number' => 'nullable|string|max:100',
        ]);

        $orderItem->update([
            'status' => $request->status,
            'tracking_number' => $request->tracking_number,
        ]);

        // Reload order with all items to get fresh data
        $order = $orderItem->order->fresh();
        
        // Update parent order status based on item statuses
        $this->updateParentOrderStatus($order);

        return back()->with('success', 'Order item status updated.');
    }

    /**
     * Update parent order status based on the status of all its items
     */
    protected function updateParentOrderStatus($order)
    {
        // Reload items to get fresh data
        $items = $order->items()->get();
        $allStatuses = $items->pluck('status')->unique();

        // If all items have the same status, update order to that status
        if ($allStatuses->count() === 1) {
            $order->update(['status' => $allStatuses->first()]);
            return;
        }

        // If any item is shipped, order is partially shipped
        if ($allStatuses->contains('shipped')) {
            $order->update(['status' => 'shipped']);
            return;
        }

        // If any item is delivered, order is partially delivered but keep as processing
        if ($allStatuses->contains('delivered')) {
            if (!in_array($order->status, ['shipped', 'delivered'])) {
                $order->update(['status' => 'processing']);
            }
            return;
        }

        // If any item is processing
        if ($allStatuses->contains('processing')) {
            $order->update(['status' => 'processing']);
            return;
        }

        // If any item is cancelled, check if all are cancelled
        if ($allStatuses->contains('cancelled')) {
            if ($items->where('status', '!=', 'cancelled')->isEmpty()) {
                $order->update(['status' => 'cancelled']);
            }
            return;
        }

        // Default to pending
        $order->update(['status' => 'pending']);
    }
}
