<?php

namespace App\Livewire;

use App\Models\IndustryCategory;
use App\Models\IndustryService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

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

    public IndustryCategory $category;
    public $search = '';

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

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

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

    public function industryServices()
    {
        $query = IndustryService::where('industry_category_id', $this->category->id)
            ->where('is_active', true)
            ->ordered();

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

        return $query->paginate(12);
    }

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

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