<?php

namespace App\Livewire\Diagnosis;

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

class Index extends Component
{
    use WithPagination;

    public $search = '';

    public $statusFilter = '';

    public $priorityFilter = '';

    public $dateFrom = '';

    protected $queryString = [
        'search' => ['except' => ''],
        'statusFilter' => ['except' => ''],
        'priorityFilter' => ['except' => ''],
        'dateFrom' => ['except' => ''],
    ];

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

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

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

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

    public function clearFilters()
    {
        $this->search = '';
        $this->statusFilter = '';
        $this->priorityFilter = '';
        $this->dateFrom = '';
        $this->resetPage();
    }

    public function refreshList()
    {
        $this->resetPage();
        $this->dispatch('$refresh');
    }

    public function render()
    {
        $query = Diagnosis::with([
            'jobCard.customer',
            'jobCard.vehicle',
            'serviceCoordinator',
            'estimate',
        ]);

        // Apply search filter
        if ($this->search) {
            $query->whereHas('jobCard', function ($q) {
                $q->where('job_card_number', 'like', '%'.$this->search.'%')
                    ->orWhereHas('customer', function ($customerQuery) {
                        $customerQuery->where('first_name', 'like', '%'.$this->search.'%')
                            ->orWhere('last_name', 'like', '%'.$this->search.'%')
                            ->orWhere('phone', 'like', '%'.$this->search.'%');
                    });
            });
        }

        // Apply status filter
        if ($this->statusFilter) {
            $query->where('diagnosis_status', $this->statusFilter);
        }

        // Apply priority filter
        if ($this->priorityFilter) {
            $query->where('priority_level', $this->priorityFilter);
        }

        // Apply date filter
        if ($this->dateFrom) {
            $query->whereDate('diagnosis_date', '>=', $this->dateFrom);
        }

        $diagnoses = $query->orderBy('created_at', 'desc')->paginate(20);

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