<?php

namespace App\Http\Controllers;

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

class CrmItemController extends Controller
{
    public function index()
    {
        $data = [
            'items' => CrmItem::all(),
        ];
        // dd($data);
        return view('crm.item.index', $data);

    }

    public function create()
    {
        $data = [
            'units' => CrmItemUnit::all(),
        ];
        return view('crm.item.create', $data);
    }

    public function store(Request $request)
    {
        // dd($request->all());
        $request->validate([
            'name' => 'required|unique:crm_items,name',
            'crm_item_unit_id' => 'required',
        ]);

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

    public function edit($id)
    {
        $item = CrmItem::find($id);
        $data = [
            'item' => $item,
            'units' => CrmItemUnit::all(),
        ];
        return view('crm.item.edit', $data);
    }

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

        $item = CrmItem::find($id);
        $item->name = $request->name;
        $item->crm_item_unit_id = $request->crm_item_unit_id;
        $item->save();

        Toastr::success('Item created successfully', 'Success');

        return redirect()->back();
    }

}
