<?php

namespace App\Services\Forms\Users;

use App\Models\Objects\FieldType;
use App\Models\User;
use App\Services\Forms\FormsService;
use App\Transformers\Assets\AssetTransformer;
use App\Transformers\Users\UserTransformer;
use Illuminate\Http\JsonResponse;

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

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

    public function commonGroupFields(?User $model): array {
        $fields = [
            [
                'name' => 'email',
                'title' => 'Электронная почта',
                'type' => FieldType::STRING,
                'required' => true,
                'readonly' => !!$model,
                'value' => $model->email ?? null
            ],
            [
                'name' => 'name',
                'title' => 'ФИО',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->name ?? null
            ],
            [
                'name' => 'phone',
                'title' => 'Телефон',
                'type' => FieldType::STRING,
                'value' => $model->phone ?? null
            ],
            [
                'name' => 'avatar',
                'title' => 'Фотография профиля',
                'type' => FieldType::IMAGE,
                'value' => ($model->avatar ?? null) ? fractal($model->avatar, new AssetTransformer()) : null
            ]
        ];
        return ['data' => $fields];
    }



    public function store(array $data): ?JsonResponse {
        $model = User::getByData($data, true);
        return fractal($model, new UserTransformer())->respond();

    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = User::byUuid($id)->firstOrFail();
        $model->update($data);
        $model->setAvatar($data['avatar'] ?? null);
        return fractal($model->fresh(), new UserTransformer())->respond();
    }


}
