<?php

namespace App\Services\Filters\Publications;

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

class PublicationFilters 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, ['name', 'excerpt']);
            elseif ($prop === 'page') $this->applyRelationFilter($query, 'page', $value);
        }
    }

    public function applyPermissionsFilters(Builder $query) {
        $user = Auth::user();
        if (!($user->isAdmin ?? null)) $query->where(['is_published' => true])->where('published_at', '<=', now());
    }

}
