<?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 AdvisoryForms 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)],
              //  ['title' => 'Руководство', 'groups' => $this->form2Groups($model)]
            ]
        ];
    }

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

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

    public function commonGroupFields(?Advisory $model): array {
        $fields = [
            [
                'name' => 'type',
                'title' => 'Тип подразделения',
                'type' => FieldType::RELATION,
                'required' => true,
                'appearance' => 'radio',
                'options' => $this->getRelationItems(AdvisoryType::TITLES),
                'value' => $this->getRelationValue(AdvisoryType::TITLES, $model->type ?? null)
            ],
            [
                'name' => 'title',
                'title' => 'Название подразделения',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->title ?? null
            ],
            [
                'name' => 'number',
                'title' => 'Обозначение подразделения',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->number ?? null
            ],
            [
                'name' => 'email',
                'title' => 'Электронная почта',
                'type' => FieldType::STRING,
                'value' => $model->email ?? null
            ],
            [
                'name' => 'phone',
                'title' => 'Телефон',
                'type' => FieldType::STRING,
                'value' => $model->phone ?? null
            ],
            [
                'name' => 'director_name',
                'title' => 'Руководитель',
                'type' => FieldType::STRING,
                'value' => $model->director_name ?? null
            ],
            [
                'name' => 'secretary_name',
                'title' => 'Секретарь',
                'type' => FieldType::STRING,
                'value' => $model->secretary_name ?? null
            ],
            [
                'name' => 'document',
                'title' => 'Списочный состав',
                'type' => FieldType::DOCUMENT,
                'value' => ($model->document ?? null) ? fractal($model->document, new AssetTransformer()) : null
            ],
            /*
            [
                'name' => 'logo',
                'title' => 'Логотип',
                'type' => FieldType::IMAGE,
                'value' => ($model->logo ?? null) ? fractal($model->logo, new AssetTransformer()) : null
            ]
            */
        ];
        return ['data' => $fields];
    }

    public function managementGroupFields(?Advisory $model): array {
        $fields = [
            [
                'name' => 'chairman',
                'title' => 'Руководитель',
                'type' => FieldType::RELATION,
                //'required' => true,
                'options' => fractal(CompanyMember::all(), new CompanyMemberTransformer()),
                'value' => ($val = $model->chairman ?? null) ? fractal($val, new CompanyMemberTransformer()) : null
            ],
            [
                'name' => 'vices',
                'title' => 'Заместители',
                'type' => FieldType::RELATION,
                'multiple' => true,
                'options' => fractal(CompanyMember::all(), new CompanyMemberTransformer()),
                'value' => $model ? fractal($model->chairmanVices, new CompanyMemberTransformer()) : null
            ],
            [
                'name' => 'secretary',
                'title' => 'Ответственный секретарь',
                'type' => FieldType::RELATION,
                //'required' => true,
                'options' => fractal(CompanyMember::all(), new CompanyMemberTransformer()),
                'value' => ($val = $model->secretary ?? null) ? fractal($val, new CompanyMemberTransformer()) : null
            ],
            [
                'name' => 'assistants',
                'title' => 'Помощники секретаря',
                'type' => FieldType::RELATION,
                'multiple' => true,
                'options' => fractal(CompanyMember::all(), new CompanyMemberTransformer()),
                'value' => $model ? fractal($model->secretaryAssistants, new CompanyMemberTransformer()) : null
            ]
        ];
        return ['data' => $fields];
    }



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

    public function update(string $id, array $data): JsonResponse {
        $model = Advisory::byUuid($id)->firstOrFail();
        $this->updateData($model, $data);
        return fractal($model->fresh(), new AdvisoryTransformer())->respond();
    }

    public function updateData(Advisory $model, $data) {
        $data['name'] = $this->makeName($data);
        $model->update(collect($data)->only('type', 'name', 'title', 'number', 'email', 'phone', 'director_name', 'secretary_name')->all());
        $this->syncMembers($model, $data);
        $model->setLogo($data['logo'] ?? null);
        $model->setDocument($data['document'] ?? null);
    }

    public function makeName($data): string {
        $val = $data['number'] ?? $data['title'] ?? '';
        return Str::lower(Str::replace(' ', '', Str::transliterate($val)));
    }


    public function syncMembers(Advisory $model, $data) {
        $ranksByFields = ['chairman' => AdvisoryMemberRank::CHAIRMAN, 'vices' => AdvisoryMemberRank::VICE_CHAIRMAN,
            'secretary' => AdvisoryMemberRank::SECRETARY, 'assistants' => AdvisoryMemberRank::SECRETARY_ASSISTANT, 'ordinary' => AdvisoryMemberRank::ORDINARY];
        collect($ranksByFields)->each(function($rank, $field) use($model, $data) {
            if (array_key_exists($field, $data)) $model->syncMembers(CompanyMember::byUuids($data[$field])->get(), $rank);
        });
    }


}
