<?php

namespace App\Http\Controllers\KnowledgeSharing;

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

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

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

        $query = KnowledgeBaseQuestion::with(['user', 'category'])
            ->withCount('publishedAnswers');

        // Non-managers can only see their own questions
        if (!auth()->user()->hasAnyRole(['Super Manager', 'Manager'])) {
            $query->where('user_id', auth()->id());
        }

        // Apply filters
        if ($request->filled('search')) {
            $query->search($request->get('search'));
        }

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->get('category_id'));
        }

        if ($request->filled('status')) {
            $query->where('status', $request->get('status'));
        }

        if ($request->filled('difficulty')) {
            $query->where('difficulty', $request->get('difficulty'));
        }

        // Apply sorting
        $sort = $request->get('sort', 'latest');
        switch ($sort) {
            case 'popular':
                $query->popular();
                break;
            case 'helpful':
                $query->orderByDesc('helpful_count');
                break;
            default:
                $query->latest();
        }

        $questions = $query->paginate(15);
        $categories = KnowledgeBaseCategory::active()->orderBy('name')->get();
        $statistics = $this->knowledgeBaseService->getStatistics();

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

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

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

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

    /**
     * Store a newly created question.
     *
     * @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 questions'), 403);

        // Validation
        $validated = $request->validate([
            'title' => 'required|string|max:191|min:5',
            'content' => 'required|string|min:20',
            'category_id' => 'required|exists:knowledge_base_categories,id',
            'difficulty' => 'nullable|in:beginner,intermediate,advanced',
            'tags' => 'nullable|string|max:500',
            'status' => 'nullable|in:draft,published,pending_review',
            'is_featured' => 'nullable|boolean',
            'meta_title' => 'nullable|string|max:191',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:191',
        ], [
            'title.required' => 'Please enter a question title.',
            'title.min' => 'The title must be at least 5 characters.',
            'title.max' => 'The title cannot exceed 191 characters.',
            'content.required' => 'Please enter the question content.',
            'content.min' => 'The content must be at least 20 characters.',
            'category_id.required' => 'Please select a category.',
            'category_id.exists' => 'The selected category is invalid.',
        ]);

        // Create question
        $question = $this->knowledgeBaseService->createQuestion($validated, auth()->user());

        return redirect()
            ->route('knowledge-sharing.knowledge-base.show', $question)
            ->with('success', 'Question created successfully!');
    }

    /**
     * Display the specified question.
     *
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\View\View
     */
    public function show(KnowledgeBaseQuestion $question): View
    {
        // Permission check
        abort_unless(
            $question->user_id === auth()->id() || 
            auth()->user()->can('view knowledge base questions'),
            403
        );

        $question->load(['user', 'category', 'answers.user']);

        return view('knowledge-sharing.knowledge-base.questions.show', compact('question'));
    }

    /**
     * Show the form for editing the specified question.
     *
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\View\View
     */
    public function edit(KnowledgeBaseQuestion $question): View
    {
        // Permission check
        abort_unless(
            $question->user_id === auth()->id() || 
            auth()->user()->can('edit knowledge base questions'),
            403
        );

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

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

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

        // Validation
        $validated = $request->validate([
            'title' => 'required|string|max:191|min:5',
            'content' => 'required|string|min:20',
            'category_id' => 'required|exists:knowledge_base_categories,id',
            'difficulty' => 'nullable|in:beginner,intermediate,advanced',
            'tags' => 'nullable|string|max:500',
            'status' => 'nullable|in:draft,published,archived,pending_review',
            'is_featured' => 'nullable|boolean',
            'meta_title' => 'nullable|string|max:191',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:191',
        ]);

        // Update question
        $this->knowledgeBaseService->updateQuestion($question, $validated);

        return redirect()
            ->route('knowledge-sharing.knowledge-base.show', $question)
            ->with('success', 'Question updated successfully!');
    }

    /**
     * Remove the specified question.
     *
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(KnowledgeBaseQuestion $question): RedirectResponse
    {
        // Permission check
        abort_unless(
            $question->user_id === auth()->id() || 
            auth()->user()->can('delete knowledge base questions'),
            403
        );

        $this->knowledgeBaseService->deleteQuestion($question);

        return redirect()
            ->route('knowledge-sharing.knowledge-base.index')
            ->with('success', 'Question deleted successfully!');
    }

    /**
     * Publish a question.
     *
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\Http\RedirectResponse
     */
    public function publish(KnowledgeBaseQuestion $question): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('publish knowledge base questions'), 403);

        $this->knowledgeBaseService->publishQuestion($question);

        return redirect()
            ->back()
            ->with('success', 'Question published successfully!');
    }

    /**
     * Archive a question.
     *
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\Http\RedirectResponse
     */
    public function archive(KnowledgeBaseQuestion $question): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('archive knowledge base questions'), 403);

        $this->knowledgeBaseService->archiveQuestion($question);

        return redirect()
            ->back()
            ->with('success', 'Question archived successfully!');
    }

    /**
     * Toggle featured status.
     *
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\Http\RedirectResponse
     */
    public function toggleFeatured(KnowledgeBaseQuestion $question): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('feature knowledge base questions'), 403);

        $isFeatured = $this->knowledgeBaseService->toggleFeatured($question);

        return redirect()
            ->back()
            ->with('success', $isFeatured 
                ? 'Question marked as featured.' 
                : 'Question removed from featured.');
    }
}
