<?php

namespace App\Http\Controllers;

use App\Models\InventoryItem;
use App\Models\InventoryMovement;
use App\Models\Supplier;
use Illuminate\Http\Request;

class InventoryController extends Controller
{
    public function index()
    {
        $items = InventoryItem::where('farm_id', 1)
            ->with('supplier')
            ->orderBy('category')
            ->orderBy('item_name')
            ->get();

        $belowReorder = $items->filter->isBelowReorder();
        $totalValue = $items->sum->stock_value;
        $suppliers = Supplier::where('farm_id', 1)->orderBy('name')->get();

        return view('inventory.index', compact('items', 'belowReorder', 'totalValue', 'suppliers'));
    }

    public function create()
    {
        $suppliers = Supplier::where('farm_id', 1)->orderBy('name')->get();

        return view('inventory.create', compact('suppliers'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'item_name' => ['required', 'string', 'max:200'],
            'category' => ['required', 'in:feed,drug,chemical,equipment,other'],
            'unit' => ['required', 'in:kg,bag,litre,piece,sachet'],
            'reorder_threshold' => ['required', 'numeric', 'min:0'],
            'unit_cost_naira' => ['nullable', 'numeric', 'min:0'],
            'supplier_id' => ['nullable', 'exists:suppliers,id'],
            'notes' => ['nullable', 'string'],
        ]);

        InventoryItem::create(array_merge($validated, ['farm_id' => 1]));

        return redirect()->route('inventory.index')
            ->with('success', 'Inventory item created.');
    }

    public function receipt(Request $request, InventoryItem $item)
    {
        $request->validate([
            'quantity' => ['required', 'numeric', 'min:0.01'],
            'unit_cost_naira' => ['nullable', 'numeric', 'min:0'],
            'supplier_id' => ['nullable', 'exists:suppliers,id'],
            'notes' => ['nullable', 'string'],
        ]);

        $item->increment('current_stock', $request->quantity);
        if ($request->unit_cost_naira) {
            $item->update(['unit_cost_naira' => $request->unit_cost_naira]);
        }

        InventoryMovement::create([
            'item_id' => $item->id,
            'movement_type' => 'receipt',
            'quantity' => $request->quantity,
            'movement_date' => today(),
            'notes' => $request->notes,
            'logged_by' => auth()->id(),
            'supplier_id' => $request->supplier_id ?: null,
        ]);

        return back()->with('success', "Stock updated for {$item->item_name}.");
    }

    public function adjust(Request $request, InventoryItem $item)
    {
        $request->validate([
            'adjustment_quantity' => ['required', 'numeric', 'min:0.01'],
            'notes' => ['required', 'string'],
        ]);

        $qty = (float) $request->adjustment_quantity;

        if ($qty > $item->current_stock) {
            return back()->withErrors(['adjustment_quantity' => "Cannot remove {$qty} {$item->unit} — only {$item->current_stock} in stock."])->withInput();
        }

        $item->decrement('current_stock', $qty);

        InventoryMovement::create([
            'item_id' => $item->id,
            'movement_type' => 'adjustment',
            'quantity' => -$qty,
            'movement_date' => today(),
            'notes' => $request->notes,
            'logged_by' => auth()->id(),
        ]);

        return back()->with('success', "Removed {$qty} {$item->unit} from {$item->item_name}.");
    }

    public function show(InventoryItem $item)
    {
        $movements = $item->movements()
            ->with('logger', 'supplier')
            ->latest('movement_date')
            ->paginate(30);

        $suppliers = Supplier::where('farm_id', 1)->orderBy('name')->get();

        return view('inventory.show', compact('item', 'movements', 'suppliers'));
    }

    public function edit(InventoryItem $item)
    {
        $suppliers = Supplier::where('farm_id', 1)->orderBy('name')->get();

        return view('inventory.edit', compact('item', 'suppliers'));
    }

    public function update(Request $request, InventoryItem $item)
    {
        $validated = $request->validate([
            'item_name' => ['required', 'string', 'max:200'],
            'category' => ['required', 'in:feed,drug,chemical,equipment,other'],
            'unit' => ['required', 'in:kg,bag,litre,piece,sachet'],
            'reorder_threshold' => ['required', 'numeric', 'min:0'],
            'unit_cost_naira' => ['nullable', 'numeric', 'min:0'],
            'supplier_id' => ['nullable', 'exists:suppliers,id'],
            'notes' => ['nullable', 'string'],
        ]);

        $item->update($validated);

        return redirect()->route('inventory.show', $item)
            ->with('success', 'Item updated.');
    }

    public function destroy(InventoryItem $item)
    {
        $name = $item->item_name;
        $stockValue = $item->stock_value;
        $stock = $item->current_stock;
        $unit = $item->unit;

        $item->delete();

        $msg = "'{$name}' deleted (removed {$stock} {$unit} from stock";
        $msg .= $stockValue > 0
            ? ', stock value reduced by ₦'.number_format($stockValue, 2).').'
            : '). No unit cost was set, so stock value total is unchanged.';

        return redirect()->route('inventory.index')->with('success', $msg);
    }
}
