<?php

namespace App\Services\Forms\Objects;

use App\Events\FeedbackSender;
use App\Models\Objects\FieldsGroup;
use App\Models\Objects\FieldType;
use App\Models\Objects\ObjectType;
use App\Services\Forms\FormsService;
use App\Transformers\Objects\FieldsGroupTransformer;

class FieldsGroupForms extends FormsService
{
    public array $formTitles = ['create' => 'Создание группы объекта', 'update' => 'Редактирование группы объекта'];

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

    public function commonGroupFields(?FieldsGroup $model): array {
        $fields = [
            [
                'name' => 'name',
                'title' => 'Наименование',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->name ?? null
            ]
        ];
        return ['data' => $fields];
    }

    public function store(array $data) {
        $object_type = ObjectType::byUuid($data['object_type'] ?? null)->first();
        $data['object_type_id'] = $object_type->id ?? null;
        $model = FieldsGroup::create($data);
        return fractal($model, new FieldsGroupTransformer())->respond();
    }

    public function update(string $id, array $data) {
        $model = FieldsGroup::byUuid($id)->firstOrFail();
        $model->update($data);
        return fractal($model->fresh(), new FieldsGroupTransformer())->respond();
    }
}