<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Discussion;
use App\Models\DiscussionTopic;
use App\Services\DiscussionService;
use App\Services\SEOService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

/**
 * PublicDiscussionController
 * 
 * Handles public-facing discussion board pages.
 * Displays discussions, topics, and handles search/filtering.
 * 
 * @package App\Http\Controllers\Public
 */
class PublicDiscussionController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected DiscussionService $discussionService,
        protected SEOService $seoService
    ) {}

    /**
     * Display the discussion boards landing page.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request): View
    {
        // Get filters from request
        $filters = [
            'topic_id' => $request->get('topic'),
            'topic_slug' => $request->get('topic_slug'),
            'search' => $request->get('q'),
            'sort' => $request->get('sort', 'latest'),
        ];

        // Get discussions with pagination
        $discussions = $this->discussionService->getPublicDiscussions($filters, 15);

        // Get active topics for sidebar
        $topics = $this->discussionService->getActiveTopics();

        // Get featured discussions
        $featuredDiscussions = $this->discussionService->getFeaturedDiscussions(3);

        // Get popular discussions
        $popularDiscussions = $this->discussionService->getPopularDiscussions(5);

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

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

        return view('public.discussions.index', compact(
            'discussions',
            'topics',
            'featuredDiscussions',
            'popularDiscussions',
            'statistics',
            'seoMetadata',
            'filters'
        ));
    }

    /**
     * Display discussions by topic.
     *
     * @param \Illuminate\Http\Request $request
     * @param string $slug
     * @return \Illuminate\View\View
     */
    public function topic(Request $request, string $slug): View
    {
        // Get the topic
        $topic = $this->discussionService->getTopicBySlug($slug);

        // Get filters
        $filters = [
            'topic_id' => $topic->id,
            'search' => $request->get('q'),
            'sort' => $request->get('sort', 'latest'),
        ];

        // Get discussions
        $discussions = $this->discussionService->getPublicDiscussions($filters, 15);

        // Get all topics for sidebar
        $topics = $this->discussionService->getActiveTopics();

        // Generate SEO metadata
        $seoMetadata = $this->seoService->generateTopicMetadata($topic);

        // Generate breadcrumb schema
        $breadcrumbSchema = $this->seoService->generateBreadcrumbSchema([
            ['name' => 'Home', 'url' => url('/')],
            ['name' => 'Discussions', 'url' => route('public.discussions.index')],
            ['name' => $topic->name],
        ]);

        return view('public.discussions.topic', compact(
            'topic',
            'discussions',
            'topics',
            'seoMetadata',
            'breadcrumbSchema'
        ));
    }

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

        // Increment view count
        $this->discussionService->incrementViewCount($discussion);

        // Get replies
        $replies = $this->discussionService->getDiscussionReplies($discussion, 10);

        // Get related discussions
        $relatedDiscussions = Discussion::published()
            ->where('id', '!=', $discussion->id)
            ->where('topic_id', $discussion->topic_id)
            ->latestActivity()
            ->limit(5)
            ->get();

        // Get all topics for sidebar
        $topics = $this->discussionService->getActiveTopics();

        // Generate SEO metadata
        $seoMetadata = $this->seoService->generateDiscussionMetadata($discussion);

        // Generate structured data
        $schemaData = $this->seoService->generateDiscussionSchema($discussion);

        // Generate breadcrumb schema
        $breadcrumbSchema = $this->seoService->generateBreadcrumbSchema([
            ['name' => 'Home', 'url' => url('/')],
            ['name' => 'Discussions', 'url' => route('public.discussions.index')],
            ['name' => $discussion->topic->name ?? 'General', 'url' => $discussion->topic?->url],
            ['name' => $discussion->title],
        ]);

        return view('public.discussions.show', compact(
            'discussion',
            'replies',
            'relatedDiscussions',
            'topics',
            'seoMetadata',
            'schemaData',
            'breadcrumbSchema'
        ));
    }

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

        $filters = [
            'search' => $query,
            'topic_id' => $request->get('topic'),
            'sort' => $request->get('sort', 'relevance'),
        ];

        $discussions = $this->discussionService->getPublicDiscussions($filters, 15);
        $topics = $this->discussionService->getActiveTopics();

        return view('public.discussions.search', compact(
            'discussions',
            'topics',
            'query'
        ));
    }

    /**
     * AJAX real-time search for the discussion 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 = Discussion::query()
            ->with('topic')
            ->published()
            ->where(function ($q) use ($query) {
                $q->where('title', 'like', "%{$query}%")
                  ->orWhere('excerpt', 'like', "%{$query}%")
                  ->orWhere('content', 'like', "%{$query}%");
            })
            ->withCount('activeReplies');

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

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

        $results = $discussions->map(fn ($d) => [
            'title'       => $d->title,
            'topic'       => $d->topic?->name ?? 'General',
            'reply_count' => $d->active_replies_count ?? 0,
            'view_count'  => number_format($d->view_count),
            'url'         => route('public.discussions.show', $d->slug),
        ]);

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