<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;

use App\Models\Category;
use App\Models\StockItem;
use Illuminate\Http\Request;

class StockItemsController extends Controller
{
    public function index()
    {
        $categories = Category::all();
        $stockItems = StockItem::with('category')->get();
        return view('admin.master.stockitems', compact('categories', 'stockItems'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'item_name'   => 'required|string',
            'uom'         => 'nullable|string',
            'sgst'        => 'nullable|numeric',
            'cgst'        => 'nullable|numeric',
            'igst'        => 'nullable|numeric',
        ]);

        StockItem::create($request->all());
        return redirect()->back()->with('success', 'Item added successfully!');
    }

    public function update(Request $request, $id)
    {
        $item = StockItem::findOrFail($id);
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'item_name'   => 'required|string',
            'uom'         => 'nullable|string',
            'sgst'        => 'nullable|numeric',
            'cgst'        => 'nullable|numeric',
            'igst'        => 'nullable|numeric',
        ]);
        $item->update($request->all());
        return redirect()->back()->with('success', 'Item updated successfully!');
    }

    public function destroy($id)
    {
        $item = StockItem::findOrFail($id);
        $item->delete();
        return redirect()->back()->with('success', 'Item deleted successfully!');
    }

    public function storeCategory(Request $request)
    {
        $request->validate([
            'name' => 'required|unique:categories,name',
        ]);

        Category::create(['name' => $request->name]);
        return redirect()->back()->with('success', 'Category added successfully!');
    }

    public function importExcel(Request $request)
    {
        // Handle Excel import logic here
    }
}
