<?php

namespace App\Services\Forms\Users;

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

class UserPasswordForms 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' => 'current_password',
                'title' => 'Текущий пароль',
                'type' => FieldType::STRING,
                'appearance' => 'password',
                'required' => true
            ],
            [
                'name' => 'password',
                'title' => 'Новый пароль',
                'type' => FieldType::STRING,
                'appearance' => 'password',
                'required' => true
            ],
            [
                'name' => 'confirmation',
                'title' => 'Подтверждение пароля',
                'type' => FieldType::STRING,
                'appearance' => 'password',
                'required' => true
            ]
        ];
        return ['data' => $fields];
    }



    public function store(array $data): void {
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = User::byUuid($id)->firstOrFail();
        //Validator::make($data, []);
        if (!$model->checkPassword($data['current_password'])) $this->error('current_password', 'Текущий пароль указан неверно');
        if (($data['password']) !== ($data['confirmation'])) $this->error('confirmation', 'Пароль и подтверждение пароля не совпадают');
        if (!$this->errors) {
            $model->setPassword($data['password']);
            return fractal($model, new UserTransformer())->respond();
        } else return response()->json($this->errors, 422);
    }

    public function error($field, $message) {
        $this->errors[$field][] = $message;
    }


}
