<?php

namespace App\Http\Controllers\KnowledgeSharing;

use App\Http\Controllers\Controller;
use App\Models\KnowledgeBaseCategory;
use App\Services\KnowledgeBaseService;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

/**
 * KnowledgeBaseCategoryController
 * 
 * Handles CRUD operations for knowledge base categories.
 * Only Managers and Super Managers can manage categories.
 * 
 * @package App\Http\Controllers\KnowledgeSharing
 */
class KnowledgeBaseCategoryController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected KnowledgeBaseService $knowledgeBaseService
    ) {}

    /**
     * Display a listing of categories.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request): View
    {
        // Permission check
        abort_unless(auth()->user()->can('manage knowledge base categories'), 403);

        $query = KnowledgeBaseCategory::with(['parent', 'children'])
            ->withCount(['questions', 'publishedQuestions']);

        // Apply filters
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        }

        if ($request->has('inactive')) {
            $query->where('is_active', false);
        } else {
            $query->where('is_active', true);
        }

        // Get root categories with children
        $categories = $query->root()
            ->with(['children' => function ($q) {
                $q->withCount(['questions', 'publishedQuestions'])->ordered();
            }])
            ->ordered()
            ->get();

        return view('knowledge-sharing.knowledge-base.categories.index', compact('categories'));
    }

    /**
     * Show the form for creating a new category.
     *
     * @return \Illuminate\View\View
     */
    public function create(): View
    {
        // Permission check
        abort_unless(auth()->user()->can('create knowledge base categories'), 403);

        $parentCategories = KnowledgeBaseCategory::active()
            ->root()
            ->orderBy('name')
            ->get();

        return view('knowledge-sharing.knowledge-base.categories.create', compact('parentCategories'));
    }

    /**
     * Store a newly created category.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('create knowledge base categories'), 403);

        // Validation
        $validated = $request->validate([
            'name' => 'required|string|max:191|unique:knowledge_base_categories,name',
            'slug' => 'nullable|string|max:191|unique:knowledge_base_categories,slug',
            'description' => 'nullable|string|max:1000',
            'parent_id' => 'nullable|exists:knowledge_base_categories,id',
            'icon' => 'nullable|string|max:50',
            'color' => 'nullable|string|max:20',
            'sort_order' => 'nullable|integer|min:0',
            'is_active' => 'nullable|boolean',
            'meta_title' => 'nullable|string|max:191',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:191',
        ], [
            'name.required' => 'Please enter a category name.',
            'name.unique' => 'A category with this name already exists.',
            'name.max' => 'The category name cannot exceed 191 characters.',
            'parent_id.exists' => 'The selected parent category is invalid.',
        ]);

        // Create category
        $category = $this->knowledgeBaseService->createCategory($validated);

        return redirect()
            ->route('knowledge-sharing.knowledge-base.categories.index')
            ->with('success', "Category '{$category->name}' created successfully!");
    }

    /**
     * Display the specified category.
     *
     * @param \App\Models\KnowledgeBaseCategory $category
     * @return \Illuminate\View\View
     */
    public function show(KnowledgeBaseCategory $category): View
    {
        // Permission check
        abort_unless(auth()->user()->can('view knowledge base categories'), 403);

        $category->load([
            'parent',
            'children',
            'questions' => function ($query) {
                $query->published()->latest()->limit(10);
            }
        ]);

        return view('knowledge-sharing.knowledge-base.categories.show', compact('category'));
    }

    /**
     * Show the form for editing the specified category.
     *
     * @param \App\Models\KnowledgeBaseCategory $category
     * @return \Illuminate\View\View
     */
    public function edit(KnowledgeBaseCategory $category): View
    {
        // Permission check
        abort_unless(auth()->user()->can('edit knowledge base categories'), 403);

        $parentCategories = KnowledgeBaseCategory::active()
            ->root()
            ->where('id', '!=', $category->id)
            ->orderBy('name')
            ->get();

        return view('knowledge-sharing.knowledge-base.categories.edit', compact('category', 'parentCategories'));
    }

    /**
     * Update the specified category.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\KnowledgeBaseCategory $category
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, KnowledgeBaseCategory $category): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('edit knowledge base categories'), 403);

        // Validation
        $validated = $request->validate([
            'name' => "required|string|max:191|unique:knowledge_base_categories,name,{$category->id}",
            'slug' => "nullable|string|max:191|unique:knowledge_base_categories,slug,{$category->id}",
            'description' => 'nullable|string|max:1000',
            'parent_id' => 'nullable|exists:knowledge_base_categories,id|not_in:' . $category->id,
            'icon' => 'nullable|string|max:50',
            'color' => 'nullable|string|max:20',
            'sort_order' => 'nullable|integer|min:0',
            'is_active' => 'nullable|boolean',
            'meta_title' => 'nullable|string|max:191',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:191',
        ], [
            'parent_id.not_in' => 'A category cannot be its own parent.',
        ]);

        // Update category
        $this->knowledgeBaseService->updateCategory($category, $validated);

        return redirect()
            ->route('knowledge-sharing.knowledge-base.categories.index')
            ->with('success', "Category '{$category->name}' updated successfully!");
    }

    /**
     * Remove the specified category.
     *
     * @param \App\Models\KnowledgeBaseCategory $category
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(KnowledgeBaseCategory $category): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('delete knowledge base categories'), 403);

        // Check if category has questions
        if ($category->questions()->exists()) {
            return redirect()
                ->back()
                ->with('error', "Cannot delete category '{$category->name}' because it contains questions. Please move or delete the questions first.");
        }

        // Check if category has children
        if ($category->children()->exists()) {
            return redirect()
                ->back()
                ->with('error', "Cannot delete category '{$category->name}' because it has sub-categories. Please delete or move the sub-categories first.");
        }

        $name = $category->name;
        $this->knowledgeBaseService->deleteCategory($category);

        return redirect()
            ->route('knowledge-sharing.knowledge-base.categories.index')
            ->with('success', "Category '{$name}' deleted successfully!");
    }

    /**
     * Toggle category active status.
     *
     * @param \App\Models\KnowledgeBaseCategory $category
     * @return \Illuminate\Http\RedirectResponse
     */
    public function toggleActive(KnowledgeBaseCategory $category): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('edit knowledge base categories'), 403);

        $category->update([
            'is_active' => !$category->is_active
        ]);

        $status = $category->is_active ? 'activated' : 'deactivated';

        return redirect()
            ->back()
            ->with('success', "Category '{$category->name}' has been {$status}.");
    }

    /**
     * Update sort order for categories.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateOrder(Request $request): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('edit knowledge base categories'), 403);

        $validated = $request->validate([
            'order' => 'required|array',
            'order.*.id' => 'required|exists:knowledge_base_categories,id',
            'order.*.sort_order' => 'required|integer|min:0',
        ]);

        foreach ($validated['order'] as $item) {
            KnowledgeBaseCategory::where('id', $item['id'])
                ->update(['sort_order' => $item['sort_order']]);
        }

        return redirect()
            ->back()
            ->with('success', 'Category order updated successfully!');
    }

    /**
     * Move questions from one category to another.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\KnowledgeBaseCategory $category
     * @return \Illuminate\Http\RedirectResponse
     */
    public function moveQuestions(Request $request, KnowledgeBaseCategory $category): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('edit knowledge base categories'), 403);

        $validated = $request->validate([
            'target_category_id' => 'required|exists:knowledge_base_categories,id|different:' . $category->id,
        ], [
            'target_category_id.different' => 'Please select a different category.',
        ]);

        $targetCategory = KnowledgeBaseCategory::find($validated['target_category_id']);

        // Move questions
        $count = $category->questions()->update(['category_id' => $targetCategory->id]);

        // Update counts
        $category->updateQuestionsCount();
        $targetCategory->updateQuestionsCount();

        return redirect()
            ->back()
            ->with('success', "{$count} questions moved to '{$targetCategory->name}' successfully!");
    }
}
