<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\Post;
use Illuminate\Http\Request;

class CommentsController extends Controller
{
    public function index(Request $request)
    {
        $comments = Comment::with('post')
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->when($request->search, fn($q) => $q->where('content', 'like', "%{$request->search}%")
                ->orWhere('author_name', 'like', "%{$request->search}%"))
            ->latest()
            ->paginate(30)
            ->withQueryString();

        $counts = [
            'all'     => Comment::count(),
            'pending' => Comment::where('status', 'pending')->count(),
            'approved'=> Comment::where('status', 'approved')->count(),
            'spam'    => Comment::where('status', 'spam')->count(),
        ];

        return view('admin.comments.index', compact('comments', 'counts'));
    }

    public function approve(Comment $comment)
    {
        $wasNotApproved = $comment->status !== 'approved';
        $comment->update(['status' => 'approved']);
        if ($wasNotApproved) {
            $comment->post->increment('comments_count');
        }
        return back()->with('success', 'Comment approved.');
    }

    public function spam(Comment $comment)
    {
        $wasApproved = $comment->status === 'approved';
        $comment->update(['status' => 'spam']);
        if ($wasApproved) {
            $comment->post->decrement('comments_count');
        }
        return back()->with('success', 'Marked as spam.');
    }

    public function destroy(Comment $comment)
    {
        if ($comment->status === 'approved') {
            $comment->post->decrement('comments_count');
        }
        $comment->delete();
        return back()->with('success', 'Comment deleted.');
    }

    public function bulkAction(Request $request)
    {
        $ids    = $request->input('ids', []);
        $action = $request->input('action');

        if (empty($ids)) return back()->with('error', 'No comments selected.');

        match($action) {
            'approve' => Comment::whereIn('id', $ids)->update(['status' => 'approved']),
            'spam'    => Comment::whereIn('id', $ids)->update(['status' => 'spam']),
            'delete'  => Comment::whereIn('id', $ids)->delete(),
            default   => null,
        };

        return back()->with('success', count($ids) . ' comments updated.');
    }
}
