<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\KnowledgeBaseCategory;
use App\Models\KnowledgeBaseQuestion;
use App\Services\KnowledgeBaseService;
use App\Services\SEOService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

/**
 * PublicKnowledgeBaseController
 * 
 * Handles public-facing knowledge base pages.
 * Displays questions, categories, and handles search/filtering.
 * 
 * @package App\Http\Controllers\Public
 */
class PublicKnowledgeBaseController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected KnowledgeBaseService $knowledgeBaseService,
        protected SEOService $seoService
    ) {}

    /**
     * Display the knowledge base landing page.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request): View
    {
        // Get filters from request
        $filters = [
            'category_id' => $request->get('category'),
            'category_slug' => $request->get('category_slug'),
            'difficulty' => $request->get('difficulty'),
            'tag' => $request->get('tag'),
            'search' => $request->get('q'),
            'sort' => $request->get('sort', 'recent'),
        ];

        // Get questions with pagination
        $questions = $this->knowledgeBaseService->getPublicQuestions($filters, 15);

        // Get categories for sidebar
        $categories = $this->knowledgeBaseService->getActiveCategories();

        // Get featured questions
        $featuredQuestions = $this->knowledgeBaseService->getFeaturedQuestions(5);

        // Get popular questions
        $popularQuestions = $this->knowledgeBaseService->getPopularQuestions(5);

        // Get popular tags
        $tags = $this->knowledgeBaseService->getTagsWithCount();

        // Get statistics
        $statistics = $this->knowledgeBaseService->getStatistics();

        // Generate SEO metadata
        $seoMetadata = $this->seoService->generateLandingPageMetadata('knowledge-base');

        return view('public.knowledge-base.index', compact(
            'questions',
            'categories',
            'featuredQuestions',
            'popularQuestions',
            'tags',
            'statistics',
            'seoMetadata',
            'filters'
        ));
    }

    /**
     * Display questions by category.
     *
     * @param \Illuminate\Http\Request $request
     * @param string $slug
     * @return \Illuminate\View\View
     */
    public function category(Request $request, string $slug): View
    {
        // Get the category
        $category = $this->knowledgeBaseService->getCategoryBySlug($slug);

        // Get filters
        $filters = [
            'category_id' => $category->id,
            'difficulty' => $request->get('difficulty'),
            'tag' => $request->get('tag'),
            'search' => $request->get('q'),
            'sort' => $request->get('sort', 'recent'),
        ];

        // Get questions
        $questions = $this->knowledgeBaseService->getPublicQuestions($filters, 15);

        // Get all categories for sidebar
        $categories = $this->knowledgeBaseService->getActiveCategories();

        // Get tags for this category
        $tags = $this->knowledgeBaseService->getTagsWithCount();

        // Generate SEO metadata
        $seoMetadata = $this->seoService->generateCategoryMetadata($category);

        // Generate breadcrumb schema
        $breadcrumbSchema = $this->seoService->generateBreadcrumbSchema([
            ['name' => 'Home', 'url' => url('/')],
            ['name' => 'Knowledge Base', 'url' => route('public.knowledge-base.index')],
            ['name' => $category->name],
        ]);

        return view('public.knowledge-base.category', compact(
            'category',
            'questions',
            'categories',
            'tags',
            'seoMetadata',
            'breadcrumbSchema'
        ));
    }

    /**
     * Display a single question.
     *
     * @param string $slug
     * @return \Illuminate\View\View
     */
    public function show(string $slug): View
    {
        // Get the question
        $question = $this->knowledgeBaseService->getQuestionBySlug($slug);

        // Increment view count
        $this->knowledgeBaseService->incrementViewCount($question);

        // Get answers
        $answers = $question->publishedAnswers()->with('user')->get();

        // Get related questions
        $relatedQuestions = KnowledgeBaseQuestion::published()
            ->where('id', '!=', $question->id)
            ->where('category_id', $question->category_id)
            ->latest()
            ->limit(5)
            ->get();

        // Get categories for sidebar
        $categories = $this->knowledgeBaseService->getActiveCategories();

        // Generate SEO metadata
        $seoMetadata = $this->seoService->generateQuestionMetadata($question);

        // Generate structured data
        $schemaData = $this->seoService->generateQuestionSchema($question);

        // Generate breadcrumb schema
        $breadcrumbSchema = $this->seoService->generateBreadcrumbSchema([
            ['name' => 'Home', 'url' => url('/')],
            ['name' => 'Knowledge Base', 'url' => route('public.knowledge-base.index')],
            ['name' => $question->category->name ?? 'General', 'url' => $question->category?->url],
            ['name' => $question->title],
        ]);

        return view('public.knowledge-base.show', compact(
            'question',
            'answers',
            'relatedQuestions',
            'categories',
            'seoMetadata',
            'schemaData',
            'breadcrumbSchema'
        ));
    }

    /**
     * Search knowledge base.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function search(Request $request): View
    {
        $query = $request->get('q', '');

        $filters = [
            'search' => $query,
            'category_id' => $request->get('category'),
            'difficulty' => $request->get('difficulty'),
            'tag' => $request->get('tag'),
            'sort' => $request->get('sort', 'relevance'),
        ];

        $questions = $this->knowledgeBaseService->getPublicQuestions($filters, 15);
        $categories = $this->knowledgeBaseService->getActiveCategories();
        $tags = $this->knowledgeBaseService->getTagsWithCount();

        return view('public.knowledge-base.search', compact(
            'questions',
            'categories',
            'tags',
            'query'
        ));
    }

    /**
     * AJAX real-time search for the knowledge base dropdown.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxSearch(Request $request): JsonResponse
    {
        $query = trim($request->get('q', ''));

        if (strlen($query) < 2) {
            return response()->json(['results' => []]);
        }

        $qb = \App\Models\KnowledgeBaseQuestion::query()
            ->with('category')
            ->published()
            ->where(function ($q) use ($query) {
                $q->where('title', 'like', "%{$query}%")
                  ->orWhere('excerpt', 'like', "%{$query}%")
                  ->orWhere('content', 'like', "%{$query}%");
            });

        // Optional category filter
        if ($request->filled('category_id')) {
            $qb->where('category_id', $request->integer('category_id'));
        }

        $questions = $qb->limit(8)->get();

        $results = $questions->map(fn ($q) => [
            'title'    => $q->title,
            'category' => $q->category?->name ?? 'General',
            'excerpt'  => Str::limit(strip_tags($q->excerpt ?? $q->content), 100),
            'url'      => route('public.knowledge-base.show', $q->slug),
        ]);

        return response()->json(['results' => $results]);
    }

    /**
     * Display questions by tag.
     *
     * @param \Illuminate\Http\Request $request
     * @param string $tag
     * @return \Illuminate\View\View
     */
    public function tag(Request $request, string $tag): View
    {
        $filters = [
            'tag' => $tag,
            'sort' => $request->get('sort', 'recent'),
        ];

        $questions = $this->knowledgeBaseService->getPublicQuestions($filters, 15);
        $categories = $this->knowledgeBaseService->getActiveCategories();
        $tags = $this->knowledgeBaseService->getTagsWithCount();

        return view('public.knowledge-base.tag', compact(
            'questions',
            'categories',
            'tags',
            'tag'
        ));
    }
}
