<?php
 namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\ExpenseCategory; use App\Traits\LogsAdminActivity; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class ExpenseCategoryController extends Controller { use LogsAdminActivity; public function index() { return view('admin.expense-categories.index'); } public function records(Request $request): JsonResponse { $totalRecords = ExpenseCategory::count(); $query = ExpenseCategory::withCount('expenses'); if ($request->filled('search')) { $raw = $request->input('search'); $search = is_array($raw) ? ($raw['value'] ?? '') : (string) $raw; if ($search !== '') { $query->where('name', 'like', "%{$search}%"); } } $total = $query->count(); $start = (int) $request->input('start', 0); $length = (int) $request->input('length', 10); $categories = $query->orderBy('name')->skip($start)->take($length)->get(); $data = $categories->map(fn (ExpenseCategory $c) => [ 'id' => $c->id, 'name' => $c->name, 'icon' => $c->icon, 'is_active' => $c->is_active, 'expenses_count' => $c->expenses_count, ]); return response()->json([ 'draw' => $request->input('draw'), 'recordsTotal' => $totalRecords, 'recordsFiltered' => $total, 'data' => $data, ]); } public function store(Request $request): JsonResponse { $validated = $request->validate([ 'name' => ['required', 'string', 'max:255'], 'icon' => ['nullable', 'string', 'max:100'], 'is_active' => ['nullable', 'boolean'], ]); $category = ExpenseCategory::create([ 'name' => $validated['name'], 'icon' => $validated['icon'] ?? null, 'is_active' => $request->boolean('is_active', true), ]); $this->logCreated($category, "Created expense category #{$category->id}"); return response()->json([ 'success' => true, 'message' => __('admin/expenses.categories_messages_created'), ]); } public function update(Request $request, ExpenseCategory $expenseCategory): JsonResponse { $validated = $request->validate([ 'name' => ['required', 'string', 'max:255'], 'icon' => ['nullable', 'string', 'max:100'], 'is_active' => ['nullable', 'boolean'], ]); $expenseCategory->update([ 'name' => $validated['name'], 'icon' => $validated['icon'] ?? null, 'is_active' => $request->boolean('is_active', true), ]); $this->logUpdated($expenseCategory, "Updated expense category #{$expenseCategory->id}"); return response()->json([ 'success' => true, 'message' => __('admin/expenses.categories_messages_updated'), ]); } public function destroy(ExpenseCategory $expenseCategory): JsonResponse { if ($expenseCategory->expenses()->exists()) { return response()->json([ 'success' => false, 'message' => __('admin/expenses.categories_messages_in_use'), ], 422); } $this->logDeleted($expenseCategory, "Deleted expense category #{$expenseCategory->id}"); $expenseCategory->delete(); return response()->json([ 'success' => true, 'message' => __('admin/expenses.categories_messages_deleted'), ]); } } 