<?php

namespace App\Services\Forms\Advisories;

use App\Models\Advisories\Advisory;
use App\Models\Companies\Company;
use App\Models\Objects\FieldType;
use App\Services\Forms\FormsService;
use App\Transformers\Advisories\AdvisoryTransformer;
use App\Transformers\Companies\CompanyTransformer;
use Illuminate\Http\JsonResponse;

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

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

    public function commonGroupFields(?Advisory $model): array {
        $fields = [
            [
                'name' => 'companies',
                'title' => 'Организации-участники',
                'type' => FieldType::RELATION,
                'multiple' => true,
                'options' => fractal(Company::all(), new CompanyTransformer()),
                'value' => $model ? fractal($model->companies, new CompanyTransformer()) : null
            ]
        ];
        return ['data' => $fields];
    }



    public function store(array $data): ?JsonResponse {
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = Advisory::byUuid($id)->firstOrFail();
        $exists = Company::byUuids($data['companies'] ?? [])->get()->map(function($company) use($model) {
            return $model->advisoryCompanies()->firstOrCreate(['company_id' => $company->id]);
        });
        $model->advisoryCompanies()->whereNotIn('id', $exists->pluck('id')->all())->delete();
        return fractal($model->fresh(), new AdvisoryTransformer())->respond();
    }


}
