<?php

namespace idoit\Module\System\Controller;

use idoit\Controller\Responseable;
use idoit\Exception\Exception;
use idoit\Module\System\Model\AttributeVisibility;
use isys_application as Application;
use isys_array;
use isys_cmdb_dao_category;
use isys_format_json;
use isys_format_json as JSON;
use isys_module_cmdb;
use isys_register as Register;
use isys_tenantsettings;

/**
 * Ajax Controller
 *
 * @package     Modules
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class AjaxAttributeVisibility extends Main implements Responseable
{
    /**
     * @var array
     */
    protected $response = [
        'success' => false,
        'data' => [],
        'message' => ''
    ];

    /**
     * Overwriting the "handle" method.
     *
     * @param Register    $request
     * @param Application $application
     *
     * @return  null
     */
    public function handle(Register $request, Application $application)
    {
        return null;
    }

    /**
     * @param Application $application
     *
     * @return AttributeVisibility
     */
    public function dao(Application $application)
    {
        return AttributeVisibility::instance($application->container->get('database'));
    }

    /**
     * @param Register $request
     */
    public function getProperties(Register $request)
    {
        $post = $request->get('POST');
        $dao = $this->dao(Application::instance());
        $language = Application::instance()->container->get('language');
        $categoryInstance = $dao->getCategoryInstanceByConstant($post['id']);

        if ($categoryInstance === null) {
            $this->response['success'] = false;
            $this->response['message'] = 'Category DAO does not exist.';
            return;
        }

        $properties = $dao->getProperties($categoryInstance);
        $this->response['data'] = [
            'title' => $language->get($categoryInstance->getCategoryTitle()),
            'properties' => $properties
        ];
    }

    /**
     * @param Register $request
     *
     * @throws \idoit\Exception\JsonException
     */
    public function saveConfig(Register $request)
    {
        /**
         * @var isys_array $data
         */
        $postData = $request->get('POST');
        $dao = $this->dao(Application::instance());
        $currentConfig = $dao->getConfig();
        try {
            if (isset($postData['configuration'])) {
                $config = $postData['configuration'];
                if (isys_format_json::is_json($config)) {
                    $config = isys_format_json::decode($config);
                }
                foreach ($config as $categoryConstant => $data) {
                    unset($currentConfig[$categoryConstant]);
                    $dao->saveConfig($categoryConstant, $data['properties']);
                }
            }

            if (!empty($currentConfig)) {
                $categoryConstants = array_keys($currentConfig);
                $dao->removeConfig($categoryConstants);
            }

            if (isset($postData['configuration']) || !empty($currentConfig)) {
                isys_tenantsettings::force_save();
            }

            if (isset($postData['removeRequiredFields'])) {
                $removeRequiredFields = $postData['removeRequiredFields'];
                if (isys_format_json::is_json($removeRequiredFields)) {
                    $removeRequiredFields = isys_format_json::decode($removeRequiredFields);
                }
                $this->dao(Application::instance())->unsetMandatoryFields($removeRequiredFields);
            }
        } catch (Exception $e) {
            $this->response['success'] = false;
            $this->response['message'] = $e->getMessage();
        }
    }

    /**
     * @param Register $request
     *
     * @throws \idoit\Exception\JsonException
     */
    public function loadConfig(Register $request)
    {
        $post = $request->get('POST');
        $categoryConstant = $post['categoryConstant'] ?: null;
        $response = AttributeVisibility::getAttributeVisibilityForCategories($categoryConstant);

        $this->response['data'] = $response;
    }

    /**
     * Pre method gets called by the framework.
     */
    public function pre()
    {
        header('Content-Type: application/json');

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

    /**
     * Post method gets called by the framework.
     */
    public function post()
    {
        echo JSON::encode($this->response);
        die;
    }

    /**
     * @return array
     */
    public function getResponse()
    {
        return $this->response;
    }
}
