<?php

use idoit\Component\Property\Property;
use idoit\Module\Pro\Model\AttributeSettings;

/**
 * i-doit
 *
 * Popup class for attribute-settings feature.
 *
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_popup_attribute_setting_edit extends isys_component_popup
{
    public const VISIBILITY__VISIBLE = 0;
    public const VISIBILITY__HIDDEN = 1;
    public const VISIBILITY__HIDDEN_ON_OVERVIEW = 2;

    /**
     * @param isys_component_template $template
     * @param array                   $parameters
     *
     * @return string
     */
    public function handle_smarty_include(isys_component_template $template, $parameters)
    {
        return '<button type="button" class="btn btn-secondary mr5" data-action="edit" data-tooltip="1" onclick="' . $this->process_overlay('', 550, '70%', ['id' => $parameters['id']], null, null, 400, null, 800) . '" title="' . $this->language->get('LC__UNIVERSAL__EDIT') . '">' .
            '<img src="' . rtrim(isys_application::instance()->www_path, '/') . '/images/axialis/basic/tool-pencil.svg" alt="" />' .
            '</button>';
    }

    /**
     * @param isys_module_request $moduleRequest
     *
     * @return void
     * @throws \idoit\Exception\JsonException
     */
    public function &handle_module_request(isys_module_request $moduleRequest)
    {
        $attributeSettingsModel = AttributeSettings::instance($this->database);
        $parameters = isys_format_json::decode(base64_decode($_POST['params']));
        $routeGenerator = isys_application::instance()->container->get('route_generator');

        $attributeSettingId = (int)$parameters['id'];
        $attributeSetting = $attributeSettingsModel->getById($attributeSettingId);

        if (!$attributeSetting) {
            throw new Exception('The attribute setting ID does not exist!');
        }

        [$categoryConstant, $propertyKey] = explode('::', $attributeSetting['propertyReference']);

        $categoryDao = $attributeSettingsModel->getCategoryDaoByConstant($categoryConstant);
        $property = $categoryDao->get_property_by_key($propertyKey);

        if (is_array($property)) {
            $property = Property::createInstanceFromArray($property);
        }

        $validationOption = isys_format_json::decode($attributeSetting['validationOption']);

        $rules = [
            'C__ATTRIBUTE_SETTING__HIDDEN'                => [
                'p_arData'        => [
                    self::VISIBILITY__VISIBLE => 'LC__ATTRIBUTE_SETTINGS__VISIBILITY__VISIBLE',
                    self::VISIBILITY__HIDDEN => 'LC__ATTRIBUTE_SETTINGS__VISIBILITY__HIDDEN',
                    self::VISIBILITY__HIDDEN_ON_OVERVIEW => 'LC__ATTRIBUTE_SETTINGS__VISIBILITY__HIDDEN_ON_OVERVIEW'
                ],
                'p_strClass'      => 'input-small',
                'p_strSelectedID' => $attributeSetting['visible'] ? ($attributeSetting['visibleOverview'] ? self::VISIBILITY__VISIBLE : self::VISIBILITY__HIDDEN_ON_OVERVIEW) : self::VISIBILITY__HIDDEN,
                'p_bDbFieldNN'    => true,
            ],
            'C__ATTRIBUTE_SETTING__MANDATORY'              => [
                'p_bChecked'        => $attributeSetting['mandatory'] ?? 0,
                'p_bInfoIconSpacer' => false,
                'p_strTitle'        => 'LC__ATTRIBUTE_SETTINGS__MANDATORY'
            ],
            'C__ATTRIBUTE_SETTING__UNIQUE_PER_OBJECT'      => [
                'p_bChecked'        => $attributeSetting['uniqueObject'] ?? 0,
                'p_bInfoIconSpacer' => false,
                'p_strTitle'        => 'LC__ATTRIBUTE_SETTINGS__UNIQUE_OBJECT'
            ],
            'C__ATTRIBUTE_SETTING__UNIQUE_PER_OBJECT_TYPE' => [
                'p_bChecked'        => $attributeSetting['uniqueObjectType'] ?? 0,
                'p_bInfoIconSpacer' => false,
                'p_strTitle'        => 'LC__ATTRIBUTE_SETTINGS__UNIQUE_OBJECT_TYPE'
            ],
            'C__ATTRIBUTE_SETTING__UNIQUE_GLOBAL'          => [
                'p_bChecked'        => $attributeSetting['uniqueGlobal'] ?? 0,
                'p_bInfoIconSpacer' => false,
                'p_strTitle'        => 'LC__ATTRIBUTE_SETTINGS__UNIQUE_GLOBAL'
            ],
            'C__ATTRIBUTE_SETTING__VALIDATION'             => [
                'p_arData'        => [
                    'FILTER_VALIDATE_INT'    => 'LC__SETTINGS__CMDB__VALIDATION__TYPE_INT',
                    'FILTER_VALIDATE_FLOAT'  => 'LC__SETTINGS__CMDB__VALIDATION__TYPE_FLOAT',
                    'FILTER_VALIDATE_REGEXP' => 'LC__SETTINGS__CMDB__VALIDATION__TYPE_REGEX',
                    'FILTER_VALIDATE_EMAIL'  => 'LC__SETTINGS__CMDB__VALIDATION__TYPE_EMAIL',
                    'FILTER_VALIDATE_URL'    => 'LC__SETTINGS__CMDB__VALIDATION__TYPE_URL',
                    'VALIDATE_BY_TEXTFIELD'  => 'LC__SETTINGS__CMDB__VALIDATION__BY_TEXTFIELD'
                ],
                'p_strClass'      => 'input-medium',
                'p_strSelectedID' => $attributeSetting['validation'] ?? -1,
                'p_bDbFieldNN'    => false,
                'p_bSort'         => false,
            ],
            'C__ATTRIBUTE_SETTING__VALIDATION_REGEX'       => [
                'p_strClass'       => 'input-medium',
                'p_strPlaceholder' => 'LC__SETTINGS__CMDB__VALIDATION__REGEX_LABEL',
                'p_strValue'       => $validationOption['options']['regexp'] ?? '',
            ],
            'C__ATTRIBUTE_SETTING__VALIDATION_TEXTFIELD'       => [
                'p_strClass'       => 'input-medium',
                'p_strValue'       => $validationOption['value'] ?? '',
            ],
            'C__ATTRIBUTE_SETTING__VALIDATION_TEXTFIELD_AS_DROPDOWN'       => [
                'p_bChecked'        => (int) ($validationOption['as-select'] ?? false),
                'p_strTitle'        => 'LC__ATTRIBUTE_SETTINGS__EDIT_POPUP__TEXTAREA_AS_DROPDOWN',
            ]
        ];

        $propertyOptions = $attributeSettingsModel->getPropertyOptions($attributeSetting['propertyReference'], $property);

        // Display the dialog template and return it.
        $this->template
            ->activate_editmode()
            ->assign('isUnhideable', $propertyOptions['isUnhideable'])
            ->assign('isMultivalued', $categoryDao->is_multivalued())
            ->assign('isViewOnly', !($propertyOptions['isReadonly'] || $propertyOptions['isVirtual']))
            ->assign('isValidationAllowed', !$propertyOptions['isReadonly'] && $propertyOptions['canBeValidated'])
            ->assign('popupEditTitle', $this->language->get('LC__ATTRIBUTE_SETTINGS__EDIT_POPUP__TITLE', htmlentities($this->language->get($property->getInfo()->getTitle()))))
            ->assign('editAttributeSettingUrl', $routeGenerator->generate('pro.attribute-settings.edit-attribute-setting', ['id' => $attributeSettingId]))
            ->smarty_tom_add_rules('tom.popup.attribute-settings.edit', $rules)
            ->display(isys_module_pro::getPath() . 'templates/SettingPage/AttributeSettings/popup/edit.tpl');
        die;
    }
}
