<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::withCount(['subcategories', 'ads'])
            ->with(['subcategories' => function($query) {
                $query->withCount('ads');
            }])
            ->orderBy('sort_order')
            ->get();

        $totalCategories = Category::count();
        $totalSubcategories = \App\Models\Subcategory::count();
        $activeCategories = Category::where('is_active', true)->count();
        $inactiveCategories = Category::where('is_active', false)->count();
            
        return view('admin.categories.index', compact('categories', 'totalCategories', 'totalSubcategories', 'activeCategories', 'inactiveCategories'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'icon' => 'nullable|string',
            'description' => 'nullable|string',
            'status' => 'required|in:active,inactive',
            'order' => 'integer'
        ]);

        $category = Category::create([
            'name' => $request->name,
            'slug' => str()->slug($request->name),
            'icon' => $request->icon ?? '📁',
            'description' => $request->description,
            'is_active' => $request->status === 'active',
            'sort_order' => $request->order,
        ]);

        return response()->json(['message' => 'Category created successfully', 'category' => $category]);
    }

    // Additional methods (update, destroy) can be implemented similarly or relying on existing JS logic calling generic endpoints, 
    // but for now index is key for Custom Fields work. 
    // I'll implement basic CRUD placeholders if needed by the View's JS, 
    // but the View currently mocks it. The user task is Custom Fields, so I focus on that.
    // However, to make the "Edit" buttons work on real data, I should probably support basic updates.
    
    public function update(Request $request, Category $category)
    {
         $request->validate([
            'name' => 'required|string|max:255',
            'status' => 'required|in:active,inactive',
        ]);

        $category->update([
            'name' => $request->name,
            'slug' => str()->slug($request->name),
            'icon' => $request->icon,
            'description' => $request->description,
            'is_active' => $request->status === 'active',
            'sort_order' => $request->order,
        ]);

        return response()->json(['message' => 'Category updated successfully']);
    }

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