<?php

namespace App\Services\Forms\Objects;

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

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

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

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

    public function store(array $data) {
        $parent = ObjectType::byUuid($data['parent'] ?? null)->first();
        $data['parent_id'] = $parent->id ?? 0;
        $model = ObjectType::create($data);
        return fractal($model, new ObjectTypeTransformer())->respond();
    }

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