<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Listing;
use App\Models\Location;
use App\Models\RentalType;
use Livewire\WithPagination;

class ListingSearch extends Component
{
    use WithPagination;

    public $location;
    public $type;
    public $check_in;
    public $check_out;
    public $guests;

    protected $queryString = [
        'location',
        'type',
        'check_in',
        'check_out',
        'guests',
    ];

    public function render()
    {
        $query = Listing::with(['location', 'rentalType'])
            ->withCount('reviews')
            ->withAvg('reviews', 'rating')
            ->available();

        if ($this->location) {
            $query->where('location_id', $this->location);
        }

        if ($this->type) {
            $query->where('rental_type_id', $this->type);
        }

        if ($this->guests) {
            $query->where('capacity', '>=', $this->guests);
        }

        // Cache filter options for better performance
        $locations = \Illuminate\Support\Facades\Cache::remember('locations.all', 3600, function () {
            return Location::withCount('listings')->orderBy('name')->get();
        });

        $rentalTypes = \Illuminate\Support\Facades\Cache::remember('rental_types.all', 3600, function () {
            return RentalType::all();
        });

        return view('livewire.listing-search', [
            'listings' => $query->paginate(12),
            'locations' => $locations,
            'rentalTypes' => $rentalTypes,
        ])->layout('layouts.app');
    }
}
