<?php
/*
 * Author: Michael Finkenberger
 * @since V2.5.24.0
 * Last change in plugin version: V2.5.24.0
 * - V2.5.24.0: Main plugin callback function moved from main plugin file to this separate file
 * Date: 21.03.2026
 * Tested with the latest plugin version
*/



// *************************************************************************************************************************************************************************************
// *************************************************************************************************************************************************************************************
// **********************************************************************                                       ************************************************************************
// **********************************************************************   The main plugin callback function   ************************************************************************
// **********************************************************************                                       ************************************************************************
// *************************************************************************************************************************************************************************************
// *************************************************************************************************************************************************************************************

function foodle_admin_page_callback() {
  global $wpdb;
  global $wp_roles;
  global $wp_admin_bar;
  global $foodle_title;
  global $foodle_admin_menu_color;
  global $foodle_undefined_error;
  global $foodle_sorting;
  global $foodle_help_tooltips;
  global $foodle_frontend_tooltips;
  global $foodle_warnings_removed;
  global $foodle_no_safety_query;
  global $foodle_results_text_default;
  global $foodle_results_text;
  global $foodle_bar_graph_text_default;
  global $foodle_bar_graph_text;
  global $foodle_roles_metafields;
  global $foodle_roles_sorting;
  global $foodle_roles_sproles;
  global $foodle_roles_email;
  global $foodle_roles_usage;
  global $foodle_roles_settings;
  global $foodle_roles_tips;
  global $foodle_roles_deleteun;
  global $foodle_email_link_admins;
  global $foodle_email_link_non_admins;
  global $foodle_show_vote_date_admins;
  global $foodle_show_vote_time_admins;
  global $foodle_show_vote_date_specview;
  global $foodle_show_vote_time_specview;
  global $foodle_scroll_up_button_visible;

  // check user capabilities
  if ( ! current_user_can( 'manage_foodle' ) ) return; // Not allowed!
  
  if ( ! get_option('foodle_dem_categories') ) update_option('foodle_dem_categories', array(), 'yes'); // just to be sure

  $update_in_progress = __('Update in progress ','foodle-for-democracy-poll'); // default text when jumping to another admin page

  // handle and store the Foodle category selection from the democracy poll edit page in option 'foodle_dem_categories'
  if ( isset($_POST['select_poll_categories']) ) {
    $foodle_admin_notice = '';
    $foodle_error = false;
    $foodle_warning = false;

    if ( isset($_POST['democracy_url']) ) {
      $democracy_url = filter_var(esc_url_raw($_POST['democracy_url']), FILTER_VALIDATE_URL);
      $new_poll = __('New Poll','foodle-for-democracy-poll');
      if (! $democracy_url === false ) {
        if ( strpos( $democracy_url, 'add_new') !== false )
          $poll_id = $new_poll;
        else {
          $poll_id = substr($democracy_url,strpos($democracy_url,"&edit_poll=") + 11);
          if ( strpos($poll_id, "&") !== false )
            $poll_id = substr($poll_id,0,strpos($poll_id,"&"));
        }
        if ( $poll_id != $new_poll ) {
          $foodle_dem_categories = (array)get_option('foodle_dem_categories');
          if ( isset($_POST['foodle_dem_categories']) ) {
            $foodle_dem_categories[$poll_id] = array(); // initialize
            foreach($_POST['foodle_dem_categories'] as $foodle_dem_category) {
              $foodle_dem_categories[$poll_id][] = sanitize_text_field($foodle_dem_category);
            }
          } else {
              $foodle_dem_categories[$poll_id] = array(); // no categories
          }
          if ( isset($_POST['sorting_button_text']) ) // determine and store the sorting button text for this Democracy Poll id
            $foodle_dem_categories['sorting_button_text'][$poll_id] = sanitize_text_field($_POST['sorting_button_text']);
          else
            $foodle_dem_categories['sorting_button_text'][$poll_id] = $foodle_sorting;
          if ( isset($_POST['democracy_refresh_button_voted']) ) // determine whether the refresh button shall be displayed after voting for this Democracy Poll id
            $foodle_dem_categories['refresh_button_voted'][$poll_id] = ( $_POST['democracy_refresh_button_voted'] == 'yes' );
          else
            $foodle_dem_categories['refresh_button_voted'][$poll_id] = false;
          if ( isset($_POST['democracy_refresh_button_not_voted']) ) // determine whether the refresh button shall be displayed before voting for this Democracy Poll id
            $foodle_dem_categories['refresh_button_not_voted'][$poll_id] = ( $_POST['democracy_refresh_button_not_voted'] == 'yes' );
          else
            $foodle_dem_categories['refresh_button_not_voted'][$poll_id] = false;
          if ( isset($_POST['democracy_count_marked_voters']) ) // determine whether the refresh button shall be displayed before voting for this Democracy Poll id
            $foodle_dem_categories['count_marked_voters'][$poll_id] = ( $_POST['democracy_count_marked_voters'] == 'yes' );
          else
            $foodle_dem_categories['count_marked_voters'][$poll_id] = false;
          if ( isset($_POST['democracy_delete_poll_IP_addresses']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['delete_poll_IP_addresses'][$poll_id] = ( $_POST['democracy_delete_poll_IP_addresses'] == 'yes' );
          else
            $foodle_dem_categories['delete_poll_IP_addresses'][$poll_id] = false;
          if ( isset($_POST['democracy_send_comment_email']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['send_comment_email'][$poll_id] = ( $_POST['democracy_send_comment_email'] == 'yes' );
          else
            $foodle_dem_categories['send_comment_email'][$poll_id] = false;
          if ( isset($_POST['foodle_roles_show_democracy']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['roles_show_democracy'][$poll_id] = ( $_POST['foodle_roles_show_democracy'] == 'yes' );
          else
            $foodle_dem_categories['roles_show_democracy'][$poll_id] = false;
          if ( isset($_POST['foodle_roles_show_foodle']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['roles_show_foodle'][$poll_id] = ( $_POST['foodle_roles_show_foodle'] == 'yes' );
          else
            $foodle_dem_categories['roles_show_foodle'][$poll_id] = false;
          if ( isset($_POST['foodle_roles_show_comments']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['roles_show_comments'][$poll_id] = ( $_POST['foodle_roles_show_comments'] == 'yes' );
          else
            $foodle_dem_categories['roles_show_comments'][$poll_id] = false;
          if ( isset($_POST['foodle_roles_do_comments']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['roles_do_comments'][$poll_id] = ( $_POST['foodle_roles_do_comments'] == 'yes' );
          else
            $foodle_dem_categories['roles_do_comments'][$poll_id] = false;
          if ( isset($_POST['foodle_roles_show_bar_graph']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['roles_show_bar_graph'][$poll_id] = ( $_POST['foodle_roles_show_bar_graph'] == 'yes' );
          else
            $foodle_dem_categories['roles_show_bar_graph'][$poll_id] = false;
          if ( isset($_POST['foodle_roles_show_admin']) ) // determine whether storage of IP addresses shall be inhibited for this Democracy Poll id
            $foodle_dem_categories['roles_show_admin'][$poll_id] = ( $_POST['foodle_roles_show_admin'] == 'yes' );
          else
            $foodle_dem_categories['roles_show_admin'][$poll_id] = false;
          if ( isset($_POST['foodle_dem_category_column']) ) // determine and store the category column for this Democracy Poll id
            $foodle_dem_categories['category_column'][$poll_id] = sanitize_text_field($_POST['foodle_dem_category_column']);
          else
            $foodle_dem_categories['category_column'][$poll_id] = '';
          if ( isset($_POST['event_use']) ) // determine whether the poll concerns an event
            $foodle_dem_categories['event_use'][$poll_id] = ( $_POST['event_use'] == 'yes' );
          else
            $foodle_dem_categories['event_use'][$poll_id] = false;
          if ( isset($_POST['event_auto']) ) // determine whether the poll concerns an event
            $foodle_dem_categories['event_auto'][$poll_id] = ( $_POST['event_auto'] == 'yes' );
          else
            $foodle_dem_categories['event_auto'][$poll_id] = false;
          if ( isset($_POST['event_summary']) ) // determine and store the event_summary/title for this Democracy Poll id
            $foodle_dem_categories['event_summary'][$poll_id] = sanitize_text_field($_POST['event_summary']);
          else
            $foodle_dem_categories['event_summary'][$poll_id] = "";
          if ( isset($_POST['event_start']) ) // determine and store the event_summary/title for this Democracy Poll id
            $foodle_dem_categories['event_start'][$poll_id] = sanitize_text_field($_POST['event_start']);
          else
            $foodle_dem_categories['event_start'][$poll_id] = "";
          if ( isset($_POST['event_end']) ) // determine and store the event_summary/title for this Democracy Poll id
            $foodle_dem_categories['event_end'][$poll_id] = sanitize_text_field($_POST['event_end']);
          else
            $foodle_dem_categories['event_end'][$poll_id] = "";
          if ( isset($_POST['event_description']) ) // determine and store the event_summary/title for this Democracy Poll id
            $foodle_dem_categories['event_description'][$poll_id] = sanitize_text_field($_POST['event_description']);
          else
            $foodle_dem_categories['event_description'][$poll_id] = "";
          if ( isset($_POST['event_location']) ) // determine and store the event_summary/title for this Democracy Poll id
            $foodle_dem_categories['event_location'][$poll_id] = sanitize_text_field($_POST['event_location']);
          else
            $foodle_dem_categories['event_location'][$poll_id] = "";
          if ( isset($_POST['event_url']) ) // determine and store the event_summary/title for this Democracy Poll id
            $foodle_dem_categories['event_url'][$poll_id] = sanitize_text_field($_POST['event_url']);
          else
            $foodle_dem_categories['event_url'][$poll_id] = "";
          if ( isset($_POST['ics_button_text']) ) // determine and store the event_summary/title for this Democracy Poll id
            $foodle_dem_categories['ics_button_text'][$poll_id] = sanitize_text_field($_POST['ics_button_text']);
          else
            $foodle_dem_categories['ics_button_text'][$poll_id] = "";
          $foodle_roles_concerned_selection = false;
          if ( isset($_POST['foodle_roles_concerned']) ) {
            $sanitized_foodle_roles_array = array();
            $poll_id = 0;
            foreach ( $_POST['foodle_roles_concerned'] as $selected_foodle_role ) {
              $foodle_role_sanitized = sanitize_text_field($selected_foodle_role);
              if ( $poll_id == 0 ) $poll_id = (int)substr($foodle_role_sanitized, 0, strpos($foodle_role_sanitized, '|'));
              $foodle_role = substr($foodle_role_sanitized, strpos($foodle_role_sanitized, '|') + 1);
              if ( $foodle_role != "*" ) $sanitized_foodle_roles_array[] = $foodle_role;
            }
            $sanitized_foodle_roles_array_serialized = serialize($sanitized_foodle_roles_array);
            $sql = "SELECT * FROM $wpdb->democracy_q WHERE id={$poll_id}";
            $current_roles_concerned = $wpdb->get_row($sql)->roles_concerned;
            if ( $current_roles_concerned == "") $current_roles_concerned = serialize(array()); // Make sure that the change from an unfilled database field to a serialized empty array is not recognized as a change in content.
            $sql = "UPDATE $wpdb->democracy_q SET roles_concerned='{$sanitized_foodle_roles_array_serialized}' WHERE id={$poll_id}";
            $wpdb->query($sql);
            if ( $current_roles_concerned !== $sanitized_foodle_roles_array_serialized ) $foodle_roles_concerned_selection = true;
          }
          $foodle_roles_for_not_voted_selection = false;
          if ( isset($_POST['foodle_roles_for_not_voted']) ) { // determine for which roles the tooltip with users that did not vote for a poll shall be displayed
            $sanitized_foodle_roles_for_not_voted_array = array();
            $poll_id = 0;
            foreach ( $_POST['foodle_roles_for_not_voted'] as $selected_foodle_role ) {
              $foodle_role_sanitized = sanitize_text_field($selected_foodle_role);
              if ( $poll_id == 0 ) $poll_id = (int)substr($foodle_role_sanitized, 0, strpos($foodle_role_sanitized, '|'));
              $foodle_role = substr($foodle_role_sanitized, strpos($foodle_role_sanitized, '|') + 1);
              if ( $foodle_role != "*" ) $sanitized_foodle_roles_for_not_voted_array[] = $foodle_role;
            }
            $foodle_dem_categories['roles_for_not_voted'][$poll_id] = $sanitized_foodle_roles_for_not_voted_array;
            if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_for_not_voted'][$poll_id]) ) )
              $roles_for_not_voted = ( get_option('foodle_dem_categories')['roles_for_not_voted'][$poll_id] );
            else
              $roles_for_not_voted = array('');
            if ( $roles_for_not_voted !== $sanitized_foodle_roles_for_not_voted_array ) $foodle_roles_for_not_voted_selection = true;
          }
        }
        foodle_pwx_admin_notice__info('<p><span style="vertical-align:160%;">'.$update_in_progress.'...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span> <img src="'.plugin_dir_url(__FILE__).'img/loader.gif"></p>');
        if ( ( update_option('foodle_dem_categories', $foodle_dem_categories, 'yes') ) || ( $foodle_roles_concerned_selection ) ) // store it, check success and jump back with the news as GET parameters...
          echo '<script type="text/javascript">window.location.href="'.$democracy_url.'&foodle_dem_edit=foodle_changed"</script>';
        else
          echo '<script type="text/javascript">window.location.href="'.$democracy_url.'&foodle_dem_edit=foodle_unchanged"</script>';
      } else {
        foodle_pwx_admin_notice__defined_error('<p>'.__('The democracy poll url could not properly be retrieved','foodle-for-democracy-poll').'</p>');
      }
    } else {
      foodle_pwx_admin_notice__defined_error('<p>'.__('The Foodle categories could not properly be set during democracy poll edit','foodle-for-democracy-poll').'</p>');
    }
  }

  // handle the update of the shortcode use
  if ( isset($_POST['update_shortcode_usage']) ) {
    foodle_check_shortcode_presence();
    if ( ! get_option('foodle_shortcode_usage_error_pages_posts') ) {
      $foodle_admin_notice = __('The shortcode use update was performed successfully','foodle-for-democracy-poll').'.';
      foodle_pwx_admin_notice__success('<p>'.$foodle_admin_notice.'</p>');
    } else {
      $foodle_admin_notice = __('Errors were found during the shortcode use update','foodle-for-democracy-poll');
      foodle_pwx_admin_notice__warning('<p>'.$foodle_admin_notice.'</p>');
    }
  }

  // handle and store the other Foodle settings in option 'foodle_settings'
  if ( isset($_POST['save_foodle_settings']) ) {
    $foodle_admin_notice = '';
    $foodle_error = false;
    $foodle_warning = false;

    if ( ( current_user_can('manage_options') ) && ( isset($_POST['foodle_title']) ) && ( $_POST['foodle_title'] != '' ) ) { // last line of defence for an administrator privilege
      $foodle_title = sanitize_text_field($_POST['foodle_title']);
    }
    else if ( ( current_user_can('manage_options') ) && ( isset($_POST['foodle_title']) ) )
      $foodle_title = 'Foodle';

    if ( ( isset($_POST['foodle_results_text']) ) && ( $_POST['foodle_results_text'] != '' ) ) {
      $foodle_results_text = sanitize_text_field($_POST['foodle_results_text']);
    } else $foodle_results_text = $foodle_results_text_default;

    if ( ( isset($_POST['foodle_bar_graph_text']) ) && ( $_POST['foodle_bar_graph_text'] != '' ) ) {
      $foodle_bar_graph_text = sanitize_text_field($_POST['foodle_bar_graph_text']);
    } else $foodle_bar_graph_text = $foodle_bar_graph_text_default;

    if ( current_user_can('manage_options') ) { // last line of defence for an administrator privilege
      $foodle_email_link_admins = ( isset($_POST['voter-email-link-for-admins']) ) ? true : false;
      $foodle_email_link_non_admins = ( isset($_POST['voter-email-link-for-non-admins']) ) ? true : false;
    }

    if ( current_user_can('manage_options') ) { // last line of defence for an administrator privilege
      $foodle_show_vote_date_admins = ( isset($_POST['vote-date-for-admins']) ) ? true : false;
      $foodle_show_vote_time_admins = ( isset($_POST['vote-time-for-admins']) ) ? true : false;
      $foodle_show_vote_date_specview = ( isset($_POST['vote-date-for-specview']) ) ? true : false;
      $foodle_show_vote_time_specview = ( isset($_POST['vote-time-for-specview']) ) ? true : false;
    }

    if ( ( isset($_POST['foodle_admin_menu_color']) ) && ( $_POST['foodle_admin_menu_color'] != '' ) ) {
      $foodle_admin_menu_color = sanitize_text_field($_POST['foodle_admin_menu_color']);
    } else $foodle_admin_menu_color = '#8CBD5A';

    if ( ( current_user_can('manage_options') ) && ( isset($_POST['foodle_page_post_exclusion']) ) && ( $_POST['foodle_page_post_exclusion'] != '' ) ) { // last line of defence for an administrator privilege
      $foodle_page_post_exclusion = array_filter(explode(',', sanitize_text_field($_POST['foodle_page_post_exclusion'])));
    } else
    if ( ( current_user_can('manage_options') ) && ( isset($_POST['foodle_page_post_exclusion']) ) )
      $foodle_page_post_exclusion = array();
    else
      $foodle_page_post_exclusion = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_page_post_exclusion']) ) ) ? get_option('foodle_settings')['foodle_page_post_exclusion'] : array();

    if ( ( current_user_can('manage_options') ) && ( isset($_POST['foodle_democracy_textarea_template']) ) ) { // last line of defence for an administrator privilege
      //$foodle_democracy_textarea_template_new = sanitize_textarea_field($_POST['foodle_democracy_textarea_template']);
      $foodle_democracy_textarea_template_new = preg_replace('/(?<!\\\\)"/', '\\"', wp_kses_post($_POST['foodle_democracy_textarea_template'])); // Allow what WordPress allows in posts
    }

      if ( ( isset($_POST['foodle_date_format']) ) && ( $_POST['foodle_date_format'] != '' ) ) {
      $foodle_date_format = sanitize_text_field($_POST['foodle_date_format']);
    } else $foodle_date_format = 'mm/dd/yy';

    if ( ( current_user_can('manage_options') ) && ( isset($_POST['foodle_selected_roles']) ) ) { // last line of defence for an administrator privilege
      $foodle_selected_roles = array();
      foreach($_POST['foodle_selected_roles'] as $foodle_selected_role) {
        $foodle_selected_roles[] = sanitize_text_field($foodle_selected_role);
      }
    } 
    else
    if ( current_user_can('manage_options' ) )
      $foodle_selected_roles = array();
    else
      $foodle_selected_roles = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_selected_roles']) ) ) ? get_option('foodle_settings')['foodle_selected_roles'] : array();
    
    if ( current_user_can('manage_options') ) { // last line of defence for an administrator privilege
      $foodle_roles_metafields = ( isset($_POST['foodle-roles-metafields']) ) ? true : false;
      $foodle_roles_sorting = ( isset($_POST['foodle-roles-sorting']) ) ? true : false;
      $foodle_roles_sproles = ( isset($_POST['foodle-roles-sproles']) ) ? true : false;
      $foodle_roles_email = ( isset($_POST['foodle-roles-email']) ) ? true : false;
      $foodle_roles_usage = ( isset($_POST['foodle-roles-usage']) ) ? true : false;
      $foodle_roles_settings = ( isset($_POST['foodle-roles-settings']) ) ? true : false;
      $foodle_roles_tips = ( isset($_POST['foodle-roles-tips']) ) ? true : false;
      $foodle_roles_deleteun = ( isset($_POST['foodle-roles-deleteun']) ) ? true : false;
    }
    $foodle_show_in_admin_menu_bar = ( isset($_POST['show-in-admin-menu-bar']) ) ? true : false;
    if ( current_user_can('manage_options') ) // last line of defence for an administrator privilege
      $foodle_remove_vote_expiry = ( isset($_POST['remove-vote-expiry']) ) ? true : false;
    else
      $foodle_remove_vote_expiry = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['remove-vote-expiry']) ) ) ? get_option('foodle_settings')['remove-vote-expiry'] : false;
    $foodle_metafield_user_profile = ( isset($_POST['metafields-user-profile']) ) ? true : false;
    $foodle_help_tooltips = ( isset($_POST['help-tooltips']) ) ? true : false;
    $foodle_frontend_tooltips = ( isset($_POST['frontend-tooltips']) ) ? true : false;
    $foodle_warnings_removed = ( isset($_POST['remove-warnings']) ) ? true : false;
    $foodle_no_safety_query = ( isset($_POST['no-safety-query']) ) ? true : false;

    if ( current_user_can('manage_options') ) { // last line of defence for an administrator privilege
      $foodle_scroll_up_button_visible['frontend'] = ( isset($_POST['scroll-up-visible-frontend']) ) ? true : false;
      $foodle_scroll_up_button_visible['democracy'] = ( isset($_POST['scroll-up-visible-democracy']) ) ? true : false;
      $foodle_scroll_up_button_visible['foodle'] = ( isset($_POST['scroll-up-visible-foodle']) ) ? true : false;
      $foodle_scroll_up_button_visible['comments'] = ( isset($_POST['scroll-up-visible-comments']) ) ? true : false;
      $foodle_scroll_up_button_visible['bar_graph'] = ( isset($_POST['scroll-up-visible-bar-graph']) ) ? true : false;
      $foodle_scroll_up_button_visible['backend'] = ( isset($_POST['scroll-up-visible-backend']) ) ? true : false;
      $foodle_scroll_up_button_visible['democracy_admin'] = ( isset($_POST['scroll-up-visible-democracy-admin']) ) ? true : false;
      $foodle_scroll_up_button_visible['foodle_admin'] = ( isset($_POST['scroll-up-visible-foodle-admin']) ) ? true : false;
      if ( ( ! ( $foodle_scroll_up_button_visible['foodle_admin'] ) ) && ( ! ( $foodle_scroll_up_button_visible['backend'] ) ) ) foodle_remove_scroll_up_button();
      if ( ( $foodle_scroll_up_button_visible['foodle_admin'] ) || ( $foodle_scroll_up_button_visible['backend'] ) ) foodle_provide_scroll_up_button();
    }

    $foodle_settings = array();
    $foodle_settings['foodle_title'] = $foodle_title;
    $foodle_settings['foodle_results_text'] = $foodle_results_text;
    $foodle_settings['foodle_bar_graph_text'] = $foodle_bar_graph_text;
    $foodle_settings['foodle_admin_menu_color'] = $foodle_admin_menu_color;
    $foodle_settings['foodle_page_post_exclusion'] = $foodle_page_post_exclusion;
    $foodle_settings['foodle_date_format'] = $foodle_date_format;
    $foodle_settings['foodle_selected_roles'] = $foodle_selected_roles;
    $foodle_settings['show-in-admin-menu-bar'] = $foodle_show_in_admin_menu_bar;
    $foodle_settings['remove-vote-expiry'] = $foodle_remove_vote_expiry;
    $foodle_settings['metafields-user-profile'] = $foodle_metafield_user_profile;
    $foodle_settings['help-tooltips'] = $foodle_help_tooltips;
    $foodle_settings['frontend-tooltips'] = $foodle_frontend_tooltips;
    $foodle_settings['remove-warnings'] = $foodle_warnings_removed;
    $foodle_settings['no-safety-query'] = $foodle_no_safety_query;
    $foodle_settings['foodle-roles-metafields'] = $foodle_roles_metafields;
    $foodle_settings['foodle-roles-sorting'] = $foodle_roles_sorting;
    $foodle_settings['foodle-roles-sproles'] = $foodle_roles_sproles;
    $foodle_settings['foodle-roles-email'] = $foodle_roles_email;
    $foodle_settings['foodle-roles-usage'] = $foodle_roles_usage;
    $foodle_settings['foodle-roles-settings'] = $foodle_roles_settings;
    $foodle_settings['foodle-roles-tips'] = $foodle_roles_tips;
    $foodle_settings['foodle-roles-deleteun'] = $foodle_roles_deleteun;
    $foodle_settings['voter-email-link-for-admins'] = $foodle_email_link_admins;
    $foodle_settings['voter-email-link-for-non-admins'] = $foodle_email_link_non_admins;
    $foodle_settings['vote-date-for-admins'] = $foodle_show_vote_date_admins;
    $foodle_settings['vote-time-for-admins'] = $foodle_show_vote_time_admins;
    $foodle_settings['vote-date-for-specview'] = $foodle_show_vote_date_specview;
    $foodle_settings['vote-time-for-specview'] = $foodle_show_vote_time_specview;
    $foodle_settings['foodle-democracy-textarea-template'] = $foodle_democracy_textarea_template_new;
    $foodle_settings['foodle-scroll-up-button-visible'] = $foodle_scroll_up_button_visible;

    if ( $foodle_error ) {
      foodle_pwx_admin_notice__defined_error('<p>'.$foodle_admin_notice.'</p>');
    } else {
      if ( update_option('foodle_settings', $foodle_settings, 'yes') ) { // Settings were changed
        // Set or remove the roles' capability for Foodle
        foreach ( $wp_roles->role_names as $foodle_wp_role_slug=>$foodle_wp_role_name ) {
            if ( $foodle_wp_role_slug == 'administrator' ) continue;
            if ( in_array($foodle_wp_role_slug,$foodle_selected_roles) )
                wp_roles()->add_cap( $foodle_wp_role_slug, 'manage_foodle' );
            else
                wp_roles()->remove_cap( $foodle_wp_role_slug, 'manage_foodle' );
        }
        // Set or remove cronjob for vote expiry
        if ( $foodle_remove_vote_expiry )
            foodle_schedule_cron();
        else
            foodle_unschedule_cron();
        foodle_pwx_admin_notice__success('<p>'.__('The Foodle settings were properly stored','foodle-for-democracy-poll').'.</p>');
      }
      else
        foodle_pwx_admin_notice__success('<p>'.__('The Foodle settings did not change','foodle-for-democracy-poll').'.</p>');
    }
  }

  // handle and store the user / role properties in option 'foodle_special_functions'
  if ( isset($_POST['save_special_roles_users']) ) {
    $foodle_admin_notice = 'Error: No error found - but nothing done!';
    $foodle_error = false;
    $foodle_warning = false;

    $foodle_special_functions = array();
    if ( ( isset($_POST['foodle_functions_line']) ) && ( isset($_POST['roles_users_field']) ) ) {
      $foodle_line_count = -1; // to have the first iteration see 0
      foreach( $_POST['foodle_functions_line'] as $foodle_line_ref ) { // just for referring to the input lines, even if some had been deleted
        $foodle_line_count += 1;
        $foodle_line_ref = sanitize_text_field($foodle_line_ref);

        if ( ( $_POST['roles_users_field'][$foodle_line_count] == 'no_selection' ) ) {
            $foodle_warning = true;
            $foodle_admin_notice = __('Minimum one role/user name found empty. Such rows are ignored','foodle-for-democracy-poll');
            continue; // remove lines without user or role selection but allow lines without a capability being set
        }

        $roles_users_field = ($_POST['roles_users_field'][$foodle_line_count]);

        $foodle_capabilities_raw = ( isset($_POST['capabilities'.$foodle_line_ref]) ) ? $_POST['capabilities'.$foodle_line_ref] : array() ;
        $foodle_capabilities = array();
        foreach( (array)$foodle_capabilities_raw as $foodle_capability ) {
          $foodle_capabilities[] = sanitize_text_field($foodle_capability);
        }
        $foodle_special_functions[$roles_users_field] = $foodle_capabilities;
      }

      if ( $foodle_error ) {
        foodle_pwx_admin_notice__defined_error('<p>'.$foodle_admin_notice.'</p>');
      } else {
        if ( $foodle_warning )
          foodle_pwx_admin_notice__warning('<p>'.$foodle_admin_notice.'</p>');
        if ( update_option('foodle_special_functions', $foodle_special_functions, 'yes') )
          foodle_pwx_admin_notice__success('<p>'.__('The Foodle \'Special Roles & Users\' definiton was properly set','foodle-for-democracy-poll').'.</p>');
        else
          foodle_pwx_admin_notice__success('<p>'.__('The Foodle \'Special Roles & Users\' definiton did not change','foodle-for-democracy-poll').'.</p>');
    }
    } else {
      foodle_pwx_admin_notice__error();
    }
  }

  // handle the metafield defaults & sorting definitions and storage in option 'foodle_defaults_sorting' and replacements directly in database 'usermeta'
  if ( isset($_GET['foodle_sorting_done']) ) { // coming back from changing the data
    if ( $_GET['foodle_sorting_done'] == 'yes' ) { // all good
      $foodle_admin_notice = '<p>'.__('The Foodle Defaults & Sorting definition was properly saved','foodle-for-democracy-poll').'.</p>';
      foodle_pwx_admin_notice__success($foodle_admin_notice);
    } else
    if ( $_GET['foodle_sorting_done'] == 'no' ) { // not good
      $foodle_admin_notice = '<p>'.__('The Foodle Defaults & Sorting update failed','foodle-for-democracy-poll').'.</p>';
      foodle_pwx_admin_notice__defined_error($foodle_admin_notice);
    } else
    if ( $_GET['foodle_sorting_done'] == 'nochange' ) { // not good
      $foodle_admin_notice = '<p>'.__('The Foodle Defaults & Sorting did not change','foodle-for-democracy-poll').'.</p>';
      foodle_pwx_admin_notice__success($foodle_admin_notice);
    }
  }
  if ( isset($_POST['save_meta_defaults_sorting']) ) {
    $foodle_admin_notice = '';
    $foodle_error = false;
    $foodle_warning = false;
    
    $foodle_meta_defaults_sorting = array();
    if ( isset($_POST['subreplace']) ) {
      foreach($_POST['subreplace'] as $foodle_meta_name => $foodle_meta_name_replace_data) {
        $foodle_meta_name = sanitize_text_field($foodle_meta_name);
        foreach($foodle_meta_name_replace_data as $foodle_subcategory_old => $foodle_subcategory_new) {
          $foodle_subcategory_old = ( $foodle_subcategory_old == ' ' ) ? '&nbsp;' : $foodle_subcategory_old;
          $foodle_subcategory_old = sanitize_text_field($foodle_subcategory_old);
          $foodle_subcategory_new = sanitize_text_field($foodle_subcategory_new);
          if ( $foodle_subcategory_new != '') {
            $foodle_meta_key=foodle_fieldname_to_meta_name($foodle_meta_name);
            $sql = "UPDATE $wpdb->usermeta SET meta_value='".$foodle_subcategory_new."' WHERE meta_key='".$foodle_meta_key."' AND meta_value='".$foodle_subcategory_old."'";
            $wpdb->query($sql);
          }
        }
      }
      $wpdb->flush(); // flush any cached query result
    } else $foodle_error = true;
    if ( isset($_POST['sorttype']) ) {
      foreach($_POST['sorttype'] as $foodle_meta_name => $foodle_meta_sort_type) {
        $foodle_meta_name = sanitize_text_field($foodle_meta_name);
        $foodle_meta_sort_type = sanitize_text_field($foodle_meta_sort_type);
        if ( isset($_POST['sortlist'][$foodle_meta_name]) ) {
          $foodle_meta_sort_list = '';
          if ( isset($_POST['sortlist']) ) {
              $foodle_meta_sort_list = nl2br($_POST['sortlist'][$foodle_meta_name],false);
              $foodle_meta_sort_list = html_entity_decode(sanitize_text_field(htmlentities(stripslashes(str_replace('<br><br>','<br>',preg_replace('#\r|\n#','',$foodle_meta_sort_list))))));
              // cope with empty lines
              $foodle_meta_sort_list = str_replace('<br><br>','<br>&nbsp;<br>',str_replace('<br><br>','<br>&nbsp;<br>',str_replace(' <br>','&nbsp;<br>',preg_replace('/(?:\xC2\xA0)+<br>/','&nbsp;<br>',$foodle_meta_sort_list))));
              $foodle_meta_sort_list = ( substr($foodle_meta_sort_list,0,4) == "<br>") ? "&nbsp;".$foodle_meta_sort_list : $foodle_meta_sort_list;
              $foodle_meta_sort_list = ( substr($foodle_meta_sort_list,-4,4) == "<br>") ? $foodle_meta_sort_list."&nbsp;" : $foodle_meta_sort_list;
            } else $foodle_error = true;
          $foodle_meta_defaults_sorting[$foodle_meta_name]['sorttype'] = $foodle_meta_sort_type;
          $foodle_meta_defaults_sorting[$foodle_meta_name]['sortlist'] = $foodle_meta_sort_list;
          $foodle_meta_defaults_sorting[foodle_fieldname_to_meta_name($foodle_meta_name)] = $foodle_meta_name;
        } else $foodle_error = true;
      }
    } else $foodle_error = true;
    foodle_pwx_admin_notice__info('<p><span style="vertical-align:160%;">'.$update_in_progress.'...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span> <img src="'.plugin_dir_url(__FILE__).'img/loader.gif"></p>');
    if (! $foodle_error ) {
        if ( update_option('foodle_meta_defaults_sorting', $foodle_meta_defaults_sorting, 'yes') )
          echo '<script type="text/javascript">window.location.href="'.admin_url( 'admin.php?page=foodle-admin-page&tab=metafield-default-sorting&foodle_sorting_done=yes' ).'"</script>'; // ... and jump back to properly reload the user meta data
        else
          echo '<script type="text/javascript">window.location.href="'.admin_url( 'admin.php?page=foodle-admin-page&tab=metafield-default-sorting&foodle_sorting_done=nochange' ).'"</script>'; // ... and jump back to properly reload the user meta data
    } else {
        echo '<script type="text/javascript">window.location.href="'.admin_url( 'admin.php?page=foodle-admin-page&tab=metafield-default-sorting&foodle_sorting_done=no' ).'"</script>'; // ... and jump back to properly reload the user meta data
    }
  }

  // Handle the meta field clean-up initiatied from the defaults & soting tab
  if ( isset($_POST['meta_field_clean_up']) ) { // can only be fired by administrators and only if there is a non-empty drop down list!
    $foodle_meta_field = sanitize_text_field($_POST['meta_field_clean_up']);
    $foodle_meta_field_slug = foodle_fieldname_to_meta_name($foodle_meta_field);
    $users = get_users(array(
      'orderby'  => 'meta_value',
      'meta_key' => 'last_name', // just a habit ;-)
      'order'    => 'ASC'
    ));
    $foodle_related_roles_array = ( isset(get_option('foodle_meta_fields')[$foodle_meta_field][5]) ) ? get_option('foodle_meta_fields')[$foodle_meta_field][5] : array('all') ;
    // Clean the sortlist as if it was saved with the 2.5.20.0 algorithm - just to be sure
    $foodle_meta_defaults_sorting = get_option('foodle_meta_defaults_sorting');
    $foodle_meta_sort_list = $foodle_meta_defaults_sorting[$foodle_meta_field]['sortlist'];
    // cope with empty lines
    $foodle_meta_sort_list = str_replace('<br><br>','<br>&nbsp;<br>',str_replace('<br><br>','<br>&nbsp;<br>',str_replace(' <br>','&nbsp;<br>',preg_replace('/(?:\xC2\xA0)+<br>/','&nbsp;<br>',$foodle_meta_sort_list))));
    $foodle_meta_sort_list = ( substr($foodle_meta_sort_list,0,4) == "<br>") ? "&nbsp;".$foodle_meta_sort_list : $foodle_meta_sort_list;
    $foodle_meta_sort_list = ( substr($foodle_meta_sort_list,-4,4) == "<br>") ? $foodle_meta_sort_list."&nbsp;" : $foodle_meta_sort_list;
    $foodle_meta_defaults_sorting[$foodle_meta_field]['sortlist'] = $foodle_meta_sort_list;
    update_option('foodle_meta_defaults_sorting',$foodle_meta_defaults_sorting,true);
    // And now get it to use it
    $foodle_sortlist_array = explode('<br>',get_option('foodle_meta_defaults_sorting')[$foodle_meta_field]['sortlist']);
    foreach($users as $user) {
      $foodle_user_id = $user->id;
      $foodle_user_roles = (array)$user->roles;
      $foodle_user_meta = get_user_meta($user->id,$foodle_meta_field_slug,true);
      if ( ( ! in_array('all',$foodle_related_roles_array) ) && ( count(array_intersect($foodle_user_roles,$foodle_related_roles_array)) == 0 ) ) {
      //if ( ( ! in_array('all',$foodle_related_roles_array) ) && ( count(array_intersect($foodle_user_roles,$foodle_related_roles_array)) == 0 ) && ( ! in_array('administrator',$foodle_user_roles) ) ) { // This could be used to leave administrators out of the game, however, currently not!
        delete_user_meta($user->id,$foodle_meta_field_slug);
      } else {
        if ( ! in_array($foodle_user_meta,$foodle_sortlist_array) ) {
        //if ( ( ! in_array($foodle_user_meta,$foodle_sortlist_array) ) && ( ! in_array('administrator',$foodle_user_roles) ) ) { // This could be used to leave administrators out of the game, however, currently not!
          update_user_meta($foodle_user_id,$foodle_meta_field_slug,'&nbsp;');
        }
      }
    }
    $foodle_admin_notice = __('The meta field clean-up was performed for','foodle-for-democracy-poll').' "<strong>'.str_replace('••','',$foodle_meta_field).'</strong>".';
    foodle_pwx_admin_notice__success('<p>'.$foodle_admin_notice.'</p>');
  }

  // Handle the listing of meta field sub-category members

  $help_click_for_user_edit = ( $foodle_help_tooltips ) ? ' foodle_tooltip="'.__('Click to edit this user.','foodle-for-democracy-poll').'"' : '';
  if ( isset($_POST['foodle_list_meta_sub_members']) ) {
    $foodle_list_meta_sub_members = sanitize_text_field($_POST['foodle_list_meta_sub_members']);
    $foodle_user_meta = explode('|',$foodle_list_meta_sub_members)[0];
    $foodle_user_meta_fieldname = foodle_fieldname_to_meta_name($foodle_user_meta);
    $foodle_user_meta_input = explode('|',$foodle_list_meta_sub_members)[1];
    $foodle_user_meta_input = ( $foodle_user_meta_input == ' ' ) ? '&nbsp;' : $foodle_user_meta_input;
    $users = get_users(array(
      'orderby'  => 'meta_value',
      'meta_key' => 'last_name', // just a habit ;-)
      'order'    => 'ASC'
    ));
    $foodle_admin_notice = '';
    $foodle_list_count = 0;
    foreach ( $users as $user ) {
      $foodle_user_id = $user->ID;
      $foodle_user_info = get_userdata($foodle_user_id);
      if ( get_user_meta($foodle_user_id,$foodle_user_meta_fieldname,true) == $foodle_user_meta_input ) {
        $foodle_list_count += 1;
        $foodle_admin_notice .= '<p '.$help_click_for_user_edit.' ><a href="'.get_admin_url().'user-edit.php?user_id='.$foodle_user_id.'">'.$foodle_user_info->user_login.' (ID='.$user->ID.')</a></p>';
      }
    }
    $foodle_admin_notice = '<p>'.sprintf(_n('%d user found for','%d users found for',$foodle_list_count,'foodle-for-democracy-poll'),$foodle_list_count).' <strong>'.str_replace('••','',$foodle_user_meta).' - '.$foodle_user_meta_input.'</strong>:</p>'.$foodle_admin_notice;
    foodle_pwx_admin_notice__info('<p>'.$foodle_admin_notice.'</p>');
  }

  // Handle the deletion of orphaned metafields in the database (usermeta)
  if ( ( ( current_user_can('manage_options') ) || ( $foodle_roles_deleteun ) ) && ( isset($_POST['delete_no_longer_used_metafields']) ) ) {
    $foodle_admin_notice = '';
    $foodle_meta_fields = array();

    $users = get_users(array(
        'orderby'  => 'meta_value',
        'meta_key' => 'last_name', // just a habit ;-)
        'order'    => 'ASC'
    ));

    if ( get_option('foodle_meta_fields') ) {

        // Build an array with the current foodle field names as stored in usermeta
        foreach ( get_option('foodle_meta_fields') as $foodle_fieldname => $foodle_fielddescription ) {
            $foodle_meta_fields[] = foodle_fieldname_to_meta_name($foodle_fieldname);
        }
        
        // Delete all orphaned foodle meta data
        $foodle_usermeta_count = 0;
        $foodle_user_count = 0;
        foreach ( $users as $user ) {
            $foodle_single_user_usermeta_count = 0;
            $foodle_user_id = $user->ID;
            $foodle_user_meta = get_user_meta($foodle_user_id);
            foreach( $foodle_user_meta as $foodle_meta_key => $foodle_meta_value ) {
                if ( ( strpos($foodle_meta_key,'foodle-field-') === 0 ) && ( ! in_array($foodle_meta_key,$foodle_meta_fields,true) ) ) {
                    delete_user_meta($foodle_user_id, $foodle_meta_key);
                    $foodle_single_user_usermeta_count +=1;
                    $foodle_usermeta_count += 1;
                }
            }
            if ( $foodle_single_user_usermeta_count > 0 ) $foodle_user_count += 1;
        }
        $foodle_admin_notice = __('Result','foodle-for-democracy-poll').': '.$foodle_usermeta_count.' '.__('database','foodle-for-democracy-poll').' '._n('entry was','entries were',$foodle_usermeta_count,'foodle-for-democracy-poll').' '.__('deleted for','foodle-for-democracy-poll').' '.$foodle_user_count.' '._n('registered user','registered users',$foodle_user_count,'foodle-for-democracy-poll');
        foodle_pwx_admin_notice__success('<p>'.$foodle_admin_notice.'</p>');
    } else {
        $foodle_admin_notice = __('The metafield definition was not found: deleting all metadata!','foodle-for-democracy-poll');
        foodle_pwx_admin_notice__info('<p>'.$foodle_admin_notice.'</p>');

        // Delete all foodle meta data as no metafields are defined any more
        $foodle_usermeta_count = 0;
        $foodle_user_count = 0;
        foreach ( $users as $user ) {
            $foodle_single_user_usermeta_count = 0;
            $foodle_user_id = $user->ID;
            $foodle_user_meta = get_user_meta($foodle_user_id);
            foreach( $foodle_user_meta as $foodle_meta_key => $foodle_meta_value ) {
                if ( strpos($foodle_meta_key,'foodle-field-') === 0 ) {
                    delete_user_meta($foodle_user_id, $foodle_meta_key);
                    $foodle_single_user_usermeta_count +=1;
                    $foodle_usermeta_count += 1;
                }
            }
            if ( $foodle_single_user_usermeta_count > 0 ) $foodle_user_count += 1;
        }
        $foodle_admin_notice = __('Result','foodle-for-democracy-poll').': '.$foodle_usermeta_count.' '.__('database','foodle-for-democracy-poll').' '._n('entry was','entries were',$foodle_usermeta_count,'foodle-for-democracy-poll').' '.__('deleted for','foodle-for-democracy-poll').' '.$foodle_user_count.' '._n('registered user','registered users',$foodle_user_count,'foodle-for-democracy-poll');
        foodle_pwx_admin_notice__success('<p>'.$foodle_admin_notice.'</p>');
    }
  } else if ( isset($_POST['delete_no_longer_used_metafields']) ) {
        $foodle_admin_notice = __('This function is for Foodle administrators only','foodle-for-democracy-poll').'!';
        foodle_pwx_admin_notice__defined_error('<p>'.$foodle_admin_notice.'</p>');        
  }

  // Handle the complex user meta and regexp handling and storage in options 'foodle_meta_fields' and 'foodle_regex_main'
  if ( isset($_POST['save_metafields_definition']) ) {
    $foodle_admin_notice = '';
    $foodle_error = false;
    $foodle_warning = false;

    $foodle_meta_fields = array();
    $foodle_regex_main = array();
    if ( ( isset($_POST['foodle_meta_line']) ) && ( isset($_POST['own_meta_field']) ) && ( isset($_POST['existing_meta_field']) ) && ( isset($_POST['description']) ) && ( isset($_POST['foodle_roles_for_meta_field']) ) && ( isset($_POST['regexp_field']) ) && ( isset($_POST['foodle_poll_use0']) ) && ( isset($_POST['foodle_category_use0']) ) && ( isset($_POST['meta_field_type']) ) ) {
      $foodle_line_count = -1; // to have the first iteration see 0
      foreach( $_POST['foodle_meta_line'] as $foodle_line_ref ) { // just for referring to the input lines, even if some had been deleted
        $foodle_line_count += 1;
        $foodle_line_ref = sanitize_text_field($foodle_line_ref);
        if ( $_POST['own_meta_field'][$foodle_line_count] == '---' ) {
          if ( strpos($_POST['existing_meta_field'][$foodle_line_count],'foodle-field-') === false ) {
            $foodle_field_name = '••'.sanitize_text_field($_POST['existing_meta_field'][$foodle_line_count]);
          }
          else { // recovery of still existing data
            $user_meta_key = sanitize_text_field($_POST['existing_meta_field'][$foodle_line_count]);
            $foodle_meta_field_slug = substr($user_meta_key,13);
            $foodle_field_name = str_replace('_',' ',str_replace('€','.',$foodle_meta_field_slug));
          }
        } else {
            $foodle_field_name = sanitize_text_field($_POST['own_meta_field'][$foodle_line_count]);
        }
        $description = sanitize_text_field($_POST['description'][$foodle_line_count]);
        $description = ($description == '---') ? '' : $description;

        $foodle_roles_for_meta_field_array = array();
        foreach ( $_POST['foodle_roles_for_meta_field'][$foodle_line_ref] as $selected_foodle_role ) {
          $foodle_role_sanitized = sanitize_text_field($selected_foodle_role);
          if ( $foodle_role_sanitized != "*" ) $foodle_roles_for_meta_field_array[] = $foodle_role_sanitized;
        }
        if ( count($foodle_roles_for_meta_field_array) == 0 ) $foodle_roles_for_meta_field_array = array('all');

        $link_meta_field = sanitize_text_field($_POST['link_meta_field'][$foodle_line_count]);
        $link_meta_field = ($link_meta_field == '---') ? '' : $link_meta_field;
        $foodle_poll_use = sanitize_text_field($_POST['foodle_poll_use'.$foodle_line_ref]);
        $foodle_category_use = sanitize_text_field($_POST['foodle_category_use'.$foodle_line_ref]);
        $foodle_field_type_save = sanitize_text_field($_POST['meta_field_type'][$foodle_line_count]);

        if ( $foodle_field_name != '' ) $foodle_meta_fields[$foodle_field_name] = array($description, $link_meta_field, $foodle_poll_use, $foodle_category_use, $foodle_field_type_save, $foodle_roles_for_meta_field_array);
        else {
            $foodle_warning = true;
            $foodle_admin_notice = __('Minimum one metafield name found empty. Such rows are ignored','foodle-for-democracy-poll');
        }
        $regexp_field = ( $foodle_line_count == 0 ) ? '---' : sanitize_text_field($_POST['regexp_field'][$foodle_line_count]); // if - after moving - the first row would carry such a content
        $regrep_field = ( $foodle_line_count == 0 ) ? '---' : sanitize_text_field($_POST['regrep_field'][$foodle_line_count]); // if - after moving - the first row would carry such a content
        $regrep_field = ($regrep_field == '---') ? '' : $regrep_field;
        if ( ( $regexp_field != '---' ) && ( $foodle_field_name != '' ) ) { 
          $foodle_regex_main[$foodle_field_name] = array($regexp_field, $regrep_field);
        }
      }
      if ( $foodle_error ) {
        foodle_pwx_admin_notice__defined_error('<p>'.$foodle_admin_notice.'</p>');
      } else {
        $foodle_meta_result = update_option('foodle_meta_fields', $foodle_meta_fields, 'yes');
        $foodle_regex_result = update_option('foodle_regex_main', $foodle_regex_main, 'yes');
        if ( $foodle_warning )
          foodle_pwx_admin_notice__warning('<p>'.$foodle_admin_notice.'.</p>');
        if ( ( $foodle_meta_result ) || ( $foodle_regex_result ) )
          foodle_pwx_admin_notice__success('<p>'.__('The Foodle metafields definiton was properly set','foodle-for-democracy-poll').'.</p>');
        else
          foodle_pwx_admin_notice__success('<p>'.__('The Foodle metafields definiton did not change','foodle-for-democracy-poll').'.</p>');
      } 
    } else {
      foodle_pwx_admin_notice__error();
    }
  }

  // In case the eMail text was set or updated: check if eMail text is sufficient (min. one word with min. three letters) or needs to be updated and store it as option 'foodle_ph__email_content'
  if ( isset($_POST['foodle_email_content']) ) {
    $foodle_admin_notice = '';
    $foodle_new_email_content = sanitize_text_field(htmlentities(stripslashes($_POST['foodle_email_content'])));
    if ( ( $foodle_new_email_content <> '' ) && ( $foodle_new_email_content === get_option('foodle_email_content') ) ) {
      $foodle_admin_notice .= __('The email content didn\'t change.','foodle-for-democracy-poll');
      foodle_pwx_admin_notice__success('<p>'.$foodle_admin_notice.'</p>');
    }
    else {
      if ( ( preg_match('/[a-zA-Z]{3}/', $foodle_new_email_content) )
          && ( update_option('foodle_email_content', $foodle_new_email_content) ) ) {
        $foodle_admin_notice .= __('The email content was properly stored.','foodle-for-democracy-poll');
        foodle_pwx_admin_notice__success('<p>'.$foodle_admin_notice.'</p>');
      }
      else {
        $foodle_admin_notice .= __('The email content wasn\'t stored due to text missing (looking for at least one word with three letters minimum...)!','foodle-for-democracy-poll');
        foodle_pwx_admin_notice__defined_error('<p>'.$foodle_admin_notice.'</p>');
      }
    }
  }

  // Get the active tab from the $_GET parameter
  $default_tab = 'nothing';
  if ( $foodle_roles_tips ) $default_tab = 'foodle-tips';
  if ( $foodle_roles_settings ) $default_tab = 'foodle-settings';
  if ( $foodle_roles_usage ) $default_tab = 'foodle-usage';
  if ( $foodle_roles_email ) $default_tab = 'edit-email';
  if ( $foodle_roles_sproles ) $default_tab = 'special-roles-users';
  if ( $foodle_roles_sorting ) $default_tab = 'metafield-default-sorting';
  if ( ( $foodle_roles_metafields ) || ( current_user_can('manage_options') ) ) $default_tab = 'define-metafields';

  $tab = ( isset($_GET['tab']) ) ? sanitize_text_field($_GET['tab']) : $default_tab;

  // Admin page should be inside a 'wrap': opening div
  echo '<div class="wrap">';

  // Display the page title
  echo '<h1 class="foodle_ph_-h1">Foodle for Democracy Poll</h1>'; // get_admin_page_title() does not work in all cases for capability 'manage_foodle'...
  echo '<h2 class="foodle_ph_-h2">'.__('An add-on to display poll responses in various ways and much more...','foodle-for-democracy-poll').'</h2>';


  // Specify the path to the plugin's readme.txt file
  $file_path = plugin_dir_path( __FILE__ ).'README.txt';

  // Read the contents of the file into a string
  $file_contents = file_get_contents($file_path);

  // Split the file contents into an array of lines
  $file_lines = explode("\n", $file_contents);

  // Initialize a flag to indicate whether we're in the FAQ section
  $in_faq_section = false;

  // Initialize an empty string to hold the FAQ section
  $faq_section = '';

  // Loop through each line in the file
  foreach ($file_lines as $line) {
    // If we encounter the FAQ section header, set the flag
    if (strpos($line, '== Frequently Asked Questions ==') !== false) {
        $in_faq_section = true;
    }
    // If we encounter the end of the FAQ section, unset the flag and exit the loop
    elseif (strpos($line, '==') === 0 && $in_faq_section) {
        $in_faq_section = false;
        break;
    }
    // If we're in the FAQ section, add the line to the FAQ section string
    elseif ($in_faq_section) {
        $faq_section .= $line . "<br>";
    }
  }

  // Remove any HTML tags from the FAQ section
  //$faq_section = strip_tags($faq_section);

  // Output the FAQs
  //echo str_replace('= ','<strong>',str_replace(' =','</strong>',$faq_section));

  //echo wp_remote_retrieve_body(wp_remote_get(get_site_url().'/wp-admin/plugin-install.php?tab=plugin-information&plugin=foodle-for-democracy-poll&section=faq #section-faq'));


  // Check whether Democracy will keep logs. Otherwise, issue a warning!
  echo foodle_check_keeping_logs();
  
  ?><!-- Here are the tabs -->
    <nav style="text-align:center;" class="nav-tab-wrapper">
      <?php if ( ( current_user_can('manage_options') ) || ( $foodle_roles_metafields ) ): ?><a href="?page=foodle-admin-page&tab=define-metafields" class="nav-tab <?php if($tab==='define-metafields'): ?>nav-tab-active<?php endif; ?>"><?php _e('Define<br>Metafields','foodle-for-democracy-poll')?></a><?php endif; ?>
      <?php if ( ( current_user_can('manage_options') ) || ( $foodle_roles_sorting ) ): ?><a href="?page=foodle-admin-page&tab=metafield-default-sorting" class="nav-tab <?php if($tab==='metafield-default-sorting'): ?>nav-tab-active<?php endif; ?>"><?php _e('Metafield<br>Defaults & Sorting','foodle-for-democracy-poll')?></a><?php endif; ?>
      <?php if ( ( current_user_can('manage_options') ) || ( $foodle_roles_sproles ) ): ?><a href="?page=foodle-admin-page&tab=special-roles-users" class="nav-tab <?php if($tab==='special-roles-users'): ?>nav-tab-active<?php endif; ?>"><?php _e('Special<br>Roles & Users','foodle-for-democracy-poll')?></a><?php endif; ?>
      <?php if ( ( current_user_can('manage_options') ) || ( $foodle_roles_email ) ): ?><a href="?page=foodle-admin-page&tab=edit-email" class="nav-tab <?php if($tab==='edit-email'): ?>nav-tab-active<?php endif; ?>"><?php _e('Edit<br>Email','foodle-for-democracy-poll')?></a><?php endif; ?>
      <?php if ( ( current_user_can('manage_options') ) || ( $foodle_roles_usage ) ): ?><a href="?page=foodle-admin-page&tab=foodle-usage" class="nav-tab <?php if($tab==='foodle-usage'): ?>nav-tab-active<?php endif; ?>"><?php _e('Shortcode<br>Use','foodle-for-democracy-poll')?></a><?php endif; ?>
      <?php if ( ( current_user_can('manage_options') ) || ( $foodle_roles_settings ) ): ?><a href="?page=foodle-admin-page&tab=foodle-settings" class="nav-tab <?php if($tab==='foodle-settings'): ?>nav-tab-active<?php endif; ?>"><?php _e('Foodle<br>Settings','foodle-for-democracy-poll')?></a><?php endif; ?>
      <?php if ( ( current_user_can('manage_options') ) || ( $foodle_roles_tips ) ): ?><a href="?page=foodle-admin-page&tab=foodle-tips" class="nav-tab nav-tab-tips <?php if($tab==='foodle-tips'): ?>nav-tab-active nav-tab-tips-active<?php endif; ?>"><?php _e('Widespread<br>Tips','foodle-for-democracy-poll')?></a><?php endif; ?>
    </nav>

    <div class="tab-content">
    <?php $foodle_please_consult = __('Please consult the \'Help\' tabs at the top and the Tips tab above for detailed explanations and/or use cases.','foodle-for-democracy-poll');
      switch($tab) :
      case 'define-metafields':
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('Define the Metafields for the User Profile','foodle-for-democracy-poll').'</h2>';
        echo '<p>('.$foodle_please_consult.')</p>';
        echo '<p>&nbsp;</p>';
        foodle_define_metafields();
        break;
      case 'metafield-default-sorting':
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('Define Metafield Default Values and their Sorting','foodle-for-democracy-poll').'</h2>';
        echo '<p>('.$foodle_please_consult.')</p>';
        echo '<p>&nbsp;</p>';
        foodle_metafield_defaults_sorting();
        break;
      case 'special-roles-users':
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('Select Special Roles and / or Users for Poll Marking, Hidden Views and eMail Non-Reminders','foodle-for-democracy-poll').'</h2>';
        echo '<p>('.$foodle_please_consult.')</p>';
        echo '<p>&nbsp;</p>';
        foodle_set_special_roles_users();
        break;
      case 'edit-email':
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('Edit the Reminder Email for "Lazybones"','foodle-for-democracy-poll').'</h2>';
        echo '<p>('.$foodle_please_consult.')</p>';
        echo '<p>&nbsp;</p>';
        foodle_edit_email();
        break;
      case 'foodle-usage':
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('Use of Democracy and Foodle shortcodes','foodle-for-democracy-poll').'</h2>';
        echo '<p>('.$foodle_please_consult.')</p>';
        echo '<p>&nbsp;</p>';
        foodle_usage();
        break;
      case 'foodle-settings':
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('Other Settings to Control Foodle','foodle-for-democracy-poll').'</h2>';
        echo '<p>('.$foodle_please_consult.')</p>';
        echo '<p>&nbsp;</p>';
        foodle_settings();
        break;
      case 'foodle-tips':
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('Tips for using Foodle','foodle-for-democracy-poll').'</h2>';
        echo '<p>('.$foodle_please_consult.')</p>';
        echo '<p>&nbsp;</p>';
        foodle_tips();
        break;
      default:
        echo '<p>&nbsp;</p>';
        echo '<h2>'.__('There\'s no Foodle access available!','foodle-for-democracy-poll').'</h2>';
        echo '<p>&nbsp;</p>';
        break;
    endswitch; ?>
    </div>

  <?php

  echo '<p>&nbsp;</p>';

  if ( ( isset($foodle_scroll_up_button_visible['foodle_admin']) ) && ( $foodle_scroll_up_button_visible['foodle_admin'] ) ) foodle_provide_scroll_up_button();

  // Admin page should be inside a 'wrap': closing div
  echo '</div>';
}
