<?php

namespace App\Livewire\WorkOrders;

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

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $statusFilter = '';
    public $priorityFilter = '';

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

    public function render()
    {
        $workOrders = WorkOrder::with([
                'jobCard.customer', 
                'jobCard.vehicle', 
                'serviceCoordinator',
                'assignedTechnician',
                'estimate'
            ])
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('work_order_number', 'like', '%' . $this->search . '%')
                      ->orWhereHas('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->statusFilter, function ($query) {
                $query->where('status', $this->statusFilter);
            })
            ->when($this->priorityFilter, function ($query) {
                $query->where('priority', $this->priorityFilter);
            })
            ->latest()
            ->paginate(15);

        return view('livewire.work-orders.index', compact('workOrders'));
    }
}
