<?php

namespace idoit\Module\SyneticsJdisc\Controller;

use Exception;
use idoit\Module\SyneticsJdisc\Model\JDiscProfileDao;
use idoit\Module\SyneticsJdisc\Model\JDiscServerDao;
use isys_application;
use isys_component_filemanager;
use isys_exception_general;
use isys_format_json as JSON;
use isys_module_synetics_jdisc;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

class PopupController
{
    public function columnSettingsModal(string $id): JsonResponse
    {
        global $g_dirs;
        $response = [
            'success' => true,
            'data'    => null,
            'message' => '',
        ];

        try {
            $response['data'] = isys_application::instance()->container->get('template')
                ->assign('dirImages', $g_dirs['images'])
                ->assign('cssPath', isys_module_synetics_jdisc::getPath() . 'assets/css/sync-profile-column-settings.css')
                ->fetch(isys_module_synetics_jdisc::getPath() . 'templates/popup/sync-profile-column-settings.tpl');
        } catch (\Throwable $exception) {
            $response['success'] = false;
            $response['message'] = $exception->getMessage();
        }

        return new JsonResponse($response);
    }

    public function importProfileModal(): JsonResponse
    {
        $response = [
            'success' => true,
            'data'    => null,
            'message' => '',
        ];

        try {
            $rules = [
                'C__JDISC_PROFILES__MERGE_PROFILES' => [
                    'p_arData'     => get_smarty_arr_YES_NO(),
                    'p_bDbFieldNN' => true,
                    'p_strClass'   => 'input-mini'
                ],
                'C__JDISC_PROFILES__UPLOAD'         => [
                    'p_strClass' => 'input-block'
                ]
            ];

            $response['data'] = isys_application::instance()->container->get('template')
                ->activate_editmode()
                ->assign('redirectUrl', isys_application::instance()->container->get('request')->request->get('redirectUrl'))
                ->smarty_tom_add_rules('tom.popup.profilesImport', $rules)
                ->fetch(isys_module_synetics_jdisc::getPath() . 'templates/popup/popupImport.tpl');

        } catch (\Throwable $exception) {
            $response['success'] = false;
            $response['message'] = $exception->getMessage();
        }

        return new JsonResponse($response);
    }

    public function duplicateProfileModal(Request $request)
    {
        $response = [
            'success' => true,
            'data'    => null,
            'message' => '',
        ];
        $template = isys_application::instance()->container->get('template');
        $language = isys_application::instance()->container->get('language');

        try {
            $profileIds = $request->query->get('ids');
            if ($profileIds) {
                $profileIds = JSON::decode($profileIds);
            }

            if (empty($profileIds)) {
                throw new Exception(isys_application::instance()->container->get('language')->get('LC__MODULE__JDISC__POPUP__ERROR__NO_SELECTED_PROFILE'));
            }

            $dao = JDiscProfileDao::instance(isys_application::instance()->container->get('database'));
            $result = $dao->getProfileList($profileIds);

            $profiles = [];
            while ($row = $result->get_row()) {
                $profiles[] = [
                    'id' => "C__PROFILE__{$row['isys_jdisc_profile__id']}",
                    'title' => $row['isys_jdisc_profile__title']
                ];
            }
            if (empty($profiles)) {
                throw new isys_exception_general('No profile found.');
            }

            $template->assign('items', $profiles);
        } catch (Throwable $e) {
            $template->assign('error', $e->getMessage());
        }

        try {
            $response['data'] = $template
                ->activate_editmode()
                ->assign('modalTitle', $language->get('LC__MODULE__JDISC__DUPLICATE_PROFILES'))
                ->assign('cssPath', isys_module_synetics_jdisc::getPath() . 'assets/css/duplicate-modal.css')
                ->fetch(isys_module_synetics_jdisc::getPath() . 'templates/popup/duplicate-modal.tpl');

        } catch (\Throwable $exception) {
            $response['success'] = false;
            $response['message'] = $exception->getMessage();
        }

        return new JsonResponse($response);
    }

    public function duplicateServerModal(Request $request)
    {
        $response = [
            'success' => true,
            'data'    => null,
            'message' => '',
        ];
        $template = isys_application::instance()->container->get('template');
        $language = isys_application::instance()->container->get('language');

        try {
            $serverIds = $request->query->get('ids');
            if ($serverIds) {
                $serverIds = JSON::decode($serverIds);
            }

            if (empty($serverIds)) {
                throw new Exception(isys_application::instance()->container->get('language')->get('LC__MODULE__JDISC__POPUP__ERROR__NO_SELECTED_SERVERS'));
            }

            $dao = JDiscServerDao::instance(isys_application::instance()->container->get('database'));
            $result = $dao->getServerList($serverIds);

            $profiles = [];
            while ($row = $result->get_row()) {
                $profiles[] = [
                    'id' => "C__SERVER__{$row['isys_jdisc_db__id']}",
                    'title' => $row['isys_jdisc_db__title']
                ];
            }
            if (empty($profiles)) {
                throw new isys_exception_general('No server found.');
            }

            $template->assign('items', $profiles);
        } catch (Throwable $e) {
            $template->assign('error', $e->getMessage());
        }

        try {
            $response['data'] = $template
                ->activate_editmode()
                ->assign('modalTitle', $language->get('LC__MODULE__JDISC__DUPLICATE_SERVERS'))
                ->assign('cssPath', isys_module_synetics_jdisc::getPath() . 'assets/css/duplicate-modal.css')
                ->fetch(isys_module_synetics_jdisc::getPath() . 'templates/popup/duplicate-modal.tpl');

        } catch (\Throwable $exception) {
            $response['success'] = false;
            $response['message'] = $exception->getMessage();
        }

        return new JsonResponse($response);
    }
}
