<?php

namespace App\Http\Controllers;

use App\Models\Business;
use App\Models\Category;
use App\Models\City;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ListingController extends Controller
{
    public function index(Request $request): View
    {
        $keyword = $request->string('keyword')->trim()->toString();
        $cityId = $request->integer('city_id');

        $businesses = Business::query()
            ->approved()
            ->with(['category', 'city'])
            ->when($keyword !== '', function ($query) use ($keyword) {
                $query->where(function ($q) use ($keyword) {
                    $q->where('name', 'like', "%{$keyword}%")
                        ->orWhere('description', 'like', "%{$keyword}%");
                });
            })
            ->when($cityId, fn ($query) => $query->where('city_id', $cityId))
            ->orderByDesc('featured')
            ->orderBy('name')
            ->paginate(12)
            ->withQueryString();

        return view('listing', [
            'businesses' => $businesses,
            'categories' => Category::orderBy('name')->get(),
            'cities' => City::orderBy('name')->get(),
            'keyword' => $keyword,
            'cityId' => $cityId,
        ]);
    }
}
