<?php

namespace App\Http\Livewire\Tenant;

use App\Models\Service;
use App\Support\PublicUploader;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class ServicesTable extends Component
{
    use WithPagination;

    #[Url(as: 'q')]
    public string $search = '';

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

    public function toggleActive(int $id): void
    {
        $service = Service::findOrFail($id);
        $service->update(['is_active' => ! $service->is_active]);
    }

    public function delete(int $id): void
    {
        $service = Service::findOrFail($id);
        if ($service->image_path) {
            PublicUploader::delete($service->image_path);
        }

        $service->delete();
        session()->flash('success', "Servicio '{$service->name}' eliminado.");
    }

    public function render()
    {
        $services = Service::query()
            ->with('category:id,name')
            ->when($this->search, fn ($q) => $q->where('name', 'like', '%'.$this->search.'%'))
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate(15);

        return view('livewire.tenant.services-table', compact('services'));
    }
}
