<?php

use idoit\Module\Pro\Model\CategoryFolders\Config;
use idoit\Module\Pro\Model\CategoryFolders\Folder;

/**
 * i-doit
 *
 * Popup class for category folders feature.
 *
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_popup_category_folders_selection extends isys_component_popup
{
    /**
     * Handles SMARTY request for dialog plus lists and builds the list base on the specified table.
     *
     * @param   isys_component_template &$smarty
     * @param   array                   $parameters
     *
     * @return  string
     */
    public function handle_smarty_include(isys_component_template &$smarty, $parameters)
    {
        $folderModel = Folder::instance($this->database);

        $root = $folderModel->getRootByConfig((int)$parameters['configId']);
        $root['id'] = (int) $root['id'];

        $selectedTitle = $root['title'];
        $selectedId = (int) ($parameters['folderId'] ?? $root['id']);

        $hiddenFieldOptions = [
            'id'                => $parameters['name'] . '_HIDDEN',
            'p_bInvisible'      => true,
            'p_strValue'        => isys_format_json::encode([
                'configId'           => (int)$parameters['configId'],
                'targetField'        => $parameters['name'] . '_HIDDEN',
                'preventSelectionOf' => $parameters['preventSelectionOf'],
                'folderId'           => $selectedId,
                'isRoot'             => $selectedId === $root['id']
            ]),
            'disableInputGroup' => 'true',
            'p_bInfoIconSpacer' => 0,
        ];

        if ($selectedId !== $root['id']) {
            $selectedTitle = $folderModel->getById($selectedId)['title'];
        }

        $fieldOptions = [
            'id'                => $parameters['name'] . '_FIELD',
            'p_strClass'        => 'input-small',
            'disableInputGroup' => 'true',
            'p_bInfoIconSpacer' => 0,
            'p_bDisabled'       => true,
            'p_strValue'        => $selectedTitle,
        ];

        $buttonOptions = [
            'id'                => $parameters['name'] . '_BUTTON',
            'icon'              => isys_application::instance()->www_path . 'images/axialis/documents-folders/folder-copy-2-grey.svg',
            'p_bInfoIconSpacer' => 0,
            'p_onClick'         => $this->getModalJs('', 720, 600, [], 720, 600, $hiddenFieldOptions['id']),
            'type'              => 'button',
            'p_strValue'        => 'LC__CATEGORY_FOLDERS__POPUP__SELECT_FOLDER__MOVE',
            'p_strClass'        => 'ml10',
            'p_strStyle'        => ' '
        ];

        $checkboxName = $parameters['name'] . '_ROOT_CHECKBOX';

        $checkbox = '<div class="mt5"><label>' .
            '<input type="checkbox" id="' . $checkboxName . '" name="' . $checkboxName . '" ' . ($selectedId === $root['id'] ? 'checked ' : '') . ($selectedId === $root['id'] ? 'disabled ' : '') . ' />' .
            '<span class="ml5">' . $this->language->get('LC__CATEGORY_FOLDERS__POPUP__SELECT_FOLDER__ROOT_NO_PARENT') . '</span>' .
            '</label></div>';

        // This javascript is used for the checkbox behaviour.
        $javascript = "<script>
            const rootConfig = JSON.parse('" . isys_format_json::encode(['name' => $this->language->get($root['title']), 'id' => (int)$root['id']]) . "');
            const \$viewField = $('{$parameters['name']}_FIELD');
            const \$hiddenField = $('{$hiddenFieldOptions['id']}');
            const \$checkbox = $('{$checkboxName}');

            \$checkbox.on('change', function() {
                const hiddenData = JSON.parse(\$hiddenField.getValue());

                if (\$checkbox.checked) {
                    \$viewField.setValue(rootConfig.name);
                    hiddenData.folderId = rootConfig.id;
                    hiddenData.isRoot = true;
                    \$hiddenField.setValue(JSON.stringify(hiddenData));
                    \$checkbox.disable();
                }
            });
            </script>";

        return (new isys_smarty_plugin_f_text())->navigation_edit($this->template, $hiddenFieldOptions) .
            (new isys_smarty_plugin_f_text())->navigation_edit($this->template, $fieldOptions) .
            (new isys_smarty_plugin_f_button())->navigation_edit($this->template, $buttonOptions) . '<br />' .
            $checkbox . $javascript;
    }

    /**
     * Method for handling the module request.
     *
     * @param   isys_module_request     $p_modreq
     *
     * @return void
     * @throws \idoit\Exception\JsonException
     */
    public function &handle_module_request(isys_module_request $p_modreq)
    {
        // Unpack popup request.
        $parameters = isys_format_json::decode(base64_decode($_POST['params']));

        $configuration = Config::instance($this->database)->getById((int)$parameters['configId']);

        if ($configuration === null) {
            throw new Exception('The configuration does not exist!');
        }

        $root = Folder::instance($this->database)->getRootByConfig((int)$configuration['id']);
        $root['id'] = (int) $root['id'];

        $selectedId = (int) ($parameters['folderId'] ?? $root['id']);

        // Get the route generator.
        $routeGenerator = isys_application::instance()->container->get('route_generator');

        // Display the dialog template and return it.
        $this->template
            ->activate_editmode()
            ->assign('hiddenData', [
                'configId'           => (int)$configuration['id'],
                'objectTypeId'       => (int)$configuration['objectTypeId'],
                'targetField'        => $parameters['targetField'],
                'folderId'           => $selectedId,
                'isRoot'             => $selectedId === $root['id'],
                'preventSelectionOf' => $parameters['preventSelectionOf']
            ])
            ->assign('rootData', $root)
            ->assign('loadConfigUrl', $routeGenerator->generate('pro.category-folders.load-config', ['objectTypeId' => $configuration['objectTypeId']]))
            ->assign('targetField', $parameters['targetField'])
            ->display(dirname(__DIR__) . '/templates/SettingPage/CategoryFolders/popup/select-folder.tpl');
        die;
    }
}
