<?php

namespace kernel\app_modules\user_custom_fields;

use Illuminate\Database\Eloquent\Model;
use itguild\forms\builders\SelectBuilder;
use itguild\forms\builders\TextInputBuilder;
use kernel\app_modules\tag\models\Tag;
use kernel\app_modules\tag\service\TagEntityService;
use kernel\app_modules\user_custom_fields\models\CustomField;
use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
use kernel\app_modules\user_custom_fields\services\CustomFieldService;
use kernel\app_modules\user_custom_fields\services\UserCustomValuesService;
use kernel\EntityRelation;
use kernel\helpers\Debug;
use kernel\Module;
use kernel\modules\menu\service\MenuService;
use kernel\Request;
use kernel\services\MigrationService;

class UserCustomFieldsModule extends Module
{

    public MenuService $menuService;

    public MigrationService $migrationService;

    public function __construct()
    {
        $this->menuService = new MenuService();
        $this->migrationService = new MigrationService();
    }

    public function init(): void
    {
        $this->migrationService->runAtPath("{KERNEL_APP_MODULES}/user_custom_fields/migrations");

        $this->menuService->createItem([
            "label" => "Доп. поля пользователей",
            "url" => "/admin/custom_field",
            "slug" => "custom_field",
        ]);

        $this->menuService->createItem([
            "label" => "Список",
            "url" => "/admin/custom_field",
            "slug" => "custom_field_list",
            "parent_slug" => "custom_field"
        ]);

        $this->menuService->createItem([
            "label" => "Значения",
            "url" => "/admin/custom_field/user_values",
            "slug" => "custom_field_user_values",
            "parent_slug" => "custom_field"
        ]);

        EntityRelation::addEntityRelation('user', 'user_custom_fields');
    }

    /**
     * @throws \Exception
     */
    public function deactivate(): void
    {
        $this->migrationService->rollbackAtPath("{KERNEL_APP_MODULES}/user_custom_fields/migrations");
        $this->menuService->removeItemBySlug("custom_field_user_values");
        $this->menuService->removeItemBySlug("custom_field_list");
        $this->menuService->removeItemBySlug("custom_field");

        EntityRelation::removePropertyFromEntityRelations('user', 'user_custom_fields');
    }

    public function formInputs(string $entity, Model $model = null): void
    {
        $fields = CustomFieldService::getCustomFields();

        foreach ($fields as $field) {
            /* @var CustomField $field */
            if (isset($model->id)) {
                $value = UserCustomValuesService::getValueByFieldAndUser($field->id, $model->id);
            }

            if ($field->type === "string"){
                $input = TextInputBuilder::build($field->slug, [
                    'class' => 'form-control',
                    'placeholder' => $field->label,
                    'value' => $value->value ?? '',
                ]);
            }
            else {
                $options = explode(", ", $field->field_options);
                $options = array_combine($options, $options);
                $input = SelectBuilder::build($field->slug, [
                    'class' => 'form-control',
                    'placeholder' => $field->label,
                    'value' => $value->value ?? '',
                ])->setOptions($options);
            }
            $input->setLabel($field->label);
            $input->create()->render();
        }
    }

    public function saveInputs(string $entity, Model $model, Request $request): void
    {
        $service = new UserCustomValuesService();
        $form = new CreateUserCustomValueForm();
        $fields = CustomFieldService::getCustomFields();

        foreach ($fields as $field){
            /* @var CustomField $field */
            if (isset($request->data[$field->slug])){
                UserCustomValuesService::deleteByUserAndField($model->id, $field->id);
                $form->load([
                    'user_id' => $model->id,
                    'custom_field_id' => $field->id,
                    'value' => $request->data[$field->slug]
                ]);
                $service->create($form);
            }
        }
    }

    public function getItem(string $entity, string $entity_id): string
    {
        $fields = UserCustomValuesService::getValuesByUserId($entity_id);
        $fieldsArr = [];
        foreach ($fields as $field){
            /* @var UserCustomValues $field */
            $fieldsArr[$field->customField->label] = $field->value;
        }
        $string = implode(', ', array_map(
            function ($key, $value) {
                return "$key: $value";
            },
            array_keys($fieldsArr),
            $fieldsArr
        ));

        return $string;
    }

    public function getItems(string $entity, Model $model): string
    {
        $fields = UserCustomValuesService::getValuesByUserId($model->id);
        $fieldsArr = [];
        foreach ($fields as $field){
            /* @var UserCustomValues $field */
            $fieldsArr[$field->customField->label] = $field->value;
        }
        $string = implode(', ', array_map(
            function ($key, $value) {
                return "$key: $value";
            },
            array_keys($fieldsArr),
            $fieldsArr
        ));

        return $string;
    }
}