<?php

namespace App\Http\Controllers\KnowledgeSharing;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreDiscussionReplyRequest;
use App\Http\Requests\UpdateDiscussionReplyRequest;
use App\Models\Discussion;
use App\Models\DiscussionReply;
use App\Services\DiscussionService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

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

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

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

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

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

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

    /**
     * Show the form for creating a new reply.
     */
    public function create(Discussion $discussion): View
    {
        // Permission check - accept either old or new permission
        abort_unless(
            auth()->user()->can('create discussion replies') || auth()->user()->can('create discussions'),
            403
        );

        // Ensure discussion exists and is active
        abort_if(!$discussion->is_active, 404);

        $parentReplies = DiscussionReply::where('discussion_id', $discussion->id)
            ->where('is_active', true)
            ->orderBy('created_at')
            ->get();

        return view('knowledge-sharing.discussions.replies.create', compact('discussion', 'parentReplies'));
    }

    /**
     * Store a newly created reply in storage.
     */
    public function store(StoreDiscussionReplyRequest $request, Discussion $discussion): RedirectResponse
    {
        // Ensure discussion exists and is active
        abort_if(!$discussion->is_active, 404);

        // createReply handles XSS sanitization, depth calculation, and triggers
        // discussion->updateReplyStats() via the model boot hook on created
        $reply = $this->discussionService->createReply(
            $discussion,
            $request->validated(),
            auth()->user()
        );

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

    /**
     * Display the specified reply.
     */
    public function show(DiscussionReply $reply): View
    {
        // Permission check
        abort_unless(auth()->user()->can('view discussions'), 403);

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

        $discussion = $reply->discussion;
        $childReplies = $reply->replies()->with('user')->get();

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

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

        $discussion = $reply->discussion;

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

    /**
     * Update the specified reply in storage.
     */
    public function update(UpdateDiscussionReplyRequest $request, DiscussionReply $reply): RedirectResponse
    {
        // Update the reply
        $this->discussionService->updateReply($reply, $request->validated());

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

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

        $discussion = $reply->discussion;
        $discussionSlug = $discussion->slug;

        // Delete reply (also updates reply stats via model boot)
        $this->discussionService->deleteReply($reply);

        return redirect()
            ->route('knowledge-sharing.discussions.show', $discussionSlug)
            ->with('success', 'Reply deleted successfully!');
    }
}
