<?php

namespace App\Http\Controllers;

use App\Models\Inventory;
use App\Models\Product;
use App\Models\Warehouse;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class InventoryController extends Controller
{
    public function index(Request $request)
    {
        $query = Inventory::with(['product', 'warehouse']);

        if ($request->has('product_id')) {
            $query->where('product_id', $request->product_id);
        }

        if ($request->has('warehouse_id')) {
            $query->where('warehouse_id', $request->warehouse_id);
        }

        $inventories = $query->paginate(20);

        if ($request->wantsJson() || $request->is('api/*')) {
            return response()->json($inventories);
        }

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

    public function adjust(Request $request)
    {
        $products = Product::all();
        $warehouses = Warehouse::where('status', true)->get();
        return view('inventory.adjust', compact('products', 'warehouses'));
    }

    public function storeAdjustment(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'warehouse_id' => 'required|exists:warehouses,id',
            'quantity' => 'required|numeric',
            'type' => 'required|in:in,out,adjustment',
            'notes' => 'nullable|string',
        ]);

        try {
            DB::beginTransaction();

            $inventory = Inventory::firstOrNew([
                'product_id' => $request->product_id,
                'warehouse_id' => $request->warehouse_id,
            ]);

            $change = $request->quantity;
            if ($request->type == 'out' && $change > 0) {
                $change = -$change;
            }

            $inventory->quantity += $change;

            if ($inventory->quantity < 0) {
                throw new \Exception("Insufficient stock for this operation.");
            }

            $inventory->save();

            StockMovement::create([
                'product_id' => $request->product_id,
                'warehouse_id' => $request->warehouse_id,
                'type' => $request->type == 'adjustment' ? 'adjustment' : $request->type,
                'quantity' => abs($change),
                'user_id' => Auth::id() ?? 1, // Fallback for seeds/initial setup
                'notes' => $request->notes,
            ]);

            DB::commit();

            return redirect()->route('inventory.index')->with('success', 'Inventory adjustment successful.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }
    }

    public function movements()
    {
        $movements = StockMovement::with(['product', 'warehouse', 'user'])->latest()->paginate(20);
        return view('inventory.movements', compact('movements'));
    }
}
