<?php

namespace App\Http\Controllers;

use App\Models\Items;
use App\Models\TypeItems;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ItemsController extends Controller
{
    public function index()
    {
        $items = Items::with('typeItem')->get();

        return view('pages.back.items.index', compact('items'));
    }

    public function create()
    {
        $typeItems = TypeItems::all();

        return view('pages.back.items.create', compact('typeItems'));
    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'image_url' => 'nullable|url|max:255',
            'is_available' => 'boolean',
            'type_item_id' => 'required|exists:type_items,id',
        ];

        $validatedData = $request->validate($rules);

        Items::create($validatedData);

        return redirect()->route('items.index')->with('success', 'Item berhasil ditambahkan!');
    }

    public function show(Items $item)
    {
        $item->load('typeItem');

        return view('pages.back.items.show', compact('item'));
    }

    public function edit(Items $item)
    {
        $typeItems = TypeItems::all();

        return view('pages.back.items.edit', compact('item', 'typeItems'));
    }

    public function update(Request $request, Items $item)
    {
        $rules = [
            'name' => [
                'required',
                'string',
                'max:255',
                // Rule::unique('items')->ignore($item->id),
            ],
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'image_url' => 'nullable|url|max:255',
            'is_available' => 'boolean',
            'type_item_id' => 'required|exists:type_items,id',
        ];

        $validatedData = $request->validate($rules);

        $item->update($validatedData);

        return redirect()->route('items.index')->with('success', 'Item berhasil diperbarui!');
    }

    public function destroy(Items $item)
    {
        $item->delete();

        return redirect()->route('items.index')->with('success', 'Item berhasil dihapus!');
    }
}
