<?php

use \idoit\Module\QCW\Model\Category;
use \idoit\Module\QCW\Model\ObjectType;
use \idoit\Module\Cmdb\Model\CiTypeCategoryAssigner;

/**
 * i-doit
 *
 * QCW category 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_category 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':
                    $data = isys_format_json::decode($_POST['data']);
                    $objectTypeID = ObjectType::instance($this->database)
                        ->load($_POST['context'])
                        ->get_row_value('isys_obj_type__id');
                    $ciTypeAssigner = CiTypeCategoryAssigner::instance($this->database);
                    $assignGlobalCategories = $dismissGlobalCategories = $assignCustomCategories = $dismissCustomCategories = [];

                    foreach ($data as $item) {
                        if ($item['type'] === 'g') {
                            if ($item['visible']) {
                                $assignGlobalCategories[] = $item['id'];
                            } else {
                                $dismissGlobalCategories[] = $item['id'];
                            }
                        }

                        if ($item['type'] === 'c') {
                            if ($item['visible']) {
                                $assignCustomCategories[] = $item['id'];
                            } else {
                                $dismissCustomCategories[] = $item['id'];
                            }
                        }
                    }

                    // We'll receive ALL global and custom category assignments - thus remove all, before we assign them.
                    ObjectType::instance($this->database)->dismissGlobalCategoriesFromObjectType($dismissGlobalCategories, $objectTypeID);
                    ObjectType::instance($this->database)->dismissCustomCategoriesFromObjectType($dismissCustomCategories, $objectTypeID);

                    // Use the awesome CI-type-assigner :)
                    $ciTypeAssigner->setCiTypes([$objectTypeID])
                        ->setDefaultCategories()
                        ->setGlobalCategories($assignGlobalCategories)
                        ->setCustomCategories($assignCustomCategories)
                        ->assign();

                    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  void
     * @throws  isys_exception_database
     */
    public function &handle_module_request(isys_module_request $p_modreq)
    {
        parent::handle_module_request($p_modreq);

        $categories = [];

        $categoryDao = Category::instance($this->database);
        $objectTypeDao = ObjectType::instance($this->database);
        $objectTypeID = $objectTypeDao->load($_POST['currentObjectType'])->get_row_value('isys_obj_type__id');
        $globalCategoryResult = $categoryDao->loadGlobal();
        $customCategoryResult = $categoryDao->loadCustom();
        $assignedGlobalCategories = $objectTypeDao->getAssignedGlobalCategoriesByObjectType($objectTypeID);
        $assignedCustomCategories = $objectTypeDao->getAssignedCustomCategoriesByObjectType($objectTypeID);

        while ($row = $globalCategoryResult->get_row()) {
            $categories[$this->language->get($row['isysgui_catg__title']) . '_g' . $row['isysgui_catg__id']] = [
                'id'          => $row['isysgui_catg__id'],
                'type'        => 'g',
                'const'       => $row['isysgui_catg__const'],
                'title'       => $this->language->get($row['isysgui_catg__title']) ?: $this->language->get('LC__NAVIGATION__BREADCRUMB__NO_TITLE'),
                'visible'     => in_array($row['isysgui_catg__id'], $assignedGlobalCategories),
                'selfdefined' => false
            ];
        }

        while ($row = $customCategoryResult->get_row()) {
            $categories[$this->language->get($row['isysgui_catg_custom__title']) . '_c' . $row['isysgui_catg_custom__id']] = [
                'id'          => $row['isysgui_catg_custom__id'],
                'type'        => 'c',
                'const'       => $row['isysgui_catg_custom__const'],
                'title'       => isys_glob_htmlentities($this->language->get($row['isysgui_catg_custom__title']) ?: $this->language->get('LC__NAVIGATION__BREADCRUMB__NO_TITLE')),
                'visible'     => in_array($row['isysgui_catg_custom__id'], $assignedCustomCategories),
                'selfdefined' => true
            ];
        }

        ksort($categories);

        $customCategoryURL = [
            C__GET__MODULE_ID     => defined_or_default('C__MODULE__SYSTEM'),
            C__GET__MODULE_SUB_ID => defined_or_default('C__MODULE__CUSTOM_FIELDS'),
            C__GET__TREE_NODE     => defined_or_default('C__MODULE__CUSTOM_FIELDS '). 1
        ];

        $this->template->assign('data', isys_format_json::encode(array_values($categories)))
            ->assign('context', $_POST['currentObjectType'])
            ->assign('customCategoryURL', isys_helper_link::create_url($customCategoryURL))
            ->display(isys_module_quick_configuration_wizard::getPath() . 'templates/popup/popupQcwAdjustCategory.tpl');

        die;
    }
}
