<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Comment;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    public function index(Request $request)
    {
        $query = Comment::with([
            'user',
            'commentable' => fn(MorphTo $m) => $m->constrain([
                \App\Models\Episode::class => fn($q) => $q->with('season.anime'),
                \App\Models\Anime::class   => fn($q) => $q,
            ]),
        ])->latest();

        if ($request->status) {
            $query->where('status', $request->status);
        }
        if ($request->search) {
            $query->where('content', 'like', '%' . $request->search . '%');
        }
        if ($request->user_id) {
            $query->where('user_id', $request->user_id);
        }

        $comments = $query->paginate(30)->withQueryString();
        return view('admin.comments.index', compact('comments'));
    }

    public function show(Comment $comment)
    {
        $comment->load(['user', 'replies.user', 'parent.user']);
        return view('admin.comments.show', compact('comment'));
    }

    public function approve(Comment $comment)
    {
        $comment->update(['status' => 'approved']);
        return back()->with('success', 'Yorum onaylandı.');
    }

    public function reject(Comment $comment)
    {
        $comment->update(['status' => 'rejected']);
        return back()->with('success', 'Yorum reddedildi.');
    }

    public function pin(Comment $comment)
    {
        $comment->update(['is_pinned' => !$comment->is_pinned]);
        $msg = $comment->is_pinned ? 'Yorum sabitlendi.' : 'Yorum sabit kaldırıldı.';
        return back()->with('success', $msg);
    }

    public function destroy(Comment $comment)
    {
        $comment->delete();
        return back()->with('success', 'Yorum silindi.');
    }

    public function reply(Request $request, Comment $comment)
    {
        $data = $request->validate(['content' => 'required|string|max:2000']);

        Comment::create([
            'user_id'          => auth()->id(),
            'commentable_type' => $comment->commentable_type,
            'commentable_id'   => $comment->commentable_id,
            'parent_id'        => $comment->id,
            'content'          => $data['content'],
            'status'           => 'approved',
        ]);

        return back()->with('success', 'Yanıt gönderildi.');
    }
}
