<?php

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

/**
 * 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 = Model\ObjectType::instance($this->db)
                        ->load($_POST['context'])
                        ->get_row_value('isys_obj_type__id');
                    $ciTypeAssigner = CMDBModel\CiTypeCategoryAssigner::instance($this->db);
                    $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.
                    Model\ObjectType::instance($this->db)
                        ->dismissGlobalCategoriesFromObjectType($dismissGlobalCategories, $objectTypeID);
                    Model\ObjectType::instance($this->db)
                        ->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  null
     */
    public function &handle_module_request(isys_module_request $p_modreq)
    {
        parent::handle_module_request($p_modreq);

        $categories = [];

        $categoryDao = Model\Category::instance($this->db);
        $objectTypeDao = Model\ObjectType::instance($this->db);
        $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[isys_application::instance()->container->get('language')
                ->get($row['isysgui_catg__title']) . '_g' . $row['isysgui_catg__id']] = [
                'id'          => $row['isysgui_catg__id'],
                'type'        => 'g',
                'const'       => $row['isysgui_catg__const'],
                'title'       => isys_application::instance()->container->get('language')
                    ->get($row['isysgui_catg__title']) ?: isys_application::instance()->container->get('language')
                    ->get('LC__NAVIGATION__BREADCRUMB__NO_TITLE'),
                'visible'     => in_array($row['isysgui_catg__id'], $assignedGlobalCategories),
                'selfdefined' => false
            ];
        }

        while ($row = $customCategoryResult->get_row()) {
            $categories[isys_application::instance()->container->get('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_application::instance()->container->get('language')
                    ->get($row['isysgui_catg_custom__title']) ?: isys_application::instance()->container->get('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     => C__MODULE__SYSTEM,
            C__GET__MODULE_SUB_ID => C__MODULE__CUSTOM_FIELDS,
            C__GET__TREE_NODE     => C__MODULE__CUSTOM_FIELDS . 1
        ];

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

        die;
    }
}
