<?php

use idoit\Module\QCW\Model\Category;
use idoit\Module\QCW\Model\ObjectType;
use idoit\Module\QCW\Model\ObjectTypeGroup;

/**
 * i-doit
 *
 * QCW object type adjuster popup.
 *
 * @package     Modules
 * @subpackage  QCW
 * @author      Leonard Fischer <lfischer@i-doit.com>
 * @version     1.0.0
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 * @since       i-doit 1.8.0
 */
class isys_popup_qcw_adjust_object_type extends isys_popup_qcw_adjust
{
    /**
     * Handle specific ajax requests.
     *
     * @param   isys_module_request $p_modreq
     *
     * @return  mixed
     * @author  Leonard Fischer <lfischer@i-doit.org>
     */
    public function &handle_ajax_request(isys_module_request $p_modreq)
    {
        header('Content-Type: application/json');

        $response = [
            'success' => true,
            'data'    => null,
            'message' => null
        ];

        try {
            switch ($_POST['action']) {
                case 'save':
                    $dao = ObjectType::instance($this->database);
                    $data = isys_format_json::decode($_POST['data']);
                    $objectTypeGroupID = ObjectTypeGroup::instance($this->database)
                        ->load($_POST['context'])
                        ->get_row_value('isys_obj_type_group__id');

                    foreach ($data as &$item) {
                        if ($item['detached']) {
                            $item['objectTypeGroup'] = 0;
                        }

                        if ($item['visible']) {
                            $item['objectTypeGroup'] = $objectTypeGroupID;
                        }
                    }

                    $response['data'] = array_merge($dao->saveMultiple($data), $dao->deleteMultiple(isys_format_json::decode($_POST['deleted'])));

                    if ($dao->getCreateCounter() || $dao->getDeleteCounter()) {
                        $this->clear_system_cache();
                    }
                    break;
            }
        } catch (Exception $e) {
            $response['success'] = false;
            $response['message'] = $e->getMessage();
        }

        echo \isys_format_json::encode($response);
        die;
    }

    /**
     * Method for handling the module request.
     *
     * @param  isys_module_request $p_modreq
     *
     * @return null
     * @throws isys_exception_database
     */
    public function &handle_module_request(isys_module_request $p_modreq)
    {
        parent::handle_module_request($p_modreq);

        $defaultTemplates = $objectTypes = $specificCategories = [];

        $i = 0;
        $daoCategory = Category::instance($this->database);
        $daoObjectType = ObjectType::instance($this->database);
        $templateDao = isys_templates_dao::instance($this->database);
        $objectTypeGroupID = ObjectTypeGroup::instance($this->database)
            ->load($_POST['currentObjectTypeGroup'])
            ->get_row_value('isys_obj_type_group__id');

        $result = $daoObjectType->load();

        if (count($result)) {
            while ($row = $result->get_row()) {
                $objectTypes[$this->language->get($row['isys_obj_type__title']) . (++$i)] = [
                    'id'                   => $row['isys_obj_type__id'],
                    'const'                => $row['isys_obj_type__const'],
                    'cats'                 => $row['isys_obj_type__isysgui_cats__id'] ?: -1,
                    'template'             => $row['isys_obj_type__default_template'] ?: -1,
                    'title'                => $this->language->get($row['isys_obj_type__title']),
                    'titleOrig'            => $row['isys_obj_type__title'],
                    'objectTypeGroupTitle' => ($row['isys_obj_type__isys_obj_type_group__id'] == $objectTypeGroupID ? '' : ($this->language->get($row['isys_obj_type_group__title']) ?: ' - ')),
                    'color'                => isys_helper_color::unifyHexColor((string)$row['isys_obj_type__color']),
                    'container'            => $row['isys_obj_type__container'],
                    'insertion'            => $row['isys_obj_type__show_in_rack'],
                    'visible'              => $row['isys_obj_type__isys_obj_type_group__id'] == $objectTypeGroupID,
                    'disableDelete'        => !$row['isys_obj_type__selfdefined'],
                    'disableMove'          => ((int)$objectTypeGroupID === C__OBJTYPE_GROUP__ORPHANED && (int)$row['isys_obj_type__isys_obj_type_group__id'] === C__OBJTYPE_GROUP__ORPHANED),
                    'selfdefined'          => (bool)$row['isys_obj_type__selfdefined'],
                    'detached'             => false
                ];
            }

            ksort($objectTypes);
        }

        $result = $daoCategory->loadSpecific();

        if (count($result)) {
            while ($row = $result->get_row()) {
                $categories = [];
                $objectTypeResults = $daoObjectType->loadObjectTypesBySpecificCategory($row['isysgui_cats__id'], 5);

                if (count($objectTypeResults)) {
                    while ($objectTypeRow = $objectTypeResults->get_row()) {
                        $categories[] = $this->language->get($objectTypeRow['isys_obj_type__title']);
                    }
                }

                // We use a string inside the key, because otherwise javascript would destroy our sorting.
                $specificCategories['cats' . $row['isysgui_cats__id']] = $this->language->get($row['isysgui_cats__title']) .
                    (count($categories) ? ' (' . implode(', ', $categories) . ')' : '');
            }
        }

        asort($specificCategories);

        $result = $templateDao->get_templates();

        if (count($result)) {
            while ($row = $result->get_row()) {
                $defaultTemplates[$row['isys_obj__id']] = $row['isys_obj__title'];
            }
        }

        $this->template->assign('data', isys_format_json::encode(array_values($objectTypes)))
            ->assign('additionalData', isys_format_json::encode(['defaultTemplates' => $defaultTemplates, 'specificCategories' => $specificCategories]))
            ->assign('context', $_POST['currentObjectTypeGroup'])
            ->display(isys_module_quick_configuration_wizard::getPath() . 'templates/popup/popupQcwAdjustObjectType.tpl');

        die;
    }
}
