<?php

namespace App\Http\Controllers;

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

class CategoryController extends Controller
{
    // Show form + table
    public function index()
    {
        $categories = Category::orderBy('idCategory')->get();

        return view('categories', [
            'categories' => $categories,
        ]);
    }

    // Save new category
    public function store(Request $request)
    {
        $request->validate([
            'nameCategory' => 'required|string|max:255',
        ]);

        Category::create([
            'nameCategory' => $request->nameCategory,
        ]);

        return redirect()
            ->route('categories.index')
            ->with('success', 'Category added.');
    }

    // Show edit form
    public function edit(Category $category)
    {
        return view('categories_edit', [
            'category' => $category,
        ]);
    }

    // Update existing category
    public function update(Request $request, Category $category)
    {
        $request->validate([
            'nameCategory' => 'required|string|max:255',
        ]);

        $category->update([
            'nameCategory' => $request->nameCategory,
        ]);

        return redirect()
            ->route('categories.index')
            ->with('success', 'Category updated.');
    }

    // Delete a category
    public function destroy(Category $category)
    {
        $category->delete();

        return redirect()
            ->route('categories.index')
            ->with('success', 'Category deleted.');
    }
}
