<?php

namespace App\Livewire\Inspections;

use App\Models\VehicleInspection;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $typeFilter = '';
    public $statusFilter = '';

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

    public function render()
    {
        $inspections = VehicleInspection::with([
                'jobCard.customer',
                'jobCard.vehicle', 
                'inspector'
            ])
            ->when($this->search, function ($query) {
                $query->whereHas('jobCard', function ($jobQuery) {
                    $jobQuery->where('job_number', 'like', '%' . $this->search . '%')
                            ->orWhereHas('customer', function ($customerQuery) {
                                $customerQuery->where('first_name', 'like', '%' . $this->search . '%')
                                            ->orWhere('last_name', 'like', '%' . $this->search . '%');
                            });
                });
            })
            ->when($this->typeFilter, function ($query) {
                $query->where('inspection_type', $this->typeFilter);
            })
            ->when($this->statusFilter, function ($query) {
                $query->where('overall_condition', $this->statusFilter);
            })
            ->latest()
            ->paginate(15);

        return view('livewire.inspections.index', compact('inspections'));
    }
}
