<?php

namespace App\Services\Forms\Companies;

use App\Models\Companies\Department;
use App\Models\Objects\FieldType;
use App\Services\Forms\FormsService;
use App\Transformers\Companies\DepartmentTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;

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

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

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



    public function store(array $data): ?JsonResponse {
        $parent = Department::byUuid($data['department'] ?? null)->firstOrFail();
        if ($title = trim($data['title'] ?? null)) {
            $model = $parent->addChildren(Str::transliterate($title), $title);
            return fractal($model, new DepartmentTransformer())->respond();
        }
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = Department::byUuid($id)->firstOrFail();
        if ($val = trim($data['title'] ?? null)) {
            $model->update(['title' => $val]);
            if ($model->name !== 'root') $model->update(['name' => Str::transliterate($val)]);
        }
        return fractal($model, new DepartmentTransformer())->respond();
    }


}
