<?php

namespace App\Http\Livewire\Pages\Main;

use Livewire\Component;
use App\Models\Cars as ModelCars;
use Livewire\WithPagination;

class Cars extends Component
{
    use WithPagination;

    public $carCount = 0;
    public $price;
    public $transmission;
    public $fuel;
    public $make;

    public $allMake = [];
    protected $availableCars; // Change to protected or private

    public $perPage = 20; // Number of cars per page

    public function mount($category = null)
    {
        $this->allMake = \App\Models\Make::all(); // Fetch all makes for the dropdown

        if(!$category) {

            if(session()->has('vehicle_filter')) {
                $filter = session('vehicle_filter');

                $this->price = $filter['price'];
                $this->make = $filter['make'];
            }

            // Initially, fetch all cars
            $this->queryCars();
        } else {
            $this->availableCars = ModelCars::where('category_id', $category)->paginate($this->perPage);
            $this->carCount = $this->availableCars->total();
        }
    }

    public function updated()
    {
        // Reapply the filters when a property is updated
        $this->queryCars();
    }

    public function queryCars()
    {
        // Start with the Cars query builder
        $query = ModelCars::with(['car_detail', 'car_general', 'car_engine']);

        // Apply make filter if selected
        if ($this->make) {
            $query->where('make_id', $this->make);
        }
        
        // Apply price filter if selected
        if ($this->price) {
            $query->where('price', '<=', $this->price);
        }

        // Apply transmission filter if selected
        if ($this->transmission) {
            $query->whereHas('car_detail', function($query) {
                $query->where('transmission', $this->transmission);
            });
        }

        // Apply fuel filter if selected
        if ($this->fuel) {
            $query->whereHas('car_detail', function($query) {
                $query->where('fuel', $this->fuel);
            });
        }

        // Get paginated results (e.g., 10 cars per page)
        $this->availableCars = $query->paginate($this->perPage);

        // Update the total car count
        $this->carCount = $this->availableCars->total();
    }

    // Public method to get available cars (paginated)
    public function getAvailableCarsProperty()
    {
        return $this->availableCars;
    }

    public function render()
    {
        return view('livewire.pages.main.cars', [
            'cars' => $this->availableCars, // Expose paginated cars
        ]);
    }
}
