<?php

use \idoit\Module\QCW\Model as Model;

/**
 * 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 = Model\ObjectType::instance($this->db);
                    $data = isys_format_json::decode($_POST['data']);
                    $objectTypeGroupID = Model\ObjectTypeGroup::instance($this->db)
                        ->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
     */
    public function &handle_module_request(isys_module_request $p_modreq)
    {
        parent::handle_module_request($p_modreq);

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

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

        $result = $daoObjectType->load();

        if (count($result)) {
            while ($row = $result->get_row()) {
                $objectTypes[isys_application::instance()->container->get('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'                => isys_application::instance()->container->get('language')
                        ->get($row['isys_obj_type__title']),
                    'titleOrig'            => $row['isys_obj_type__title'],
                    'objectTypeGroupTitle' => ($row['isys_obj_type__isys_obj_type_group__id'] ==
                    $objectTypeGroupID ? '' : (isys_application::instance()->container->get('language')
                        ->get($row['isys_obj_type_group__title']) ?: ' - ')),
                    'color'                => $row['isys_obj_type__color'] ?: 'ffffff',
                    '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'],
                    'selfdefined'          => !!$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[] = isys_application::instance()->container->get('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']] = isys_application::instance()->container->get('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->tpl->assign('data', isys_format_json::encode(array_values($objectTypes)))
            ->assign('additionalData', isys_format_json::encode(['defaultTemplates' => $defaultTemplates, 'specificCategories' => $specificCategories]))
            ->assign('context', $_POST['currentObjectTypeGroup'])
            ->display(dirname(dirname(__DIR__)) . '/templates/popup/popupQcwAdjustObjectType.tpl');

        die;
    }
}
