<?php

namespace App\Services\Forms\Advisories;

use App\Models\Advisories\Advisory;
use App\Models\Advisories\AdvisoryMemberRank;
use App\Models\Advisories\AdvisoryType;
use App\Models\Companies\CompanyMember;
use App\Models\Objects\FieldType;
use App\Services\Forms\FormsService;
use App\Transformers\Advisories\AdvisoryTransformer;
use App\Transformers\Assets\AssetTransformer;
use App\Transformers\Companies\CompanyMemberTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;

class AdvisoryGroupForms extends FormsService {
    public array $formTitles = ['create' => 'Добавление направления', 'update' => 'Редактирование направления'];

    public function form(?string $id = null, array $data = []): array {
        $model = Advisory::byUuid($id)->first();
        return [
            'title' => $this->formTitle($model),
            'frames' => [
                ['title' => 'Общие сведения', 'groups' => $this->form1Groups($model)]
            ]
        ];
    }

    public function form1Groups(?Advisory $model): array {
        $groups = [
            ['name' => 'common', 'title' => '', 'fields' => $this->commonGroupFields($model)]
        ];
        return ['data' => $groups];
    }

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


    public function store(array $data): JsonResponse {
        $parent = Advisory::byUuid($data['parent'] ?? null)->firstOrFail();
        $data['name'] = $this->makeName($data);
        $model = $parent->children()->create(collect($data)->only('name', 'title')->all());
        $model->setLogo($data['logo'] ?? null);
        return fractal($model, new AdvisoryTransformer())->respond(201);
    }

    public function update(string $id, array $data): JsonResponse {
        $model = Advisory::byUuid($id)->firstOrFail();
        $data['name'] = $this->makeName($data);
        $model->update(collect($data)->only('name', 'title')->all());
        $model->setLogo($data['logo'] ?? null);
        return fractal($model->fresh(), new AdvisoryTransformer())->respond();
    }

    public function makeName($data): string {
        return Str::slug(Str::transliterate($data['title'] ?? ''));
    }

}
