<?php

namespace App\Http\Controllers\KnowledgeSharing;

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

/**
 * DiscussionController
 * 
 * Handles CRUD operations for discussions in the authenticated dashboard.
 * Contributors can create and manage their own discussions.
 * Managers can manage all discussions.
 * 
 * @package App\Http\Controllers\KnowledgeSharing
 */
class DiscussionController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected DiscussionService $discussionService
    ) {}

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

        // Build query based on user role
        $query = Discussion::with(['user', 'topic'])
            ->withCount('activeReplies');

        // Non-managers can only see their own discussions
        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('topic_id')) {
            $query->where('topic_id', $request->get('topic_id'));
        }

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

        if ($request->has('inactive')) {
            $query->where('is_active', false);
        } else {
            $query->where('is_active', true);
        }

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

        $discussions = $query->paginate(15);
        $topics = DiscussionTopic::active()->orderBy('name')->get();
        $statistics = $this->discussionService->getStatistics();

        return view('knowledge-sharing.discussions.index', compact(
            'discussions',
            'topics',
            'statistics'
        ));
    }

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

        $topics = DiscussionTopic::active()->orderBy('name')->get();

        return view('knowledge-sharing.discussions.create', compact('topics'));
    }

    /**
     * Store a newly created discussion.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('create discussions'), 403);

        // Validation
        $validated = $request->validate([
            'title' => 'required|string|max:191|min:5',
            'content' => 'required|string|min:20',
            'topic_id' => 'required|exists:discussion_topics,id',
            'status' => 'nullable|in:draft,published,pending_review',
        ], [
            'title.required' => 'Please enter a title for your discussion.',
            'title.min' => 'The title must be at least 5 characters.',
            'title.max' => 'The title cannot exceed 191 characters.',
            'content.required' => 'Please enter content for your discussion.',
            'content.min' => 'The content must be at least 20 characters.',
            'topic_id.required' => 'Please select a topic for your discussion.',
            'topic_id.exists' => 'The selected topic is invalid.',
        ]);

        // Create discussion
        $discussion = $this->discussionService->createDiscussion($validated, auth()->user());

        return redirect()
            ->route('knowledge-sharing.discussions.show', $discussion)
            ->with('success', 'Discussion created successfully!');
    }

    /**
     * Display the specified discussion.
     *
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\View\View
     */
    public function show(Discussion $discussion): View
    {
        // Permission check - owner or manager
        abort_unless(
            $discussion->user_id === auth()->id() || 
            auth()->user()->can('view discussions'),
            403
        );

        $discussion->load(['user', 'topic', 'activeReplies.user']);

        return view('knowledge-sharing.discussions.show', compact('discussion'));
    }

    /**
     * Show the form for editing the specified discussion.
     *
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\View\View
     */
    public function edit(Discussion $discussion): View
    {
        // Permission check - owner or manager
        abort_unless(
            $discussion->user_id === auth()->id() || 
            auth()->user()->can('edit discussions'),
            403,
            'You do not have permission to edit this discussion.'
        );

        $topics = DiscussionTopic::active()->orderBy('name')->get();

        return view('knowledge-sharing.discussions.edit', compact('discussion', 'topics'));
    }

    /**
     * Update the specified discussion.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Discussion $discussion): RedirectResponse
    {
        // Permission check
        abort_unless(
            $discussion->user_id === auth()->id() || 
            auth()->user()->can('edit discussions'),
            403,
            'You do not have permission to update this discussion.'
        );

        // Validation
        $validated = $request->validate([
            'title' => 'required|string|max:191|min:5',
            'content' => 'required|string|min:20',
            'topic_id' => 'required|exists:discussion_topics,id',
            'status' => 'nullable|in:draft,published,archived,pending_review',
            'is_active' => 'nullable|boolean',
            'is_pinned' => 'nullable|boolean',
            'is_featured' => 'nullable|boolean',
        ]);

        // Only managers can change pinned/featured status
        if (!auth()->user()->hasAnyRole(['Super Manager', 'Manager'])) {
            unset($validated['is_pinned'], $validated['is_featured']);
        }

        // Update discussion
        $this->discussionService->updateDiscussion($discussion, $validated);

        return redirect()
            ->route('knowledge-sharing.discussions.show', $discussion)
            ->with('success', 'Discussion updated successfully!');
    }

    /**
     * Remove the specified discussion.
     *
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Discussion $discussion): RedirectResponse
    {
        // Permission check
        abort_unless(
            $discussion->user_id === auth()->id() || 
            auth()->user()->can('delete discussions'),
            403,
            'You do not have permission to delete this discussion.'
        );

        $this->discussionService->deleteDiscussion($discussion);

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

    /**
     * Toggle featured status.
     *
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\Http\RedirectResponse
     */
    public function toggleFeatured(Discussion $discussion): RedirectResponse
    {
        // Permission check - only managers
        abort_unless(auth()->user()->can('feature discussions'), 403);

        $isFeatured = $this->discussionService->toggleFeatured($discussion);

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

    /**
     * Toggle pinned status.
     *
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\Http\RedirectResponse
     */
    public function togglePinned(Discussion $discussion): RedirectResponse
    {
        // Permission check - only managers
        abort_unless(auth()->user()->can('pin discussions'), 403);

        $isPinned = $this->discussionService->togglePinned($discussion);

        return redirect()
            ->back()
            ->with('success', $isPinned 
                ? 'Discussion pinned to top.' 
                : 'Discussion unpinned.');
    }

    /**
     * Bulk delete discussions.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function bulkDelete(Request $request): RedirectResponse
    {
        // Permission check
        abort_unless(auth()->user()->can('delete discussions'), 403);

        $validated = $request->validate([
            'discussion_ids' => 'required|array',
            'discussion_ids.*' => 'exists:discussions,id',
        ]);

        $deleted = Discussion::whereIn('id', $validated['discussion_ids'])->delete();

        return redirect()
            ->back()
            ->with('success', "{$deleted} discussions deleted successfully.");
    }
}
