<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProductVariant;
use App\Services\Admin\InventoryService;
use Illuminate\Http\Request;

class InventoryController extends Controller
{
    public function __construct(
        protected InventoryService $inventoryService
    ) {}

    public function index(Request $request)
    {
        $query = ProductVariant::with('product');

        if ($request->has('low_stock')) {
            $query->whereColumn('stock_quantity', '<=', 'min_stock_level');
        }

        if ($request->has('search')) {
            $query->whereHas('product', function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%');
            });
        }

        $variants = $query->orderBy('stock_quantity')->paginate(20);

        return view('admin.inventory.index', compact('variants'));
    }

    public function updateStock(Request $request, ProductVariant $variant)
    {
        $validated = $request->validate([
            'quantity' => ['required', 'integer', 'min:0'],
            'type' => ['required', 'in:adjustment,in,out'],
            'notes' => ['nullable', 'string', 'max:500'],
        ]);

        $this->inventoryService->updateStock(
            $variant->id,
            $validated['quantity'],
            $validated['type'],
            $validated['notes'] ?? null,
            auth()->id()
        );

        return redirect()->route('admin.inventory.index')
            ->with('success', 'Stock updated successfully.');
    }

    public function history(ProductVariant $variant)
    {
        $history = $this->inventoryService->getStockHistory($variant->id, 50);

        return view('admin.inventory.history', compact('variant', 'history'));
    }
}
