<?php

namespace App\Http\Controllers;

use App\Models\Item;
use App\Models\ItemCategory;
use Illuminate\Http\Request;

class ItemController extends Controller
{
    public function index()
    {
        $items = Item::latest()->paginate(20);
        $categories = ItemCategory::orderBy('name')->get();
        return view('items.index', compact('items', 'categories'));
    }

    public function create()
    {
        $categories = ItemCategory::orderBy('name')->get();
        return view('items.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'        => 'required|string|max:255',
            'category'    => 'required|string|max:100',
            'unit'        => 'required|string|max:50',
            'quantity'    => 'required|numeric|min:0',
            'unit_price'  => 'required|numeric|min:0',
            'description' => 'nullable|string|max:1000',
        ]);

        Item::create($validated);

        return redirect()->route('items.index')->with('success', 'Item added successfully.');
    }

    public function edit(Item $item)
    {
        $categories = ItemCategory::orderBy('name')->get();
        return view('items.edit', compact('item', 'categories'));
    }

    public function update(Request $request, Item $item)
    {
        $validated = $request->validate([
            'name'        => 'required|string|max:255',
            'category'    => 'required|string|max:100',
            'unit'        => 'required|string|max:50',
            'quantity'    => 'required|numeric|min:0',
            'unit_price'  => 'required|numeric|min:0',
            'description' => 'nullable|string|max:1000',
        ]);

        $item->update($validated);

        return redirect()->route('items.index')->with('success', 'Item updated successfully.');
    }

    public function destroy(Item $item)
    {
        $item->delete();
        return back()->with('success', 'Item deleted.');
    }

    // Category management
    public function categories()
    {
        $categories = ItemCategory::withCount('items')->orderBy('name')->get();
        return view('items.categories', compact('categories'));
    }

    public function storeCategory(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:100|unique:item_categories,name',
            'icon' => 'nullable|string|max:50',
        ]);

        ItemCategory::create([
            'name' => $request->name,
            'icon' => $request->icon ?: 'bi-tag',
        ]);

        return back()->with('success', 'Category added.');
    }

    public function destroyCategory(ItemCategory $itemCategory)
    {
        if ($itemCategory->items()->count() > 0) {
            return back()->with('error', 'Cannot delete — category has items assigned.');
        }
        $itemCategory->delete();
        return back()->with('success', 'Category deleted.');
    }
}
