<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CategoryController extends Controller
{
    public function index() { return response()->json(['success'=>true,'data'=>Category::withCount('products')->orderBy('sort_order')->get()]); }
    public function store(Request $request)
    {
        $data = $request->validate(['name'=>'required','parent_id'=>'nullable|exists:categories,id','icon'=>'nullable','is_active'=>'boolean']);
        $data['slug'] = Str::slug($data['name']);
        return response()->json(['success'=>true,'data'=>Category::create($data)],201);
    }
    public function update(Request $request, int $id)
    {
        $cat = Category::findOrFail($id);
        $cat->update($request->validate(['name'=>'string','is_active'=>'boolean','sort_order'=>'integer']));
        return response()->json(['success'=>true,'data'=>$cat]);
    }
    public function destroy(int $id) { Category::findOrFail($id)->delete(); return response()->json(['success'=>true]); }
}
