<?php

namespace App\Http\Controllers;

use App\Models\CrmItemUnit;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;

class CrmItemUnitController extends Controller
{
    public function index()
    {
        $data = [
            'items' => CrmItemUnit::all(),
        ];
        return view('crm.item_unit.index', $data);
    }

    public function create()
    {
        return view('crm.item_unit.create');
    }

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

        $item = new CrmItemUnit();
        $item->name = $request->name;
        $item->save();
        Toastr::success('Item unit created successfully', 'Success');
        return redirect()->back();
    }

    public function edit($id)
    {
        $item = CrmItemUnit::find($id);
        return view('crm.item_unit.edit', compact('item'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|unique:crm_item_units,name,' . $id,
        ]);

        $item = CrmItemUnit::find($id);
        $item->name = $request->name;
        $item->save();
        Toastr::success('Item unit created successfully', 'Success');

        return redirect()->back();
    }
}
