<?php

namespace App\Services\Filters\Companies;

use App\Models\Companies\CompanyMember;
use App\Services\Filters\FiltersService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;

class CompanyMemberFilters extends FiltersService {
    public function get(Collection $filters): array {
        $groups = [
            [
                'name' => 'common',
                'title' => 'Общие параметры',
                'fields' => $this->nativeFields($filters)
            ]
        ];
        $query = CompanyMember::query();
        $this->applyFilters($query, $filters);
        return ['groups' => ['data' => $groups], 'total' => $query->count()];
    }

    public function nativeFields(Collection $filters): array {
        return [
        ];
    }


    public function applyFilters(Builder $query, Collection $filters) {
        $this->applyNativeFilters($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, ['position', 'room', 'intercom', ['user' => ['name', 'email', 'phone']], ['department' => ['title']]]);
            elseif ($prop === 'company') $this->applyCompanyFilter($query, $value);
        }
    }

    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) {
    }

}
