<?php

namespace App\Http\Livewire\Pages;

use Illuminate\Support\Facades\Log;
use Livewire\Component;

class Index extends Component
{
    public $carCount = 0;
    public $allMake = [];

    public $make;
    public $price;
    public $verified = true;

    public function mount()
    {
        $this->carCount = \App\Models\Cars::count(); // Get the total count of cars
        $this->allMake = \App\Models\Make::all(); // Fetch all makes for the dropdown
    }

    // Add validation rules for properties
    protected $rules = [
        'make' => 'nullable|exists:makes,id',  // Validate make exists in the makes table
        'price' => 'nullable|numeric|min:1',  // Validate price is numeric and greater than 0
    ];

    public function updated($property)
    {
        $this->validateOnly($property); // Validate only the updated property
        $this->queryCars(); // Call the method to query cars based on filters
    }

    public function submit()
    {
        return $this->navigate(); // Navigate when form is submitted
    }

    public function navigate()
    {
        // Redirect with selected options
        return redirect()->route('cars')->with(['vehicle_filter' => ['make' => $this->make, 'price' => $this->price]]);
    }

    public function queryCars()
    {
        // Start building the query for the Cars model
        $query = \App\Models\Cars::query();

        // Filter by make if selected
        if ($this->make) {
            $query->where('make_id', $this->make);
        }

        // Filter by price range if selected
        if ($this->price) {
            $query->where('price', '<=', $this->price);
        }

        // Count the filtered cars
        $this->carCount = $query->count();
    }

    public function render()
    {
        return view('livewire.pages.index');
    }
}
