<?php

namespace Modules\Employee\Filters;

use Illuminate\Database\Eloquent\Builder;
use Modules\Employee\DTO\EmployeeListDTO;

class EmployeeFilter
{
    public function __construct(protected EmployeeListDTO $dto) {}

    public function apply(Builder $query): Builder
    {
        return $query->hasUser($this->dto->hasUser)
            ->filterStatus($this->dto->status)
            ->search($this->dto->search)
            ->when($this->dto->sortBy, fn ($q) => $this->sort($q));
    }

    protected function sort(Builder $query): Builder
    {
        $allowed = ['name', 'emp_number', 'phone', 'created_at'];

        if (in_array($this->dto->sortBy, $allowed)) {
            return $query->orderBy(
                $this->dto->sortBy,
                $this->dto->sortOrder
            );
        }

        return $query;
    }
}
