<?php

namespace App\Livewire;

use App\Models\ServiceCategory;
use App\Models\Service;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('components.layouts.app')]
class ServicesByCategory extends Component
{
    use WithPagination;

    public ServiceCategory $category;
    public $search = '';

    protected $queryString = [
        'search' => ['except' => ''],
    ];

    public function mount($slug)
    {
        $this->category = ServiceCategory::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();
    }

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

    public function services()
    {
        $query = Service::where('category_id', $this->category->id)
            ->where('is_active', true)
            ->ordered();

        if ($this->search) {
            $query->where(function ($q) {
                $q->where('title', 'like', '%' . $this->search . '%')
                    ->orWhere('description', 'like', '%' . $this->search . '%');
            });
        }

        return $query->paginate(12);
    }

    public function processes()
    {
        return $this->category->processes()
            ->where('is_active', true)
            ->orderBy('order')
            ->get();
    }

    public function getTitle()
    {
        return $this->category->name . ' - Services';
    }

    public function render()
    {
        return view('livewire.services-by-category', [
            'services' => $this->services(),
            'processes' => $this->processes(),
        ])
        ->title($this->getTitle());
    }
}
