<?php

namespace App\Livewire\Estimates;

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

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $statusFilter = '';
    public $approvalStatusFilter = '';

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

    public function render()
    {
        $estimates = Estimate::with(['jobCard.customer', 'jobCard.vehicle', 'preparedBy'])
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('estimate_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->approvalStatusFilter, function ($query) {
                $query->where('customer_approval_status', $this->approvalStatusFilter);
            })
            ->latest()
            ->paginate(15);

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