<?php

namespace App\Http\Controllers;

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

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::all();
        return response()->json($categories);
    }

    public function create()
    {
        return response()->json(['message' => 'Not implemented in API'], 404);
    }

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

        $slug = Str::slug($request->name);
        if (empty($slug)) {
            $slug = uniqid('cat_');
        }

        $category = Category::create([
            'name' => $request->name,
            'slug' => $slug,
            'is_active' => $request->has('is_active'),
        ]);

        return response()->json($category, 201);
    }

    public function edit(Category $category)
    {
        return response()->json($category);
    }

    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:categories,name,' . $category->id,
            'is_active' => 'boolean',
        ]);

        $slug = Str::slug($request->name);
        if (empty($slug)) {
            $slug = uniqid('cat_');
        }

        $category->update([
            'name' => $request->name,
            'slug' => $slug,
            'is_active' => $request->has('is_active'),
        ]);

        return response()->json($category);
    }

    public function destroy(Category $category)
    {
        $category->delete();
        return response()->json(['message' => 'Category deleted successfully']);
    }

    public function apiIndex()
    {
        $categories = Category::where('is_active', true)->get();
        return response()->json($categories);
    }
}
