<?php

namespace App\Services\Forms\Companies;

use App\Models\Companies\CompanyMember;
use App\Models\Companies\CompanyMemberRank;
use App\Models\Companies\CompanyMemberRole;
use App\Models\Companies\Department;
use App\Models\Dictionaries\Dictionary;
use App\Models\Objects\FieldType;
use App\Models\Pages\Page;
use App\Models\User;
use App\Services\Forms\FormsService;
use App\Transformers\Companies\CompanyMemberTransformer;
use App\Transformers\Companies\DepartmentTransformer;
use App\Transformers\Dictionaries\DictionaryItemTransformer;
use App\Transformers\Pages\PageTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class CompanyMemberForms extends FormsService {
    public array $formTitles = ['create' => 'Добавление сотрудника организации', 'update' => 'Редактирование сотрудника'];

    public function form(?string $id = null, array $data = []): array {
        $department = Department::byUuid($data['department'] ?? null)->first();
        $model = CompanyMember::byUuid($id)->first();
        $company = $model->company ?? $department->company;
        $user = Auth::user();
        $frames = [['title' => 'Общие сведения', 'groups' => $this->form1Groups($model)]];
        if (($company->is_main ?? null) && $user->isAdmin) $frames[] = ['title' => 'Полномочия', 'groups' => $this->form2Groups($model)];
        return ['title' => $this->formTitle($model), 'frames' => $frames];
    }

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

    public function form2Groups(?CompanyMember $model): array {
        $groups = [
            ['name' => 'permissions', 'title' => '', 'fields' => $this->permissionsGroupFields($model),
                'dynamic' => [
                    ['field' => 'role', 'hide' => ['moderate-pages']],
                    ['field' => 'role', 'value' => CompanyMemberRole::MODERATOR, 'show' => ['moderate-pages']]
                ]
            ]
        ];
        return ['data' => $groups];
    }


    public function commonGroupFields(?CompanyMember $model): array {
        $fields = [
            [
                'name' => 'email',
                'title' => 'Email',
                'type' => FieldType::STRING,
                'required' => true,
                'readonly' => !!$model && !Auth::user()->isPrivileged,
                'value' => $model->user->email ?? null
            ],
            [
                'name' => 'name',
                'title' => 'ФИО',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $model->user->name ?? null
            ],
            [
                'name' => 'position',
                'title' => 'Должность',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->position ?? null
            ],
            [
                'name' => 'phone',
                'title' => 'Телефон',
                'type' => FieldType::STRING,
                'value' => $model->user->phone ?? null
            ],
            [
                'name' => 'room',
                'title' => 'Кабинет',
                'type' => FieldType::STRING,
                'value' => $model->room ?? null
            ],
            [
                'name' => 'intercom',
                'title' => 'Внутренний телефон',
                'type' => FieldType::STRING,
                'value' => $model->intercom ?? null
            ]
            /*
            [
                'name' => 'rank',
                'title' => 'Ранг сотрудника',
                'type' => FieldType::RELATION,
                'required' => true,
                'appearance' => 'radio',
                'options' => $this->getRelationItems(CompanyMemberRank::TITLES),
                'value' => $model ? $model->parsedRank + ['id' => $model->rank] : null
            ],
            [
                'name' => 'representative',
                'title' => 'Назначить администратором',
                'type' => FieldType::BOOLEAN,
                'value' => $model->representative ?? null
            ]
            */
        ];
        /*
        if ($model) $fields[] = [
            'name' => 'department',
            'title' => 'Отдел',
            'type' => FieldType::RELATION,
            'options' => fractal($model->company->departments ?? [], new DepartmentTransformer()),
            'value' => $model ? fractal($model->department, new DepartmentTransformer()) : null
        ];
        */

        return ['data' => $fields];
    }

    public function permissionsGroupFields(?CompanyMember $model): array {
        $fields = [
            [
                'name' => 'role',
                'title' => 'Роль',
                'type' => FieldType::RELATION,
                'required' => true,
                'appearance' => 'radio',
                'options' => $this->getRelationItems(CompanyMemberRole::TITLES),
                'value' => $this->getRelationValue(CompanyMemberRole::TITLES, $model->role ?? null)
            ],
            [
                'name' => 'moderate-pages',
                'title' => 'Разделы сайта',
                'type' => FieldType::RELATION,
                'multiple' => true,
                'options' => fractal(Page::all(), new PageTransformer()),
                'value' => $model ? fractal($model->properties->getValue('moderate-pages'), new PageTransformer()) : null
            ],
            [
                'name' => 'moderate-permissions',
                'title' => 'Права',
                'type' => FieldType::RELATION,
                'multiple' => true,
                'appearance' => 'checkbox',
                'options' => fractal(Dictionary::byName('moderate-permissions')->first()->items, new DictionaryItemTransformer()),
                'value' => $model ? fractal($model->properties->getValue('moderate-permissions'), new DictionaryItemTransformer()) : null
            ],
        ];

        return ['data' => $fields];
    }



    public function store(array $data): ?JsonResponse {
        if (($department = Department::byUuid($data['department'] ?? null)->first()) && ($user = User::getByData(collect($data)->except('role')->all(), true))) {
            $model = $department->addMember($user, $data['position'] ?? null);
            $model->update(['position' => $data['position'] ?? null, 'role' => $data['role'] ?? null, 'room' => $data['room'] ?? null, 'intercom' => $data['intercom'] ?? null]);
            $model->properties->setValues($data);
            return fractal($model, new CompanyMemberTransformer())->respond();
        }
    }

    public function update(string $id, array $data): ?JsonResponse {
        $model = CompanyMember::byUuid($id)->firstOrFail();
        $model->update(['position' => $data['position'] ?? null, 'role' => $data['role'] ?? null, 'room' => $data['room'] ?? null, 'intercom' => $data['intercom'] ?? null]);
        if ($department = Department::byUuid($data['department'] ?? null)->first()) $model->update(['department_id' => $department->id]);
        $model->user->update(['name' => $data['name'] ?? null, 'phone' => $data['phone'] ?? null]);
        if (($email = $data['email'] ?? null) && !User::query()->where(['email' => $email])->exists()) $model->user->update(['email' => $data['email']]);
        $model->properties->setValues($data);
        return fractal($model->fresh(), new CompanyMemberTransformer())->respond();
    }


}
