<?php

namespace App\Livewire\Timesheets;

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

class Index extends Component
{
    use WithPagination;

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

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

    public function render()
    {
        $timesheets = Timesheet::with([
                'jobCard.customer',
                'jobCard.vehicle',
                'technician',
                'workOrderTask'
            ])
            ->when($this->search, function ($query) {
                $query->whereHas('jobCard', function ($jobQuery) {
                    $jobQuery->where('job_number', 'like', '%' . $this->search . '%')
                            ->orWhereHas('customer', function ($customerQuery) {
                                $customerQuery->where('name', 'like', '%' . $this->search . '%');
                            });
                })
                ->orWhereHas('technician', function ($techQuery) {
                    $techQuery->where('name', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->typeFilter, function ($query) {
                $query->where('task_type', $this->typeFilter);
            })
            ->when($this->statusFilter, function ($query) {
                $query->where('status', $this->statusFilter);
            })
            ->when($this->dateFilter, function ($query) {
                $query->whereDate('start_time', $this->dateFilter);
            })
            ->latest()
            ->paginate(15);

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