<?php

namespace App\Livewire\Pages\QrCodes;

use App\Domains\QrCode\Models\QrCode;
use Illuminate\View\View;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public string $search = '';

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

    #[On('qr-created')]
    #[On('qr-updated')]
    #[On('qr-deleted')]
    public function refresh(): void
    {
        $this->resetPage();
    }

    public function render(): View
    {
        $workspace = require_workspace();

        $qrCodes = QrCode::where('workspace_id', $workspace->id)
            ->when($this->search, fn ($q) => $q->where('label', 'like', "%{$this->search}%"))
            ->latest()
            ->paginate(20);

        return view('livewire.pages.qr-codes.index', compact('qrCodes'))
            ->layout('layouts.nimuli-app', ['title' => 'QR Codes']);
    }
}
