<?php

use idoit\Module\Pro\Model\CategoryFolders\Category;
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_move 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
     *
     * @throws \idoit\Exception\JsonException
     * @throws isys_exception_database
     */
    public function &handle_module_request(isys_module_request $p_modreq)
    {
        // Unpack popup request.
        $parameters = isys_format_json::decode(base64_decode($_POST['params']));

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

        $selectedId = (int) ($parameters['parentId'] ?? $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('data', [
                'configurationId' => (int)$parameters['configurationId'],
                'objectTypeId'    => (int)$parameters['objectTypeId'],
                'currentParentId' => $selectedId,
                'isFolder'        => $parameters['itemType'] === 'folder',
                'isCategory'      => $parameters['itemType'] === 'category',
                'itemId'          => (int)preg_replace('~[^0-9]~', '', $parameters['itemId'])
            ])
            ->assign('loadConfigUrl', $routeGenerator->generate('pro.category-folders.load-config', ['objectTypeId' => (int)$parameters['objectTypeId']]))
            ->assign('moveItemUrl', $routeGenerator->generate('pro.category-folders.move-item'))
            ->display(dirname(__DIR__) . '/templates/SettingPage/CategoryFolders/popup/move-item.tpl');
        die;
    }
}
