<?php

namespace App\Livewire;

use App\Models\Comment;
use Livewire\Component;
use Livewire\WithPagination;

class AdminCommentSearch extends Component
{
    use WithPagination;

    public $search = '';

    public $userSearch = '';

    public function updatingSearch(): void
    {
        $this->resetPage();
    }

    public function updatingUserSearch(): void
    {
        $this->resetPage();
    }

    public function deleteComment($commentId)
    {
        $comment = Comment::where('id', (int) $commentId)->firstOrFail();
        $comment->delete();

        cache()->flush();
    }

    public function render()
    {
        $comments = Comment::when($this->search !== '', fn ($query) => $query->where('body', 'LIKE', "%$this->search%"))
            ->when($this->userSearch !== '', fn ($query) => $query->whereHas('user', fn ($query) => $query->where('name', 'LIKE', "%{$this->userSearch}%")))
            ->orderBy('created_at', 'DESC')
            ->paginate(12);

        return view('livewire.admin-comment-search', [
            'comments' => $comments,
        ]);
    }
}
