<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LibraryComment;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class LibraryCommentController extends Controller
{
    public function index(Request $request): View
    {
        $query = LibraryComment::with(['user', 'libraryContent']);

        if ($request->filled('status')) {
            if ($request->status === 'approved') {
                $query->where('is_approved', true);
            } elseif ($request->status === 'pending') {
                $query->where('is_approved', false);
            }
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('content', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($q) use ($search) {
                      $q->where('name', 'like', "%{$search}%");
                  });
        }

        $comments = $query->latest()->paginate(25);

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

    public function show(LibraryComment $comment): View
    {
        $comment->load(['user', 'libraryContent', 'replies' => function ($q) {
            $q->with('user')->latest();
        }]);

        return view('admin.library-comments.show', compact('comment'));
    }

    public function approve(LibraryComment $comment): RedirectResponse
    {
        $comment->update(['is_approved' => true]);

        return redirect()->back()
            ->with('success', 'Yorum onaylandı.');
    }

    public function reject(LibraryComment $comment): RedirectResponse
    {
        $comment->update(['is_approved' => false]);

        return redirect()->back()
            ->with('success', 'Yorum reddedildi.');
    }

    public function destroy(LibraryComment $comment): RedirectResponse
    {
        $comment->delete();

        return redirect()->back()
            ->with('success', 'Yorum silindi.');
    }

    public function bulkApprove(Request $request): RedirectResponse
    {
        $ids = $request->input('ids', []);
        LibraryComment::whereIn('id', $ids)->update(['is_approved' => true]);

        return redirect()->back()
            ->with('success', count($ids) . ' yorum onaylandı.');
    }

    public function bulkDelete(Request $request): RedirectResponse
    {
        $ids = $request->input('ids', []);
        LibraryComment::whereIn('id', $ids)->delete();

        return redirect()->back()
            ->with('success', count($ids) . ' yorum silindi.');
    }
}
