<?php

namespace idoit\Module\CustomFields\Controller;

use idoit\Component\Helper\Unserialize;
use isys_application;
use isys_custom_fields_dao;
use isys_module_custom_fields;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class TechnicalConfigurationController
{
    /**
     * @param Request $request
     * @param int     $id
     * @return JsonResponse
     */
    public function modal(Request $request, int $id): JsonResponse
    {
        try {
            $template = isys_application::instance()->container->get('template');
            $dao = isys_custom_fields_dao::instance(isys_application::instance()->container->get('database'));

            $row = $dao->get_data($id)->get_row();
            $configuration = Unserialize::toArray($row['isysgui_catg_custom__config']);

            $template
                ->assign('apiExample', $this->prepareApiExample($configuration, $row['isysgui_catg_custom__const']))
                ->assign('apiExampleConfig', $this->prepareApiExampleConfig($configuration));

            return new JsonResponse([
                'success' => true,
                'message' => '',
                'data'    => $template->fetch(isys_module_custom_fields::getPath() . 'templates/popup/technical-configuration.tpl'),
            ]);
        } catch (\Exception $e) {
            return new JsonResponse([
                'success' => false,
                'message' => $e->getMessage(),
                'data'    => null,
            ]);
        }
    }

    /**
     * @param array  $configuration
     * @param string $categoryConstant
     * @return array|array[]
     */
    private function prepareApiExample(array $configuration, string $categoryConstant): array
    {
        $apiExample = [
            'method'  => 'cmdb.category.save',
            'params'  => [
                'language' => isys_application::instance()->language,
                'apikey'   => 'your-key',
                'category' => $categoryConstant,
                'object'   => 1234,
                'data'     => []
            ],
            'id'      => 1,
            'version' => '2.0'
        ];

        if (is_array($configuration)) {
            foreach ($configuration as $key => $field) {
                // @see  API-201 / ID-7100  Skip properties that don't contain data.
                if (in_array($field['type'], ['html', 'hr', 'script'], true)) {
                    continue;
                }

                // Specific case for 'report'.
                if ($field['type'] === 'f_popup' && $field['popup'] === 'report_browser') {
                    continue;
                }

                $apiExample['params']['data'][$field['type'] . '_' . $key] = $this->getExampleContent($field);
            }
        }

        $return = [
            'create' => $apiExample,
            'read' => $apiExample
        ];

        $return['read']['method'] = 'cmdb.category.read';
        unset($return['read']['params']['data']);

        return $return;
    }

    /**
     * @param array $field
     * @return mixed
     */
    private function getExampleContent(array $field): mixed
    {
        $multiselection = isset($field['multiselection']) && $field['multiselection'];

        switch ($field['type']) {
            case 'f_time':
                return date('H:i');

            case 'f_numeric':
                return (string) (rand(1000, 9999) / 100);

            case 'f_wysiwyg':
                return 'HTML textual-content';

            case 'f_link':
            case 'f_password':
            case 'f_text':
            case 'f_textarea':
                return 'textual-content';

            case 'f_dialog':
                if ($field['extra'] === 'yes-no') {
                    return rand(0, 1);
                }

                return rand(1, 10);

            case 'f_popup':
                if ($field['popup'] === 'dialog_plus' || $field['popup'] === 'checkboxes') {
                    $randomInt = rand(1, 10);

                    if ($multiselection) {
                        return [$randomInt, $randomInt + rand(1, 10), $randomInt + rand(11, 20)];
                    }

                    return $randomInt;
                }

                if ($field['popup'] === 'browser_object' || $field['popup'] === 'file') {
                    $randomInt = rand(100, 200);

                    if ($multiselection) {
                        return [$randomInt, $randomInt + rand(1, 100), $randomInt + rand(101, 200)];
                    }

                    return $randomInt;
                }

                if ($field['popup'] === 'calendar') {
                    if ($field['default'] == '1') {
                        return date('Y-m-d H:i:s');
                    }

                    return date('Y-m-d');
                }

                // no break
            default:
                return null;
        }
    }

    /**
     * @param array $configuration
     * @return array
     */
    private function prepareApiExampleConfig(array $configuration): array
    {
        return array_filter($configuration, fn ($config) => !in_array($config['type'], ['html', 'hr', 'script'], true));
    }
}
