<?php

namespace App\Services\Filters\Objects;

use App\Models\Objects\Field;
use App\Models\Objects\NirObject;
use App\Services\Filters\FiltersService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;

class ObjectFilters extends FiltersService {
    public function get(Collection $filters): array {
        $groups = [
        ];
        $query = NirObject::query();
        $this->applyFilters($query, $filters);
        return ['groups' => ['data' => $groups], 'total' => $query->count()];
    }


    public function applyFilters(Builder $query, Collection $filters) {
        $this->applyNativeFilters($query, $filters);
        $this->applyObjectFilters($query, $filters);
        $this->applyPermissionsFilters($query);
    }

    public function applyNativeFilters(Builder $query, Collection $filters) {
        $filters->each(function($value, $prop) use($query) {
            $this->applyNativeFilter($query, $prop, $value);
        });
    }

    public function applyNativeFilter(Builder $query, $prop, $value) {
        if ($value) {
            if ($prop === 'search') $this->applySearchFilter($query, $value, ['name', ['pages' => ['name']], ['stringValues' => ['value']], ['textValues' => ['value']], ['htmlValues' => ['value']]]);
        }
    }

    public function applyObjectFilters(Builder $query, Collection $filters) {
        Field::applyFilters($query, $filters);
    }

    public function applyCompanyFilter(Builder $query, $value) {
        $query->whereHas('company', function($query) use($value) {
            ($value === 'main') ? $query->where(['is_main' => 1]) : $query->whereIn('uuid', is_array($value) ? $value : [$value]);
        });
    }


    public function applyPermissionsFilters(Builder $query) {
    }

}
