<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TopicCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class ForumCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $search = $request->input('search');
        $perPage = $request->input('per_page', 10);

        $categories = TopicCategory::withCount('topics')
            ->when($search, function ($query, $search) {
                return $query->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            })
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate($perPage);

        return Inertia::render('admin/forum/categories/Index', [
            'categories' => $categories,
            'filters' => [
                'search' => $search,
                'per_page' => $perPage,
            ],
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('admin/forum/categories/Create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:topic_categories',
            'slug' => 'nullable|string|max:255|unique:topic_categories',
            'description' => 'nullable|string',
            'color' => 'required|string|size:7|regex:/^#[0-9A-Fa-f]{6}$/',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'boolean',
        ]);

        // Generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        TopicCategory::create($validated);

        return redirect()->route('admin.forum.categories.index')
            ->with('success', 'Category created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(TopicCategory $category)
    {
        $category->loadCount('topics');
        $topics = $category->topics()
            ->with(['user', 'tags'])
            ->latest()
            ->paginate(10);

        return Inertia::render('admin/forum/categories/Show', [
            'category' => $category,
            'topics' => $topics,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(TopicCategory $category)
    {
        return Inertia::render('admin/forum/categories/Edit', [
            'category' => $category,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, TopicCategory $category)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:topic_categories,name,' . $category->id,
            'slug' => 'nullable|string|max:255|unique:topic_categories,slug,' . $category->id,
            'description' => 'nullable|string',
            'color' => 'required|string|size:7|regex:/^#[0-9A-Fa-f]{6}$/',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'boolean',
        ]);

        // Generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        $category->update($validated);

        return redirect()->route('admin.forum.categories.index')
            ->with('success', 'Category updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(TopicCategory $category)
    {
        // Check if category has topics
        if ($category->topics()->exists()) {
            return back()->withErrors(['delete' => 'Cannot delete category with existing topics.']);
        }

        $category->delete();

        return redirect()->route('admin.forum.categories.index')
            ->with('success', 'Category deleted successfully.');
    }

    /**
     * Restore the specified resource.
     */
    public function restore($id)
    {
        $category = TopicCategory::withTrashed()->findOrFail($id);
        $category->restore();

        return redirect()->route('admin.forum.categories.index')
            ->with('success', 'Category restored successfully.');
    }

    /**
     * Permanently delete the specified resource.
     */
    public function forceDelete($id)
    {
        $category = TopicCategory::withTrashed()->findOrFail($id);
        $category->forceDelete();

        return redirect()->route('admin.forum.categories.index')
            ->with('success', 'Category permanently deleted.');
    }
}