<?php

namespace App\Services\Forms\Advisories;

use App\Models\Advisories\AdvisoryCompany;
use App\Models\Advisories\AdvisoryMemberRank;
use App\Models\Companies\CompanyMember;
use App\Models\Objects\FieldType;
use App\Services\Forms\FormsService;
use App\Transformers\Advisories\AdvisoryCompanyTransformer;
use App\Transformers\Companies\CompanyMemberTransformer;
use Illuminate\Http\JsonResponse;

class AdvisoryCompanyMembersForms extends FormsService {
    public array $formTitles = ['create' => '', 'update' => 'Добавление сотрудников-участников'];

    public function form(?string $id = null, array $data = []): array {
        $model = AdvisoryCompany::byUuid($id)->first();
        $groups = [
            ['name' => 'common', 'fields' => $this->commonGroupFields($model)]
        ];
        return ['title' => $this->formTitle($model), 'data' => $groups];
    }

    public function commonGroupFields(?AdvisoryCompany $model): array {
        $fields = [
            [
                'name' => 'voter',
                'title' => 'Сотрудник с правом голоса',
                'type' => FieldType::RELATION,
                'required' => true,
                'options' => $model ? fractal($model->company->members, new CompanyMemberTransformer()) : null,
                'value' => $model ? fractal($model->getCompanyMembers(AdvisoryMemberRank::VOTER)->get(), new CompanyMemberTransformer()) : null
            ],
            [
                'name' => 'members',
                'title' => 'Сотрудники',
                'type' => FieldType::RELATION,
                'multiple' => true,
                'options' => $model ? fractal($model->company->members, new CompanyMemberTransformer()) : null,
                'value' => $model ? fractal($model->getCompanyMembers(AdvisoryMemberRank::ORDINARY)->get(), new CompanyMemberTransformer()) : null
            ]
        ];
        return ['data' => $fields];
    }



    public function store(array $data): void {
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = AdvisoryCompany::byUuid($id)->firstOrFail();
        $voter = $data['voter'] ?? null;
        $members = collect($data['members'] ?? [])->filter(function($member_id) use($voter) {
            return $member_id !== $voter;
        })->all();
        $model->advisory->syncMembers(CompanyMember::byUuids($members)->get(), AdvisoryMemberRank::ORDINARY, $model->company);
        $model->advisory->syncMembers(CompanyMember::byUuids([$voter])->get(), AdvisoryMemberRank::VOTER, $model->company);
        return fractal($model->fresh(), new AdvisoryCompanyTransformer())->respond();
    }


}
