<?php

namespace App\Http\Controllers\Contributor;

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

/**
 * ContributorDashboardController
 *
 * Handles contributor-specific routes: dashboard, discussions list, replies list.
 *
 * @package App\Http\Controllers\Contributor
 */
class ContributorDashboardController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected DiscussionService $discussionService
    ) {}

    /**
     * Display the contributor dashboard.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request): View
    {
        $user = auth()->user();

        // Statistics
        $statistics = [
            'total_discussions'     => Discussion::where('user_id', $user->id)->count(),
            'published_discussions' => Discussion::where('user_id', $user->id)->where('status', 'published')->count(),
            'draft_discussions'     => Discussion::where('user_id', $user->id)->where('status', 'draft')->count(),
            'total_views'           => (int) Discussion::where('user_id', $user->id)->sum('view_count'),
            'total_replies'         => DiscussionReply::where('user_id', $user->id)->count(),
        ];

        // Recent discussions by this contributor
        $recentDiscussions = Discussion::with(['topic'])
            ->withCount('activeReplies')
            ->where('user_id', $user->id)
            ->latest()
            ->limit(5)
            ->get();

        // Active topics with discussion counts
        $topics = DiscussionTopic::active()
            ->ordered()
            ->withCount(['discussions' => fn($q) => $q->where('status', 'published')])
            ->limit(10)
            ->get();

        // Popular discussions (most viewed, published)
        $popularDiscussions = Discussion::with('user')
            ->where('status', 'published')
            ->where('is_active', true)
            ->orderByDesc('view_count')
            ->limit(5)
            ->get();

        return view('contributor.dashboard', compact(
            'statistics',
            'recentDiscussions',
            'topics',
            'popularDiscussions'
        ));
    }

    /**
     * Display all discussions by the contributor.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function discussions(Request $request): View
    {
        $user = auth()->user();

        $query = Discussion::with(['topic'])
            ->withCount('activeReplies')
            ->where('user_id', $user->id);

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

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

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

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

        $discussions = $query->paginate(10);
        $topics = DiscussionTopic::active()->orderBy('name')->get();

        return view('contributor.discussions.index', compact('discussions', 'topics'));
    }

    /**
     * Display all replies by the contributor.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\View\View
     */
    public function replies(Request $request): View
    {
        $user = auth()->user();

        $replies = \App\Models\DiscussionReply::with(['discussion.topic'])
            ->where('user_id', $user->id)
            ->active()
            ->latest()
            ->paginate(15);

        return view('contributor.replies.index', compact('replies'));
    }
}
