<?php

namespace App\Services\Forms\Users;

use App\Events\UserRegistered;
use App\Models\Objects\FieldType;
use App\Models\Role;
use App\Models\User;
use App\Services\Forms\FormsService;
use App\Transformers\Assets\AssetTransformer;
use App\Transformers\Users\RoleTransformer;
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' => 'position',
                'title' => 'Должность',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->position ?? null
            ],
            [
                'name' => 'phone',
                'title' => 'Телефон',
                'type' => FieldType::STRING,
                'value' => $model->phone ?? null
            ],
            [
                'name' => 'role',
                'title' => 'Полномочия',
                'type' => FieldType::RELATION,
                'required' => true,
                'appearance' => 'radio',
                'options' => fractal(Role::all(), new RoleTransformer()),
                'value' => ($v = $model->role ?? null) ? fractal($v, new RoleTransformer()) : null
            ],
            [
                'name' => 'avatar',
                'title' => 'Фотография профиля',
                'type' => FieldType::IMAGE,
                'value' => ($v = $model->avatar ?? null) ? fractal($v, 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(collect($data)->only('name', 'position', 'phone')->all());
        $model->setAvatar($data['avatar'] ?? null);
        $model->syncRoles($data['role'] ?? null);
        $this->checkEmail($model, $data['email'] ?? null);
        return fractal($model->fresh(), new UserTransformer())->respond();
    }

    public function checkEmail(User $model, $email) {
        if ($email && ($email !== $model->email) && !User::byEmail($email)->withTrashed()->exists()) {
            $model->update(['email' => $email]);
            $password = User::makeDefaultPassword();
            $model->setPassword($password);
            event(new UserRegistered($model, $password));
        }
    }

}
