<?php

namespace App\Http\Controllers;

use App\Models\ForumCategory;
use App\Models\ForumReply;
use App\Models\ForumThread;
use App\Services\ThemeService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ForumController extends Controller
{
    public function __construct(
        protected ThemeService $themeService
    ) {}

    public function index()
    {
        $categories = ForumCategory::orderBy('order')->orderBy('name')
            ->withCount(['threads' => fn ($q) => $q->where('is_approved', true)])
            ->get();

        return $this->themeService->render('forum.index', [
            'categories' => $categories,
        ]);
    }

    public function category(string $slug)
    {
        $category = ForumCategory::where('slug', $slug)->firstOrFail();
        $threads = $category->threads()
            ->where('is_approved', true)
            ->paginate(20);

        return $this->themeService->render('forum.category', [
            'category' => $category,
            'threads' => $threads,
        ]);
    }

    public function thread(string $categorySlug, string $threadSlug)
    {
        $category = ForumCategory::where('slug', $categorySlug)->firstOrFail();
        $thread = ForumThread::where('forum_category_id', $category->id)
            ->where('slug', $threadSlug)
            ->where('is_approved', true)
            ->with(['replies' => fn ($q) => $q->where('is_approved', true)->orderBy('created_at'), 'category'])
            ->firstOrFail();

        return $this->themeService->render('forum.thread', [
            'category' => $category,
            'thread' => $thread,
        ]);
    }

    public function createThread(string $slug)
    {
        $category = ForumCategory::where('slug', $slug)->firstOrFail();

        return $this->themeService->render('forum.create-thread', [
            'category' => $category,
        ]);
    }

    public function storeThread(Request $request, string $slug)
    {
        $category = ForumCategory::where('slug', $slug)->firstOrFail();
        $request->validate([
            'author_name' => 'required|string|max:255',
            'author_email' => 'required|email',
            'title' => 'required|string|max:255',
            'content' => 'required|string|max:5000',
        ]);

        $approved = ! $category->moderation_enabled;

        $thread = ForumThread::create([
            'forum_category_id' => $category->id,
            'user_id' => auth()->id(),
            'author_name' => $request->author_name,
            'author_email' => $request->author_email,
            'title' => $request->title,
            'content' => $request->content,
            'is_approved' => $approved,
            'slug' => Str::slug($request->title).'-'.Str::random(6),
        ]);

        if (! $approved) {
            return redirect()->route('forum.category', $category->slug)
                ->with('success', 'Votre sujet a été envoyé. Il sera visible après validation par un modérateur.');
        }

        return redirect()->route('forum.thread', [$category->slug, $thread->slug])
            ->with('success', 'Sujet créé avec succès.');
    }

    public function storeReply(Request $request, string $categorySlug, string $threadSlug)
    {
        $category = ForumCategory::where('slug', $categorySlug)->firstOrFail();
        $thread = ForumThread::where('forum_category_id', $category->id)
            ->where('slug', $threadSlug)
            ->where('is_approved', true)
            ->firstOrFail();

        if ($thread->is_locked) {
            return back()->withErrors(['content' => 'Ce sujet est verrouillé.']);
        }

        $request->validate([
            'author_name' => 'required|string|max:255',
            'author_email' => 'required|email',
            'content' => 'required|string|max:5000',
        ]);

        $approved = ! $category->moderation_enabled;

        ForumReply::create([
            'forum_thread_id' => $thread->id,
            'user_id' => auth()->id(),
            'author_name' => $request->author_name,
            'author_email' => $request->author_email,
            'content' => $request->content,
            'is_approved' => $approved,
        ]);

        if ($approved) {
            $thread->syncReplyStats();
        }

        if (! $approved) {
            return redirect()->route('forum.thread', [$category->slug, $thread->slug])
                ->with('success', 'Votre réponse a été envoyée. Elle sera visible après validation par un modérateur.');
        }

        return redirect()->route('forum.thread', [$category->slug, $thread->slug])
            ->with('success', 'Réponse publiée.');
    }
}
