<?php

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_edit extends isys_component_popup
{
    /**
     * Handles SMARTY request for dialog plus lists and builds the list base on the specified table.
     *
     * @param   isys_component_template & $p_tplclass
     * @param   array                   $p_params
     *
     * @return  string
     */
    public function handle_smarty_include(isys_component_template &$p_tplclass, $p_params)
    {
        // Will be accessed directly via JS.
        return '';
    }

    /**
     * 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']));
        $configurationId = (int)$parameters['configurationId'];
        $folderId = (int)$parameters['itemId'];

        if (!$folderId) {
            throw new Exception('The selected folder could not be found!');
        }

        $folderModel = Folder::instance($this->database);
        $folder = $folderModel->getById($folderId);

        if ($folder === null) {
            throw new Exception('The selected folder could not be found!');
        }

        $parent = $folderModel->getById($folder['parent']);

        $l_rules = [
            'C__CATEGORY_FOLDERS__FOLDER_ID'       => [
                'p_strValue' => $folderId
            ],
            'C__CATEGORY_FOLDERS__FOLDER_NAME'     => [
                'p_strClass'       => 'input-small',
                'p_strValue'       => $folder['title'],
                'p_bNoTranslation' => true
            ],
            'C__CATEGORY_FOLDERS__FOLDER_LOCATION' => [
                'p_strPopupType'     => 'category_folders_selection',
                'disableInputGroup'  => 'true',
                'preventSelectionOf' => $folderId,
                'configId'           => $configurationId,
                'objectTypeId'       => $parameters['objectTypeId'],
                'folderId'           => $parent['id']
            ]
        ];

        // Display the dialog template and return it.
        $this->template
            ->activate_editmode()
            ->assign('popupHeadline', 'LC__CATEGORY_FOLDERS__EDIT_FOLDER')
            ->assign('folderUrl', isys_application::instance()->container->get('route_generator')->generate('pro.category-folders.edit-folder'))
            ->assign('configId', $configurationId)
            ->smarty_tom_add_rules('tom.popup.category-folders.create-folder', $l_rules)
            ->display(dirname(__DIR__) . '/templates/SettingPage/CategoryFolders/popup/update-folder.tpl');
        die;
    }
}
