<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @author     Markus Domin, Helge Nissen <markus.domin@fh-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Settingspage
{
    private $settings;

    private $title = 'TrainOn';
    private $subtitle = 'Einstellungen für Trainings';
    private $setting_admin_label = 'trainingssystem-setting-admin';
    //private $option_name = TRAININGSSYSTEM_PLUGIN_SETTINGS; //'trainingssystem_option_name';
    //private $option_group = TRAININGSSYSTEM_PLUGIN_SETTINGS . '_group';

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     */
    public function __construct()
    {
        add_action('admin_menu', array($this, 'add_plugin_page'));
        add_action('wp_ajax_saveSettings', array($this, 'saveSettings'));
    }

    /**
     * Add options page.
     */
    public function add_plugin_page()
    {
        // This page will be under "Settings"
        add_options_page(
            $this->title,
            '' . $this->title,
            'manage_options',
            '' . $this->setting_admin_label,
            array($this, 'create_admin_page')
        );
    }

    /**
     * Options page callback.
     */
    public function create_admin_page()
    {

        $posts = get_terms('nav_menu');
        $arrayAllMenusId = array();
        $arrayAllMenus = array();
        $arrayAllPagesId = array();
        $arrayAllPages = array();
        $nonceaction_createdemodata = TRAININGSSYSTEM_PLUGIN_SLUG . 'createdemodata';
        $noncefield = TRAININGSSYSTEM_PLUGIN_SLUG . 'createdemodata';
        $default_pages = Trainingssystem_Plugin_Module_Demodata::$demoCreatePages;

        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);

        /**
         * LIME-SURVEY Einstellungen
         */
        // General
        if (!isset($settings['limesurvey_rpc_url']) || trim($settings['limesurvey_rpc_url']) == "") {
            $settings['limesurvey_rpc_url'] = '';
        }
        if (!isset($settings['limesurvey_rpc_username']) || trim($settings['limesurvey_rpc_username']) == "") {
            $settings['limesurvey_rpc_username'] = '';
        }
        if (!isset($settings['limesurvey_rpc_password']) || trim($settings['limesurvey_rpc_password']) == "") {
            $settings['limesurvey_rpc_password'] = '';
        }
        // 2nd Mail
        if (!isset($settings['limesurvey_days_till_second_survey_email']) || trim($settings['limesurvey_days_till_second_survey_email']) == "") {
            $settings['limesurvey_days_till_second_survey_email'] = 42;
        }
        if (!isset($settings['limesurvey_second_survey_email_subject']) || trim($settings['limesurvey_second_survey_email_subject']) == "") {
            $settings['limesurvey_second_survey_email_subject'] = $this->loadLimesurveyEmailSubject('limesurvey_second_survey_email.xml');
        }
        if (!isset($settings['limesurvey_second_survey_email_body']) || trim($settings['limesurvey_second_survey_email_body']) == "") {
            $settings['limesurvey_second_survey_email_body'] = $this->loadLimesurveyEmailBody('limesurvey_second_survey_email.xml');
        }
        // 2nd Mail Reminder
        if (!isset($settings['limesurvey_days_till_second_survey_email_reminder']) || trim($settings['limesurvey_days_till_second_survey_email_reminder']) == "") {
            $settings['limesurvey_days_till_second_survey_email_reminder'] = 3;
        }
        if (!isset($settings['limesurvey_second_survey_email_reminder_subject']) || trim($settings['limesurvey_second_survey_email_reminder_subject']) == "") {
            $settings['limesurvey_second_survey_email_reminder_subject'] = $this->loadLimesurveyEmailSubject('limesurvey_second_survey_email_reminder.xml');
        }
        if (!isset($settings['limesurvey_second_survey_email_reminder_body']) || trim($settings['limesurvey_second_survey_email_reminder_body']) == "") {
            $settings['limesurvey_second_survey_email_reminder_body'] = $this->loadLimesurveyEmailBody('limesurvey_second_survey_email_reminder.xml');
        }
        // 3rd Mail
        if (!isset($settings['limesurvey_days_till_third_survey_email']) || trim($settings['limesurvey_days_till_third_survey_email']) == "") {
            $settings['limesurvey_days_till_third_survey_email'] = 182;
        }
        if (!isset($settings['limesurvey_third_survey_email_subject']) || trim($settings['limesurvey_third_survey_email_subject']) == "") {
            $settings['limesurvey_third_survey_email_subject'] = $this->loadLimesurveyEmailSubject('limesurvey_third_survey_email.xml');
        }
        if (!isset($settings['limesurvey_third_survey_email_body']) || trim($settings['limesurvey_third_survey_email_body']) == "") {
            $settings['limesurvey_third_survey_email_body'] = $this->loadLimesurveyEmailBody('limesurvey_third_survey_email.xml');
        }
        // 3rd Mail Reminder
        if (!isset($settings['limesurvey_days_till_third_survey_email_reminder']) || trim($settings['limesurvey_days_till_third_survey_email_reminder']) == "") {
            $settings['limesurvey_days_till_third_survey_email_reminder'] = 3;
        }
        if (!isset($settings['limesurvey_third_survey_email_reminder_subject']) || trim($settings['limesurvey_third_survey_email_reminder_subject']) == "") {
            $settings['limesurvey_third_survey_email_reminder_subject'] = $this->loadLimesurveyEmailSubject('limesurvey_third_survey_email_reminder.xml');
        }
        if (!isset($settings['limesurvey_third_survey_email_reminder_body']) || trim($settings['limesurvey_third_survey_email_reminder_body']) == "") {
            $settings['limesurvey_third_survey_email_reminder_body'] = $this->loadLimesurveyEmailBody('limesurvey_third_survey_email_reminder.xml');
        }

        $allPages = get_posts([
            'post_type' => 'page',
            'numberposts' => -1,
        ]);

        $allMenus = get_posts([
            'post_type' => 'nav_menu_item',
            'numberposts' => -1,
        ]);

        $post_type_object = get_post_type_object('nav_menu_item');
        $labelNav = $post_type_object->label;

        array_push($arrayAllMenus, 'nicht zugewiesen');
        array_push($arrayAllMenusId, 0);

        foreach ($posts as $post) {
            array_push($arrayAllMenusId, $post->term_id);
            array_push($arrayAllMenus, $post->name);
        }
        $arrayAllMenus = array_map(null, $arrayAllMenus, $arrayAllMenusId);

        $post_type_object = get_post_type_object('page');
        $labelPage = $post_type_object->label;

        array_push($arrayAllPagesId, 0);
        array_push($arrayAllPages, 'nicht zugewiesen');

        foreach ($allPages as $allPage) {
            array_push($arrayAllPagesId, $allPage->ID);
            array_push($arrayAllPages, $allPage->post_title);
        }
        $arrayAllPages = array_map(null, $arrayAllPages, $arrayAllPagesId);

        $lists = array(
            "nicht anzeigen" => -1,
            "Links oben" => 0,
            "Links unten" => 1,
            "Rechts oben" => 2,
            "Rechts unten" => 3,
        );

        $allRegisterCodes = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getAll();
        $registerCodes = array();
        
        foreach($allRegisterCodes as $allRegisterCode){
            if(empty($allRegisterCode->getCompany()) && empty($allRegisterCode->getCompanygroup())){
                $registerCodes[] = $allRegisterCode;
            }
        }
        
        $studiengruppenid_meta = get_users(array("meta_key" => 'studiengruppenid'));
        $sg_ids = [];
        foreach($studiengruppenid_meta as $sg_meta) {
            if(trim($sg_meta->studiengruppenid) != "") {
                $sg_ids[$sg_meta->studiengruppenid] = $sg_meta->studiengruppenid;
            }
        }

        $args = ['orderby' => 'display_name', 'order' => 'ASC'];
        $args['meta_key'] = 'vorlagenuser';
        $args['meta_compare'] = "NOT EXISTS";
        $allUsers = get_users($args);

        $firsts = array();
        $user_events_level_default = array();
        $user_events_level = Trainingssystem_Plugin_Database::getInstance()->UserEvent::$level;
        foreach($user_events_level as $l) {
            $firsts[$l] = true;
            $user_events_level_default[$l] = null;
        }

        $user_events_settings = Trainingssystem_Plugin_Database::getInstance()->UserEvent->getSettings();
        foreach($user_events_settings as $type => $levels) {
            foreach($levels as $level => $value) {
                if($firsts[$level] || (!is_null($user_events_level_default[$level]) && $user_events_level_default[$level] == $value && !is_null($value))) {
                    $user_events_level_default[$level] = $value;
                    $firsts[$level] = false;
                } else {
                    $user_events_level_default[$level] = null;
                }
            }
        }
        foreach($user_events_level_default as $dl => $v) {
            if(is_null($v) || trim($v) == "")
                $user_events_level_default[$dl] = null;
        }

        $demoUser = array("demoUser" => array(), "registeredUser" => array());
        $user_args = array(
            'meta_key' => 'demo_user',
            'meta_value' => '1',
            'meta_compare' => '=',
            'number' => -1
        );
        $user_query = new WP_User_Query($user_args);
        $demoUserIds = [];
        foreach($user_query->get_results() as $du) {
            $demoUserIds[] = $du->ID;
        }
        $demoUser['demoUser'] = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyNutzer(false, $demoUserIds);
        $user_args = array(
            'meta_key' => 'demo_user',
            'meta_value' => '0',
            'meta_compare' => '=',
            'number' => -1
        );
        $user_query = new WP_User_Query($user_args);
        $registeredUserIds = [];
        foreach($user_query->get_results() as $ru) {
            $registeredUserIds[] = $ru->ID;
        }
        $demoUser['registeredUser'] = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyNutzer(false, $registeredUserIds);
        
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        echo $twig->render('admin-backend-settings/admin-backend-settings.html', [
            "pages" => $default_pages,
            "submitnonce" => wp_nonce_field($nonceaction_createdemodata, $noncefield, true, false),
            "settings" => $settings,
            "title" => $this->title,
            "subtitle" => $this->subtitle,
            "arrayAllPages" => $arrayAllPages,
            "arrayAllMenus" => $arrayAllMenus,
            "lists" => $lists,
            "adjustmenulink" => "",
            "registerCodes" => $registerCodes,
            "studiengruppen" => $sg_ids,
            "user_events_level" => $user_events_level,
            "user_events_types" => Trainingssystem_Plugin_Database::getInstance()->UserEvent::$types,
            "user_events_settings" => $user_events_settings,
            "user_events_settings_default" => $user_events_level_default,
            "allUsers" => $allUsers,
            "currentDemoAccounts" => count($demoUser['demoUser']),
            "demoUser" => $demoUser,
        ]);
    }

    public function saveSettings()
    {
        $settings_old = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);

        $user_args = array(
            'meta_key' => 'demo_user',
            'meta_value' => '1',
            'meta_compare' => '=',
            'number' => -1
        );
        $user_query = new WP_User_Query($user_args);
        $demoUserIds = [];
        foreach($user_query->get_results() as $du) {
            $demoUserIds[] = $du->ID;
        }
        
        if(count($demoUserIds) > 0 && $_POST['setting']['privacy_terms_URL'] != $settings_old['privacy_terms_URL']) {
                echo "not allowed";
                wp_die();
        }

        $int_fields = array("mailbox_notification_interval", "system_user_id", "logout_time", "globalInactivity", "demologin_registerkey", "demologin_autodelete", "demologin_maxaccounts");
        $bool_fields = array("training_gridview", "lektion_gridview", "gutenbergeditor", "hide_mails", "hide_profile_menu", "hide_config_menu", "hide_trainingoverview_menu", "hide_message_menu", "hide_show_contactinfo_menu", "hide_dashboard_menu", "dashboard_redirect", "rest_activated", "xmlrpc_activated", "disable_language_dropdown", "enablevisualeditor", "open_register_main_menu", "register_redeem_code_manually", "reject_privacy_terms", "dashboard_hide_notrainings", "reset_userInactivity", "dashboard_add_name_profile", "disable_register_link");
        $textarea_fields = array("limesurvey_second_survey_email_body", "limesurvey_second_survey_email_reminder_body", "limesurvey_third_survey_email_body", "limesurvey_third_survey_email_reminder_body", "mailbox_coach_2_coachee_email_body", "mailbox_coachee_2_coach_email_body", "mailbox_feedback_from_coach_email_body", "mailbox_email_unread_message_body", "mailbox_email_unread_messages_body", "no_trainings_text_dashboard", "register_problem", "register_solution", "after_registration_text", "lektionen_text");
        $url_fields = array( "limesurvey_rpc_url", "privacy_terms_URL");
        $array_fields = array('page_user_profile_exclude_sg', 'page_user_progress_exclude_sg', 'page_zertifikate_exclude_sg', 'page_exercise_favorites_exclude_sg', 'page_check_results_exclude_sg', 'page_create_user_exclude_sg', 'page_user_list_exclude_sg', 'page_user_list_detail_exclude_sg', 'page_coach_nutzer_exclude_sg', 'page_training_overview_exclude_sg', 'page_psych_admin_overview_exclude_sg', 'page_lessons_overview_exclude_sg', 'page_company_details_exclude_sg', 'page_user_grouper_exclude_sg', 'page_user_importer_exclude_sg', 'page_user_results_export_exclude_sg', 'page_dataexport_exclude_sg', 'page_trainings_ex_import_exclude_sg', 'page_user_code_exclude_sg', 'page_system_statistics_exclude_sg', 'page_coaching_overview_exclude_sg', 'page_mailbox_view_exclude_sg', 'page_coach_vorlage_exclude_sg', 'page_show_contactinfo_exclude_sg', 'page_dashboard_exclude_sg', 'page_study_overview_exclude_sg');
        $array_fields_dashboard_items = array('dashboard_items');
        $settings = array();
        foreach ($_POST['setting'] as $name => $setting) {

            if (in_array($name, $int_fields)) {
                $settings[$name] = absint($setting);
            } elseif (in_array($name, $bool_fields)) {
                $settings[$name] = boolval($setting);
            } elseif (in_array($name, $url_fields)) {
                $settings[$name] = esc_url($setting, ['http', 'https']);
            } elseif (in_array($name, $textarea_fields)) {
                $settings[$name] = sanitize_textarea_field($setting);
            } elseif (in_array($name, $array_fields)) {
                if(!isset($settings[$name])) {
                    $settings[$name] = array();
                }
                foreach($setting as $s) {
                    $settings[$name][] = sanitize_text_field( $s );
                }
            } elseif(in_array($name, $array_fields_dashboard_items)) {
                if(!isset($settings[$name])) {
                    $settings[$name] = array();
                }
                foreach($setting as $itemindex => $item) {
                    if(isset($item['title']) && !empty(trim($item['title'])) && isset($item['css']) && !empty(trim($item['css'])) && isset($item['content']) && !empty(trim($item['content']))) {
                        if(!isset($settings[$name][$itemindex])) {
                            $settings[$name][$itemindex] = array();
                        }

                        $allowed_html = array(
                            "i" => [
                                "class" => []
                            ]
                        );
                        $settings[$name][$itemindex]['title'] = stripslashes(wp_kses($item['title'], $allowed_html));
                        $settings[$name][$itemindex]['css'] = sanitize_text_field($item['css']);
                        $settings[$name][$itemindex]['content'] = stripslashes($item['content']);
                    }
                }
            } else {
                $settings[$name] = sanitize_text_field($setting);
            }
        }

        if(empty($settings['privacy_terms_URL']) || $settings['privacy_terms_URL'] != $settings_old['privacy_terms_URL']) {
            $this->removeAllPrivacyTermAccepted();
        }

        if(empty($settings['demologin_registerkey'])) {
            $this->removeAllDemoUser();
        }

        update_option(TRAININGSSYSTEM_PLUGIN_SETTINGS, $settings);
        echo "1";
        wp_die();
    }

    private function removeAllPrivacyTermAccepted() {
        global $wpdb;

        $query = "DELETE FROM $wpdb->usermeta WHERE meta_key = 'privacy_terms_confirmed';";
        return $wpdb->query($query);
    }

    public function deleteDemoUser() {
        $this->removeAllDemoUser();
        echo "1";
        wp_die();
    }

    private function removeAllDemoUser() {
        global $wpdb;

        $user_args = array(
            'meta_key' => 'demo_user',
            'meta_value' => '1',
            'meta_compare' => '=',
            'number' => -1
        );
        $user_query = new WP_User_Query($user_args);
        
        foreach ($user_query->get_results() as $user)
        {
            wp_delete_user( $user->ID);
        }
    }

    private function loadLimesurveyEmailSubject($xmlFile)
    {
        if ($json = $this->loadXmlFileAsJson($xmlFile)) {
            if (isset($json->subject)) {
                return $json->subject;
            }
        }
        return '';
    }

    private function loadLimesurveyEmailBody($xmlFile)
    {
        if ($json = $this->loadXmlFileAsJson($xmlFile)) {
            if (isset($json->body)) {
                return $json->body;
            }
        }
        return '';
    }

    private function loadXmlFileAsJson($xmlFile)
    {
        if ($xml = simplexml_load_string(@file_get_contents(dirname(__FILE__) . './../limesurvey/emails/' . $xmlFile))) {
            return json_decode(json_encode($xml));
        }
        return false;
    }
}
