<?php

namespace App\Http\Controllers\KnowledgeSharing;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreKnowledgeBaseAnswerRequest;
use App\Http\Requests\UpdateKnowledgeBaseAnswerRequest;
use App\Models\KnowledgeBaseQuestion;
use App\Models\KnowledgeBaseAnswer;
use App\Services\KnowledgeBaseService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

/**
 * KnowledgeBaseAnswerController
 * 
 * Handles CRUD operations for knowledge base answers in the authenticated dashboard.
 * Contributors can submit and manage their own answers.
 * Managers can manage all answers and accept/reject them.
 * 
 * @package App\Http\Controllers\KnowledgeSharing
 */
class KnowledgeBaseAnswerController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected KnowledgeBaseService $knowledgeBaseService
    ) {}

    /**
     * Display a listing of answers.
     * Non-managers see only their own answers.
     * Managers see all answers.
     */
    public function index()
    {
        // Permission check
        abort_unless(auth()->user()->can('view knowledge base questions'), 403);

        // Build query
        $query = KnowledgeBaseAnswer::with(['user', 'question'])
            ->orderByDesc('created_at');

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

        // Apply filtering
        if (request()->filled('status')) {
            $query->where('is_published', request('status') === 'published');
        }

        if (request()->filled('accepted')) {
            $query->where('is_accepted', request('accepted') === 'yes');
        }

        $answers = $query->paginate(20);

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

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

        // Ensure question is published
        abort_if(!$question->is_published, 404);

        // Get existing published answers
        $existingAnswers = $question->publishedAnswers()->get();

        return view('knowledge-sharing.knowledge-base.answers.create', compact('question', 'existingAnswers'));
    }

    /**
     * Store a newly created answer in storage.
     */
    public function store(StoreKnowledgeBaseAnswerRequest $request, KnowledgeBaseQuestion $question): RedirectResponse
    {
        // Ensure question is published
        abort_if(!$question->is_published, 404);

        // createAnswer handles XSS sanitization, sort_order, and updateAnswerCount internally
        $answer = $this->knowledgeBaseService->createAnswer(
            $question,
            $request->validated(),
            auth()->user()
        );

        return redirect()
            ->route('knowledge-sharing.knowledge-base.show', $question)
            ->with('success', 'Answer submitted successfully! Thank you for contributing.');
    }

    /**
     * Display the specified answer.
     */
    public function show(KnowledgeBaseAnswer $answer): View
    {
        // Permission check
        abort_unless(auth()->user()->can('view knowledge base questions'), 403);

        // Check ownership or manager status
        abort_if($answer->user_id !== auth()->id() && !auth()->user()->hasAnyRole(['Manager', 'Super Manager']), 403);

        $question = $answer->question;

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

    /**
     * Show the form for editing the specified answer.
     */
    public function edit(KnowledgeBaseAnswer $answer): View
    {
        // Permission check - only owner, manager, or user with edit permission
        abort_if(
            $answer->user_id !== auth()->id() &&
            !auth()->user()->hasAnyRole(['Manager', 'Super Manager']) &&
            !auth()->user()->can('edit knowledge base answers'),
            403
        );

        $question = $answer->question;

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

    /**
     * Update the specified answer in storage.
     */
    public function update(UpdateKnowledgeBaseAnswerRequest $request, KnowledgeBaseAnswer $answer): RedirectResponse
    {
        // Update the answer
        $this->knowledgeBaseService->updateAnswer($answer, $request->validated());

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

    /**
     * Remove the specified answer from storage.
     */
    public function destroy(KnowledgeBaseAnswer $answer): RedirectResponse
    {
        // Permission check - only owner, manager, or user with delete permission
        abort_if(
            $answer->user_id !== auth()->id() &&
            !auth()->user()->hasAnyRole(['Manager', 'Super Manager']) &&
            !auth()->user()->can('delete knowledge base answers'),
            403
        );

        $questionId = $answer->question_id;
        $questionSlug = $answer->question->slug ?? null;

        // Delete answer
        $this->knowledgeBaseService->deleteAnswer($answer);

        // Redirect back to question
        if ($questionSlug) {
            return redirect()
                ->route('knowledge-sharing.knowledge-base.show', $questionSlug)
                ->with('success', 'Answer deleted successfully!');
        }

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

    /**
     * Accept an answer (mark as solution).
     * Only question owner or manager can accept answers.
     */
    public function accept(KnowledgeBaseAnswer $answer): RedirectResponse
    {
        $question = $answer->question;

        // Check authorization - only question owner or manager
        abort_if(
            $question->user_id !== auth()->id() && !auth()->user()->hasAnyRole(['Manager', 'Super Manager']),
            403
        );

        // Accept this answer and reject all others (pass current user)
        $this->knowledgeBaseService->acceptAnswer($answer, auth()->user());

        return redirect()
            ->route('knowledge-sharing.knowledge-base.show', $question)
            ->with('success', 'Answer marked as accepted solution!');
    }

    /**
     * Toggle helpful status for an answer.
     */
    public function toggleHelpful(KnowledgeBaseAnswer $answer): RedirectResponse
    {
        // Must be authenticated
        abort_unless(auth()->check(), 401);

        $alreadyMarked = DB::table('answer_helpful_votes')
            ->where('answer_id', $answer->id)
            ->where('user_id', auth()->id())
            ->exists();

        if ($alreadyMarked) {
            $this->knowledgeBaseService->markNotHelpful($answer, auth()->user());
            $message = 'Removed from helpful votes.';
        } else {
            $this->knowledgeBaseService->markHelpful($answer, auth()->user());
            $message = 'Marked as helpful!';
        }

        return redirect()
            ->route('knowledge-sharing.knowledge-base.show', $answer->question)
            ->with('success', $message);
    }
}
