<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use App\Models\News;
use App\Support\ActivityLogger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $query = News::with(['user', 'comments'])->publiclyVisible();

        if (Schema::hasColumn('news', 'published_at')) {
            $query->orderByRaw('COALESCE(published_at, created_at) DESC');
        } else {
            $query->orderByDesc('created_at');
        }

        $news = $query->paginate(10);

        return view('news.index', compact('news'));
    }

    /**
     * Display the specified resource.
     */
    public function show(News $news)
    {
        if (! $news->isPubliclyVisible() && (! auth()->check() || ! auth()->user()->is_admin)) {
            abort(404);
        }

        $news->load([
            'user',
            'rootComments.user',
            'rootComments.replies.user',
        ]);

        return view('news.show', compact('news'));
    }

    /**
     * Store a comment for the specified news.
     */
    public function storeComment(Request $request, News $news)
    {
        if (auth()->user()->is_banned) {
            return redirect()->route('news.show', $news)
                ->with('error', __('Your account cannot post comments.'));
        }

        $validated = $request->validate([
            'content' => 'required|string|max:1000',
            'parent_id' => 'nullable|integer|exists:comments,id',
        ]);

        $parentId = null;
        if (! empty($validated['parent_id'])) {
            $parent = Comment::query()
                ->where('news_id', $news->id)
                ->whereNull('parent_id')
                ->whereKey($validated['parent_id'])
                ->first();

            if (! $parent) {
                return redirect()->route('news.show', $news)
                    ->withErrors(['content' => __('You can only reply to top-level comments.')]);
            }

            $parentId = $parent->id;
        }

        $comment = $news->comments()->create([
            'user_id' => auth()->id(),
            'parent_id' => $parentId,
            'content' => $validated['content'],
        ]);

        ActivityLogger::log(
            'comment.created',
            \Illuminate\Support\Str::limit(strip_tags($comment->content), 80),
            $comment,
            ['news_id' => $news->id, 'news_title' => $news->title]
        );

        return redirect()->route('news.show', $news)
            ->with('success', __('Comment added successfully!'));
    }

    /**
     * Delete a comment.
     */
    public function destroyComment(News $news, Comment $comment)
    {
        if ((int) $comment->news_id !== (int) $news->id) {
            abort(404);
        }

        if (auth()->id() !== $comment->user_id && ! auth()->user()->is_admin) {
            abort(403);
        }

        ActivityLogger::log(
            'comment.deleted',
            \Illuminate\Support\Str::limit(strip_tags($comment->content), 80),
            $comment,
            ['news_id' => $news->id, 'news_title' => $news->title]
        );

        $comment->delete();

        return redirect()->route('news.show', $news)
            ->with('success', __('Comment deleted successfully!'));
    }
}
