<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class CategoryController extends Controller
{
    public function index()
    {
        return Inertia::render('Category/Index', [
            'categories' => Category::where('user_id', Auth::user()->id)->get(),
        ]);
    }

    public function create()
    {
        return Inertia::render('Category/Create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|min:1|max:255',
        ]);

        Category::create([
            'name' => $request->name,
            'user_id' => Auth::user()->id,
        ]);

        return to_route('category.index')->with('success', 'Category Added successfully.');
    }

    public function edit(Category $category)
    {
        return Inertia::render('Category/Edit', [
            'category' => $category
        ]);
    }

    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name' => 'required|string|min:3|max:255',
        ]);

        $category->update([
            'name' => $request->name,
            'user_id' => Auth::user()->id,
        ]);

        return to_route('category.index')->with('success', 'Category updated successfully.');
    }

    public function destroy(Category $category)
    {
        $category->delete();
        return to_route('category.index')->with('success', 'Category deleted successfully.');
    }
}
