<?php

namespace App\Http\Controllers\KnowledgeSharing;

use App\Http\Controllers\Controller;
use App\Models\DiscussionTopic;
use App\Services\DiscussionService;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

/**
 * DiscussionTopicController
 * 
 * Handles CRUD operations for discussion topics.
 * Only Managers and Super Managers can manage topics.
 * 
 * @package App\Http\Controllers\KnowledgeSharing
 */
class DiscussionTopicController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected DiscussionService $discussionService
    ) {}

    /**
     * Display a listing of topics.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request): View
    {
        // Permission check - view permission required (manage permission for create/edit/delete)
        abort_unless(auth()->user()->can('view discussion topics'), 403);

        $query = DiscussionTopic::withCount(['discussions', 'activeDiscussions']);

        // 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);
        }

        $topics = $query->ordered()->paginate(20);

        return view('knowledge-sharing.discussions.topics.index', compact('topics'));
    }

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

        return view('knowledge-sharing.discussions.topics.create');
    }

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

        // Validation
        $validated = $request->validate([
            'name' => 'required|string|max:191|unique:discussion_topics,name',
            'slug' => 'nullable|string|max:191|unique:discussion_topics,slug',
            'description' => 'nullable|string|max:1000',
            '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 topic name.',
            'name.unique' => 'A topic with this name already exists.',
            'name.max' => 'The topic name cannot exceed 191 characters.',
            'description.max' => 'The description cannot exceed 1000 characters.',
        ]);

        // Create topic
        $topic = $this->discussionService->createTopic($validated);

        return redirect()
            ->route('knowledge-sharing.discussions.topics.index')
            ->with('success', "Topic '{$topic->name}' created successfully!");
    }

    /**
     * Display the specified topic.
     *
     * @param \App\Models\DiscussionTopic $topic
     * @return \Illuminate\View\View
     */
    public function show(DiscussionTopic $topic): View
    {
        // Permission check
        abort_unless(auth()->user()->can('view discussion topics'), 403);

        $topic->load(['discussions' => function ($query) {
            $query->published()->latest()->limit(10);
        }]);

        return view('knowledge-sharing.discussions.topics.show', compact('topic'));
    }

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

        return view('knowledge-sharing.discussions.topics.edit', compact('topic'));
    }

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

        // Validation
        $validated = $request->validate([
            'name' => "required|string|max:191|unique:discussion_topics,name,{$topic->id}",
            'slug' => "nullable|string|max:191|unique:discussion_topics,slug,{$topic->id}",
            'description' => 'nullable|string|max:1000',
            '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',
        ]);

        // Update topic
        $this->discussionService->updateTopic($topic, $validated);

        return redirect()
            ->route('knowledge-sharing.discussions.topics.index')
            ->with('success', "Topic '{$topic->name}' updated successfully!");
    }

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

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

        $name = $topic->name;
        $this->discussionService->deleteTopic($topic);

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

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

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

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

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

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

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

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

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