<?php

namespace idoit\Module\Pro\SettingPage\AttributeSettings;

use idoit\Module\Cmdb\Model\Ci\Table\Config;
use idoit\Module\Cmdb\Model\Ci\Table\Property;
use idoit\Module\Pro\Model\AttributeSettings as AttributeSettingsModel;
use idoit\Module\System\SettingPage\SettingPage;
use isys_application;
use isys_auth as Auth;
use isys_component_list;
use isys_component_template_navbar;
use isys_module_cmdb;
use isys_module_pro;
use isys_popup_attribute_setting_delete;
use isys_popup_attribute_setting_edit;
use isys_tenantsettings;

class AttributeSettings extends SettingPage
{
    private bool $canEdit = false;
    private bool $canDelete = false;

    /**
     * @param $navMode
     *
     * @return void
     * @throws \isys_exception_auth
     * @throws \isys_exception_database
     */
    public function renderPage($navMode)
    {
        isys_module_cmdb::getAuth()->check(Auth::VIEW, 'attribute_visibility');

        $canCreate = isys_module_cmdb::getAuth()->is_allowed_to(Auth::CREATE, 'attribute_visibility');
        $this->canEdit = isys_module_cmdb::getAuth()->is_allowed_to(Auth::EDIT, 'attribute_visibility');
        $this->canDelete = isys_module_cmdb::getAuth()->is_allowed_to(Auth::DELETE, 'attribute_visibility');

        isys_component_template_navbar::getInstance()
            ->hide_all_buttons()
            ->set_active($canCreate, C__NAVBAR_BUTTON__NEW)
            ->set_visible(true, C__NAVBAR_BUTTON__NEW)
            ->set_icon(isys_application::instance()->www_path . 'images/axialis/basic/symbol-add.svg', C__NAVBAR_BUTTON__NEW)
            ->set_title('LC__UNIVERSAL__ADD', C__NAVBAR_BUTTON__NEW)
            ->set_js_onclick("get_popup('attribute_setting_add', '', '60%', '80%', {params:'W10='}, null,'800','400',null,null);", C__NAVBAR_BUTTON__NEW)
            ->append_button('LC__UNIVERSAL__DELETE', '', [
                'active'              => $this->canDelete,
                'visible'             => true,
                'tooltip'             => null,
                'icon'                => 'axialis/industry-manufacturing/waste-bin.svg',
                'icon_inactive'       => 'axialis/industry-manufacturing/waste-bin.svg',
                'navmode'             => 'delete_multiple'
            ]);

        $this->tpl
            ->assign('content_title', $this->lang->get('LC__CMDB__TREE__SYSTEM__ATTRIBUTE_SETTINGS'))
            ->assign('cssPath', isys_module_pro::getPath() . 'assets/css/attribute-settings.css')
            ->assign('tableHtml', $this->renderTable())
            ->include_template('contentbottomcontent', isys_module_pro::getPath() . 'templates/SettingPage/AttributeSettings/config.tpl');
    }

    /**
     * @return string
     * @throws \idoit\Exception\JsonException
     * @throws \isys_exception_database
     */
    private function renderTable(): string
    {
        $data = [];
        $result = AttributeSettingsModel::instance($this->db)->getAll();

        while ($row = $result->get_row()) {
            $data[] = $this->rowModifier($row);
        }

        $tableConfig = (new Config())
            ->addProperty(new Property('action', '', 'action', 'LC__ATTRIBUTE_SETTINGS__ACTION', false, 0, 'text', false))
            ->addProperty(new Property('propertyTitle', '', 'propertyTitle', 'LC__ATTRIBUTE_SETTINGS__PROPERTY_TITLE', true, 0, 'text', true))
            ->addProperty(new Property('categoryTitle', '', 'categoryTitle', 'LC__ATTRIBUTE_SETTINGS__CATEGORY_TITLE', true, 0, 'text', true))
            ->addProperty(new Property('visibility', '', 'visibility', 'LC__ATTRIBUTE_SETTINGS__VISIBILITY', true, 0, 'text', true))
            ->addProperty(new Property('mandatory', '', 'mandatory', 'LC__ATTRIBUTE_SETTINGS__MANDATORY', true, 0, 'text', true))
            ->addProperty(new Property('uniqueObject', '', 'uniqueObject', 'LC__ATTRIBUTE_SETTINGS__UNIQUE_OBJECT', true, 0, 'text', true))
            ->addProperty(new Property('uniqueObjectType', '', 'uniqueObjectType', 'LC__ATTRIBUTE_SETTINGS__UNIQUE_OBJECT_TYPE', true, 0, 'text', true))
            ->addProperty(new Property('uniqueGlobal', '', 'uniqueGlobal', 'LC__ATTRIBUTE_SETTINGS__UNIQUE_GLOBAL', true, 0, 'text', true))
            ->addProperty(new Property('validation', '', 'validation', 'LC__ATTRIBUTE_SETTINGS__VALIDATION', true, 0, 'text', true))
            // Set the default sorting.
            ->setSortingProperty('propertyTitle')
            // @see ID-9782 Enable wildcard filters.
            ->setFilterWildcard(true);

        $table = isys_component_list::instance($this->db)
            ->set_data($data)
            ->disableResizeColumns() // @see ID-10552 No need for column resizing here.
            ->config([ /* Defining the fields is not necessary, if you create a custom table config */ ], '', '[{id}]', true, true, null, false, ($_GET['resetFilter'] ?? false))
            ->set_table_config($tableConfig);

        if (!$table->createTempTable()) {
            return '';
        }

        return $table->render();
    }

    /**
     * @param array $row
     *
     * @return void
     * @throws \isys_exception_database
     */
    private function rowModifier(array $row): array
    {
        [$categoryConstant, $propertyKey] = explode('::', $row['propertyReference']);

        $dao = AttributeSettingsModel::instance($this->db)->getCategoryDaoByConstant($categoryConstant);

        $property = $dao->get_property_by_key($propertyKey);

        $actionButtons = (new isys_popup_attribute_setting_edit())->handle_smarty_include($this->tpl, ['id' => $row['id'], 'disabled' => !$this->canEdit]) .
            (new isys_popup_attribute_setting_delete())->handle_smarty_include($this->tpl, ['ids' => "[{$row['id']}]", 'disabled' => !$this->canDelete]);

        return [
            'id'               => $row['id'],
            'action'           => $actionButtons,
            'propertyTitle'    => $this->lang->get($property[C__PROPERTY__INFO][C__PROPERTY__INFO__TITLE]),
            'categoryTitle'    => $this->lang->get($dao->getCategoryTitle()),
            'visibility'       => $this->getVisibilityString((bool)$row['visible'], (bool)$row['visibleOverview']),
            'mandatory'        => $this->getYesNoString((bool)$row['mandatory']),
            'uniqueObject'     => $this->getYesNoString((bool)$row['uniqueObject']),
            'uniqueObjectType' => $this->getYesNoString((bool)$row['uniqueObjectType']),
            'uniqueGlobal'     => $this->getYesNoString((bool)$row['uniqueGlobal']),
            'validation'       => $this->getValidationString($row['validation']),
        ];
    }

    /**
     * @param bool $visible
     * @param bool $visibleOverview
     *
     * @return string
     * @throws \Exception
     */
    private function getVisibilityString(bool $visible, bool $visibleOverview): string
    {
        $wwwPath = isys_application::instance()->www_path . 'images/axialis/basic';

        $icon = 'eye.svg';
        $message = 'LC__ATTRIBUTE_SETTINGS__VISIBILITY__VISIBLE';

        if (!$visible) {
            $icon = 'symbol-cancel.svg';
            $message = 'LC__ATTRIBUTE_SETTINGS__VISIBILITY__HIDDEN';
        } elseif (!$visibleOverview) {
            $icon = 'eye-no.svg';
            $message = 'LC__ATTRIBUTE_SETTINGS__VISIBILITY__HIDDEN_ON_OVERVIEW';
        }

        return '<div class="display-flex align-items-center">' .
            '<img src="' . $wwwPath . '/' . $icon . '" alt="" />' .
            '<span class="ml5">' . $this->lang->get($message) . '</span>' .
            '</div>';
    }

    /**
     * @param bool $setting
     *
     * @return string
     * @throws \Exception
     */
    private function getYesNoString(bool $setting): string
    {
        $wwwPath = isys_application::instance()->www_path . 'images/axialis/basic';

        $icon = 'symbol-ok.svg';
        $message = 'LC__UNIVERSAL__YES';

        if (!$setting) {
            $icon = 'symbol-cancel.svg';
            $message = 'LC__UNIVERSAL__NO';
        }

        return '<div class="display-flex align-items-center">' .
            '<img src="' . $wwwPath . '/' . $icon . '" alt="" /><span class="ml5">' . $this->lang->get($message) . '</span>' .
            '</div>';
    }

    /**
     * @param string|null $validation
     *
     * @return string
     */
    private function getValidationString(?string $validation): string
    {
        switch ($validation) {
            default:
                return isys_tenantsettings::get('gui.empty_value', '-');

            case 'FILTER_VALIDATE_INT':
                return $this->lang->get('LC__SETTINGS__CMDB__VALIDATION__TYPE_INT');

            case 'FILTER_VALIDATE_FLOAT':
                return $this->lang->get('LC__SETTINGS__CMDB__VALIDATION__TYPE_FLOAT');

            case 'FILTER_VALIDATE_REGEXP':
                return $this->lang->get('LC__SETTINGS__CMDB__VALIDATION__TYPE_REGEX');

            case 'FILTER_VALIDATE_EMAIL':
                return $this->lang->get('LC__SETTINGS__CMDB__VALIDATION__TYPE_EMAIL');

            case 'FILTER_VALIDATE_URL':
                return $this->lang->get('LC__SETTINGS__CMDB__VALIDATION__TYPE_URL');

            case 'VALIDATE_BY_TEXTFIELD':
                return $this->lang->get('LC__SETTINGS__CMDB__VALIDATION__BY_TEXTFIELD');
        }
    }
}
