Files
Kol-Manager/app/Http/Controllers/ClientCategoryController.php

96 lines
3.0 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\ClientCategory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class ClientCategoryController extends Controller
{
public function index(): \Illuminate\View\View
{
$categories = ClientCategory::with('children', 'parent')
->withCount('clients')
->orderBy('sort_order')
->get();
$parents = ClientCategory::whereNull('parent_id')
->orderBy('sort_order')
->get();
return view('categories.index', compact('categories', 'parents'));
}
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'name' => 'required|string|max:100',
'parent_id' => 'nullable|exists:client_categories,id',
'icon' => 'nullable|string|max:10',
'color' => 'nullable|string|max:20',
]);
// Auto slug
$validated['slug'] = \Illuminate\Support\Str::slug($validated['name']);
// If slug conflicts, suffix with random
if (ClientCategory::where('slug', $validated['slug'])->exists()) {
$validated['slug'] .= '-' . substr(uniqid(), -4);
}
ClientCategory::create($validated);
return back()->with('success', '🏷️ Category added!');
}
public function quickStore(Request $request): \Illuminate\Http\JsonResponse
{
$validated = $request->validate([
'name' => 'required|string|max:100',
]);
$validated['slug'] = \Illuminate\Support\Str::slug($validated['name']);
if (ClientCategory::where('slug', $validated['slug'])->exists()) {
$validated['slug'] .= '-' . substr(uniqid(), -4);
}
$category = ClientCategory::create($validated);
return response()->json(['id' => $category->id, 'name' => $category->name, 'icon' => '🏷️']);
}
public function update(Request $request, ClientCategory $category): RedirectResponse
{
$validated = $request->validate([
'name' => 'required|string|max:100',
'parent_id' => 'nullable|exists:client_categories,id',
'icon' => 'nullable|string|max:10',
'color' => 'nullable|string|max:20',
]);
// Prevent a category from being its own parent
if (isset($validated['parent_id']) && $validated['parent_id'] == $category->id) {
$validated['parent_id'] = null;
}
$category->update($validated);
return back()->with('success', '🏷️ Category updated!');
}
public function destroy(ClientCategory $category): RedirectResponse
{
// Reassign children to the parent
$category->children()->update(['parent_id' => $category->parent_id]);
// Detach clients
$category->clients()->update(['category_id' => null]);
$category->delete();
return back()->with('success', '🏷️ Category removed.');
}
}