<?php

namespace App\Http\Controllers;

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

class TypeController extends Controller
{
    public function index()
    {
        $types = Type::with('category')->get();
        return response()->json($types);
    }

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

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

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

        $type = Type::create([
            'category_id' => $request->category_id,
            'name' => $request->name,
            'slug' => $slug,
            'is_active' => $request->has('is_active'),
        ]);

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

    public function edit(Type $type)
    {
        return response()->json($type);
    }

    public function update(Request $request, Type $type)
    {
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'name' => 'required|string|max:255',
            'is_active' => 'boolean',
        ]);

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

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

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

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

    public function apiIndex()
    {
        $types = Type::with('category')->where('is_active', true)->get();
        return response()->json($types);
    }

    public function apiByCategoryId($categoryId)
    {
        $types = Type::where('category_id', $categoryId)->where('is_active', true)->get();
        return response()->json($types);
    }
}
