<?php

namespace App\Livewire\Pages\Links;

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

class Index extends Component
{
    use WithPagination;

    public string $search = '';

    public string $statusFilter = '';

    public int $workspaceId = 0;

    public function mount(): void
    {
        $this->workspaceId = require_workspace()->id;
    }

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

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

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

    public function render(): View
    {
        $links = Link::where('workspace_id', $this->workspaceId)
            ->when($this->search, fn ($q) => $q->where(function ($q) {
                $q->where('title', 'like', "%{$this->search}%")
                    ->orWhere('slug', 'like', "%{$this->search}%")
                    ->orWhere('target_url', 'like', "%{$this->search}%");
            }))
            ->when($this->statusFilter, fn ($q) => $q->where('status', $this->statusFilter))
            ->latest()
            ->paginate(20);

        return view('livewire.pages.links.index', compact('links'))
            ->layout('layouts.nimuli-app', ['title' => 'Links']);
    }
}
