<?php
/**
 * DACdb Plus
 *
 * @category  Plugin
 * @package   DACdbPlus
 * @author    Member Minder Pro, LLC <wordpress@memberminderpro.com>
 * @copyright 2024 Member Minder Pro, LLC
 * @license   Apache License 2.0
 * @link      https://memberminderpro.com
 *
 * @wordpress-plugin
 * Plugin Name: DACdb Plus
 * Plugin URI:  https://dacdb.com/wordpress
 * Description: Easily publish your organization's data to WordPress.
 * Version:     3.1.37
 * Author:      Member Minder Pro, LLC
 * Author URI:  https://memberminderpro.com
 * Text Domain: mmpdb
 * License:     Apache License 2.0
 * License URI: https://www.apache.org/licenses/LICENSE-2.0
 */

//SECTION - Global Variable Definitions
function set_mmpdb_plugin_version()
{
    if (!function_exists('get_plugin_data')) {
        require_once(ABSPATH . 'wp-admin/includes/plugin.php');
    }

    $plugin_data = get_plugin_data(__FILE__);
    $version = $plugin_data['Version'];

    define('MMPDB_PLUGIN_VERSION', $version);
}

$plugin = plugin_basename(__FILE__);
// Ensure the plugin version is set.
set_mmpdb_plugin_version();

global $plugin_version;
$plugin_version = MMPDB_PLUGIN_VERSION;
/**
 * Debug mode flag.
 *
 * @var bool
 */
$fDebug = false;

/**
 * Data path.
 *
 * @var string
 */
$data_path = '';

/**
 * Data file.
 *
 * @var string
 */
$data_file = '';

/**
 * Public Path.
 *
 * @var string
 */
$public_path = '';

/**
 * Retrieves the DACdb plus options.
 *
 * @var array $options The DACdb plus options.
 */


/**
 * Category ID
 *
 * @var string
 */
$catid = '';

//SECTION - Required Files and Libraries

require_once plugin_dir_path(__FILE__) . 'plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
    'https://wordpress.dacdb.com/plugins/dacdbplus/dacdbplus.json',
	__FILE__,
    'dacdbplus'
);

require_once plugin_dir_path( __FILE__ ) . 'includes/utilities.php';
global $options;
$options = get_mmp_options();
/**
 * Echoes out the CSS stylesheets required by the DACdb Plus plugin.
 *
 * This function outputs multiple <link> tags that link to CSS stylesheets needed by the DACdb Plus plugin.
 * The stylesheets include bootstrap.css, dacdb-plus.css, custom.css, and fullcalendar.css.
 * The URLs of the stylesheets are generated using the `plugins_url` function and include the plugin version for cache-busting.
 * The function is called by the WordPress action `wp_head`.
 *
 * @return $output - A string containing the HTML <link> tags that link to the CSS stylesheets.
 */
function Dacdb_css()
{
    $output = '';

    $output .= '<link rel="stylesheet" id="dacdb-bs" href="' . plugins_url('bootstrap/bootstrap.css?ver=' . $GLOBALS['plugin_version'],  __FILE__) . '" type="text/css" media="all" />';
    $output .= '<link rel="stylesheet" id="dacdb-css" href="' . plugins_url('css/dacdb-plus.css?ver=' . $GLOBALS['plugin_version'], __FILE__) . '" type="text/css" media="all" />';
    $output .= '<link rel="stylesheet" id="dacdb-custom-css" href="' . plugins_url('css/custom.css?ver=' . $GLOBALS['plugin_version'], __FILE__) . '" type="text/css" media="all" />';
    // $output .= '<link rel="stylesheet" id="dacdb-fullcalendar" href="' . plugins_url('css/fullcalendar.css?ver=' . $GLOBALS['plugin_version'], __FILE__) . '" type="text/css" media="all" />';
    // $output .= '<link rel="stylesheet" id="dacdb-tooltip" href="' . plugins_url('css/tooltip.css?ver=' . $GLOBALS['plugin_version'], __FILE__) . '" type="text/css" media="all" />';
    $output .= '<link rel="stylesheet" id="dacdb-sm" href="' . plugins_url('css/sm.css?ver=' . $GLOBALS['plugin_version'], __FILE__) . '" type="text/css" media="all" />';
    //$output .= '<link rel="stylesheet" id="dacdb-fontawesome" href="' . plugins_url('/css/Font-Awesome6/css/all.css?ver=' . $GLOBALS['plugin_version'], __FILE__) . '" type="text/css" media="all" />';

    echo $output;
}

add_action('wp_head', 'Dacdb_css');

require_once plugin_dir_path( __FILE__ ) . 'includes/admin.php';

/**
 * Retrieve the basename of the current plugin's main file.
 *
 * The `plugin_basename()` function is a WordPress function that takes a file path as its parameter and returns
 * the basename of that file. Here, it is used to retrieve the basename of the current plugin's main file and store
 * it in the variable `$plugin` for future reference.
 *
 * @var string $plugin The basename of the current plugin's main file.
 */
$plugin = plugin_basename(__FILE__);

//SECTION - Error Handling

/**
 * Displays an error message indicating that the DACdb plugin account number is missing.
 *
 * This function outputs an error message in a div container with appropriate styling.
 * The error message states that the DACdb plugin account number is required and prompts the user to enter their account number.
 * The text of the error message is translated using the `__()` or `_e()` function with the text domain 'dacdbplus'.
 */

 function dacdb_missing_district()
 {
     global $pagenow;
 
     // Store the error message in a variable
     $error_message = __('A valid district, grand lodge, or account number is required.', 'dacdbplus');

     // Define the URL of your specific settings page.
     $settings_url = admin_url('options-general.php?page=mmp-settings');
     // Define the URL for your external customer support page.
     $support_url = 'https://www.dacdbsupport.com';
 
     // Check if the current page is the settings page
     if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
         ?>
             <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                 <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
             </div>
         <?php
     } else {
         ?>
             <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                 <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                 <!-- Container for buttons to ensure they stay together -->
                 <div>
                     <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                         <?php _e('Go to Settings', 'dacdbplus'); ?>
                     </a>
                     <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                         <?php _e('Get Support', 'dacdbplus'); ?>
                     </a>
                 </div>
             </div>
         <?php
     }
 }
 
function dacdb_missing_club()
{
    global $pagenow;

    // Store the error message in a variable
    $error_message = __('A valid club, lodge, or entity number is required. ', 'dacdbplus');

    // Define the URL of your specific settings page.
    $settings_url = admin_url('options-general.php?page=mmp-settings');
    // Define the URL for your external customer support page.
    $support_url = 'https://www.dacdbsupport.com';

    // Check if the current page is the settings page
    if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
        ?>
            <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
            </div>
        <?php
    } else {
        ?>
            <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                <!-- Container for buttons to ensure they stay together -->
                <div>
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                        <?php _e('Go to Settings', 'dacdbplus'); ?>
                    </a>
                    <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                        <?php _e('Get Support', 'dacdbplus'); ?>
                    </a>
                </div>
            </div>
        <?php
    }
}

function dacdb_missing_system()
{
    global $pagenow;
    
    // Store the error message in a variable
    $error_message = __('System selection is missing or invalid.', 'dacdbplus');

    // Define the URL of your specific settings page.
    $settings_url = admin_url('options-general.php?page=mmp-settings');
    // Define the URL for your external customer support page.
    $support_url = 'https://www.dacdbsupport.com';

    // Check if the current page is the settings page
    if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
        ?>
            <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
            </div>
        <?php
    } else {
        ?>
            <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                <!-- Container for buttons to ensure they stay together -->
                <div>
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                        <?php _e('Go to Settings', 'dacdbplus'); ?>
                    </a>
                    <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                        <?php _e('Get Support', 'dacdbplus'); ?>
                    </a>
                </div>
            </div>
        <?php
    }
}

function dacdb_missing_subscription()
{
    global $pagenow;
    
    // Store the error message in a variable
    $error_message = __('A valid DACdb plugin subscription is required, please check your settings or contact customer support.', 'dacdbplus');

    // Define the URL of your specific settings page.
    $settings_url = admin_url('options-general.php?page=mmp-settings');
    // Define the URL for your external customer support page.
    $support_url = 'https://www.dacdbsupport.com';

    // Check if the current page is the settings page
    if ($pagenow == 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'mmp-settings') {
        ?>
            <div class="updated settings-error error is-dismissible" style="padding: 10px;">
                <h2 style="margin: 0px;">DACdb Plus: <?php echo $error_message; ?></h2>
            </div>
        <?php
    } else {
        ?>
            <div class="updated settings-error error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0;"><?php echo '<a href="' . esc_url($settings_url) . '" title="Click to access DACdb Plus plugin settings">DACdb Plus</a>: ' . $error_message . ''; ?></h2>
                <!-- Container for buttons to ensure they stay together -->
                <div>
                    <a href="<?php echo esc_url($settings_url); ?>" class="button button-primary" style="margin: 10px;">
                        <?php _e('Go to Settings', 'dacdbplus'); ?>
                    </a>
                    <a href="<?php echo esc_url($support_url); ?>" class="button button-secondary" style="margin: 10px 0;">
                        <?php _e('Get Support', 'dacdbplus'); ?>
                    </a>
                </div>
            </div>
        <?php
    }
}

//!SECTION - Error Handling

class InvalidShortcodeException extends Exception
{
}

//SECTION - Class dacdb_plus

if (!class_exists('dacdb_plus')) {
    /**
     * Class dacdb_plus
     *
     * Description: This class defines a plugin called 'dacdb_plus' with various methods and functions.
     */
    class dacdb_plus
    {

        /**
         * Constructor method.
         *
         * Registers the plugin, adds a shortcode, and enqueues JavaScript files.
         */

        function dacdb_plus_register()
        {
            register_widget('DACDB_Plus_Widget');
        }

        // Section - Enqueue Dependencies

        function __construct()
        {
            //Register Plugin
            add_action('widgets_init', array($this, 'dacdb_plus_register'));
            //Add Core Functionality Shortcode
            add_shortcode('dacdb_plus', array($this, 'dacdb_plus_function'));
            // Add JavaScript Files
            add_action('admin_enqueue_scripts', array($this, 'dacdb_plus_admin_js')); // Admin scripts
            add_action('wp_enqueue_scripts', array($this, 'enqueue_resources')); // Front-end scripts and styles
        }
        
        public function enqueue_resources() {
            // Enqueue front-end scripts
            wp_enqueue_script('dacdb-plus-js', plugin_dir_url(__FILE__) . 'js/dacdb_plus.js', array('jquery'), $GLOBALS['plugin_version'], true);
            wp_enqueue_script('pagination', plugins_url('js/pagination.js', __FILE__), array('jquery'), $GLOBALS['plugin_version'], true);
            wp_enqueue_script('moment2', plugins_url('js/moment.min.js', __FILE__), array('jquery'), $GLOBALS['plugin_version'], true);
            wp_enqueue_script('fullcalendar', plugins_url('js/index.global.js', __FILE__), array('jquery'), $GLOBALS['plugin_version'], true);
            
            // Conditionally enqueue FontAwesome
            global $post;
            if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'dacdb_plus')) {
                if (!wp_style_is('font-awesome', 'enqueued') && !wp_style_is('dacdb-fontawesome', 'enqueued')) {
                    wp_enqueue_style('dacdb-fontawesome', 'https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.2/css/all.css', array(), '6.4.2', 'all');
                }
            }
        }

        /**
         * Activate method.
         *
         * Does nothing as the plugin doesn't use WordPress classes or functions.
         */

        public static function activate()
        {
            // Do nothing plug in does not use Wordpress classes or functions
        }
        /**
         * Deactivate method.
         *
         * Does nothing as the plugin doesn't use WordPress classes or functions.
         */
        public static function deactivate()
        {
            // Do nothing plug in does not use Wordpress classes or functions
        }
        /**
         * Enqueues the 'dacdb-admin-js' JavaScript file.
         * This is for loading the admin dashboard scripts only
         */
        public function dacdb_plus_admin_js()
        {
            wp_enqueue_script('dacdb-admin-js', plugin_dir_url(__FILE__) . 'js/dacdb_admin_scripts.js', array('quicktags'), $GLOBALS['plugin_version'], true);
        }
        /**
         * Enqueues the 'dacdb-plus-js' JavaScript file.
         * These are the front-end scripts
         */

        public function dacdb_plus_js()
        {
            wp_enqueue_script('dacdb-plus-js', plugin_dir_url(__FILE__) . 'js/dacdb_plus.js', array('quicktags'), $GLOBALS['plugin_version'], true);
        }

        /**
         * Enqueues the 'pagination' JavaScript file.
         */
        public function pagination()
        {
            wp_enqueue_script('pagination', plugins_url('js/pagination.js', __FILE__), '', $GLOBALS['plugin_version']);
        }

        /**
         * Enqueues the 'moment2' JavaScript file.
         */
        public function moment2()
        {
            wp_enqueue_script('moment2', plugins_url('js/moment.min.js', __FILE__), '', $GLOBALS['plugin_version']);
        }
        /**
         * Enqueues the 'fullcalendar' JavaScript file.
         */
        public function fullcalendar()
        {
            // wp_enqueue_script('fullcalendar', plugins_url('js/fullcalendar.min.js', __FILE__), '', $GLOBALS['plugin_version']);
            wp_enqueue_script('fullcalendar', plugins_url('js/index.global.js', __FILE__), '', $GLOBALS['plugin_version']);
        }

        // Method to conditionally enqueue FontAwesome based on shortcode presence
        public function maybe_enqueue_fontawesome()
        {
            global $post;
            if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'dacdb_plus')) {
                add_action('wp_enqueue_scripts', array($this, 'enqueue_fontawesome'));
            }
        }

        public function enqueue_fontawesome()
        {
            if (!wp_style_is('font-awesome', 'enqueued') && !wp_style_is('dacdb-fontawesome', 'enqueued')) {
                wp_enqueue_style('dacdb-fontawesome', 'https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.2/css/all.css', array(), '6.4.2', 'all');
            }
        }
        

        //ANCHOR - Process Shortcode
        //FIXME - This is the main function that processes the shortcode
        /**
         * Processes the 'dacdb_plus' shortcode.
         *
         * @param array $atts An associative array of shortcode attributes.
         *
         *        Supported attributes:
         *        - 'show' (string): The type of content to display.
         *        - 'storyid' (string): The ID of the story.
         *        - 'catid' (string): The ID of the category.
         *        - 'catids' (string): Comma-separated IDs of categories.
         *        - 'separator' (string): The separator for displayed items.
         *        - 'imgwidth' (string): The pixel width of the thumbnail image in member galleries.
         *        - 'org' (string): Deprecated attribute (organization).
         *        - 'orgyear' (string): The year of the organization.
         *        - 'description' (string): The description of the content.
         *        - 'folder' (string): The folder for documents.
         *        - 'sort' (string): The sorting order for clubs.
         *        - 'cid' (string): The ID of the committee.
         *        - 'row' (string): The number of rows to display.
         *        - 'style' (string): The style of the content.
         *        - 'icon' (int): Whether to display icons (1 for true, 0 for false).
         *        - 'size' (int): The size of the content.
         *        - 'date' (int): Whether to display dates (1 for true, 0 for false).
         *        - 'club_id' (string): The ID of the club.
         *        - 'mailto' (string): A system member userid to receive contact form data.
         *
         * @return string The accumulated output of the shortcode processing.
         */
        public function dacdb_plus_function($atts)
        {
            global $plugin_version, $public_path, $fDebug, $data_path, $file_path, $options;
            //NOTE - Handle Shortcode Attributes
            extract(
                shortcode_atts(
                    array(
                        'show' => '',
                        'storyid' => '',
                        'catid' => '',
                        'catids' => '',
                        'separator' => '',
                        'display' => '',            //NOTE -  removed
                        'pagetitle' => '',          //NOTE -  removed
                        'org' => '',                //NOTE -  depreciated
                        'orgyear' => '',
                        'description' => '',
                        'imgwidth' => '',
                        'folder' => '',             //NOTE -  for documents
                        'sort' => '',               //NOTE -  where clubs meet
                        // committee                //REVIEW - not used
                        'cid' => '',
                        'row' => '',
                        'style' => '',              //NOTE -  New
                        // documents                //REVIEW - not used
                        'icon' => 1,
                        'size' => 1,
                        'date' => 1,
                        'club_id' => '',            //NOTE - Display club calendar on district website
                        'mailto' => '',
                    ),
                    $atts,
                    'dacdb_plus'
                )
            );

            $pagedata = "";     //NOTE -  output for short code need to be returned.  so this variable accumulates the output.  Each short code does their own
            //NOTE -  get the settings here - update widgets at bottom if this changes!!!
            $options = get_mmp_options();
            setDataPath();   //NOTE - ShortCode DACdb or iMembersDB paths

            if ($data_path == '') {
                $pagedata .= "=================================================================<BR>";
                $pagedata .=  "Missing System selection under Plugin Settings!<BR>";
                $pagedata .=  "data_path=" . $data_path;
                $pagedata .=  "=================================================================<BR>";
                $pagedata .=  "<BR>";
            }

            //REVIEW - $subscription = file_get_contents($data_path.'wp_subscription.cfm?AccountID='.$options['dacdb_district'].'&ClubID='.$options['dacdb_club']);
            $xml = simplexml_load_file($data_path . 'wp_subscription2.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club']);  // mrl changed it back to wp_subscription.cfm
            $int = (int)$xml->status;
            if ( $int != 1 ) {
                $pagedata .= "=================================================================<BR>";
                $pagedata .=  "&nbsp; &nbsp;  Missing subscription record. System=" . $options['dacdb_system'] . ", AccountID=" . $options['dacdb_district'] . ", ClubID=" . $options['dacdb_club'] . "<BR>";
                $pagedata .=  "&nbsp; &nbsp;  Please contact: support@memberminderpro.com<BR>";
                $pagedata .=  "data_path=" . $data_path . "<br>";
                $pagedata .=  "subscription=" . $xml->status . "<br>";
                $pagedata .=  "ip_server=" . $_SERVER['SERVER_ADDR'] . "<br>";
                $pagedata .=  "php version=" . phpversion() . "<br>";
                if ( \filter_var( \ini_get('allow_url_fopen'), \FILTER_VALIDATE_BOOLEAN ) ) {
                    $pagedata .=  "allow_url_fopen is configured properly in php.ini". "<br>";
                }
                else {
                    $pagedata .=  "allow_url_fopen is NOT configured properly in php.ini". "<br>";
                }
                if ($fDebug) {
                    $pagedata .=  "&nbsp; &nbsp;  url=" . $data_path . 'wp_subscription2.cfm?AccountId=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . "<BR>";
                }
                $pagedata .=  "=================================================================<BR>";
                $pagedata .=  "<BR>";
            }
           

            
            if ($fDebug) { 
                $districtOrAccount = $options['dacdb_system'] == 'dacdb' ? 'District' : 'Account';
                $pagedata .= '
                <div class="debug"><div class="info-msg"><i class="fa fa-info-circle"></i> <strong>Debug mode <em>ON</em></strong> </div>
                    <h5>' . dacdb_debug_shortcode($GLOBALS['post'], $atts) . '</h5>
                    <pre>
                        <dl>
                            <dt>Plugin Version</dt><dd>' . (isset($plugin_version) ? $plugin_version : 'Not set') . '</dd>
                            <dt>' . $districtOrAccount . ' ID</dt><dd>' . $options['dacdb_district'] . '</dd>
                            <dt>Club ID</dt><dd>' . $options['dacdb_club'] . '</dd>
                            <dt>System</dt><dd>' . (isset($options['dacdb_system']) ? $options['dacdb_system'] : 'Not set') . '</dd>
                            <dt>CatID</dt><dd>' . (isset($GLOBALS['catid']) && $GLOBALS['catid'] !== '' ? $GLOBALS['catid'] : 'Not set') . '</dd>
                            <dt>data_path</dt><dd>' . (isset($data_path) ? $data_path : 'Not set') . '</dd>
                            <dt>file_path</dt><dd>' . (isset($file_path) ? $file_path : 'Not set') . '</dd>
                            <dt>public_path</dt><dd>' . (isset($GLOBALS['public_path']) && $GLOBALS['public_path'] !=='' ? $GLOBALS['public_path'] : 'Not set') . '</dd>
                            <dt>subscription</dt><dd>' . (isset($xml->status) ? $xml->status : 'Not set') . '</dd>
                            <dt>ip_server</dt><dd>' . (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 'Not set') . '</dd>
                            <dt>php version</dt><dd>' . (null!==phpversion() ? phpversion() : 'Not set') . '</dd>
                        </dl>
                    </pre>';
                //print("<div><strong>XML Data:</strong><pre>" . print_r($xml, true) . "</pre></div>");
                //print("<div><strong>GLOBALS:</strong><pre>".var_dump($GLOBALS)."</pre></div>");
                //print("<div class=\"info-msg\"><strong>Options: </strong><pre>" . var_dump($options) . "</pre></div>");
                //print("<div class=\"info-msg\"><strong>Show:</strong> <pre>" . var_dump($show) . "</pre></div>");
            }
            try {
                //NOTE - wcm master, club_meetings and meeting_info deprecated
                $show = strtolower(str_replace(' ', '', $show));
                switch ($show) {
                    case 'areas':
                        $pagedata .=  dacdb_areas($atts);
                        break;
                    case 'birthdays':
                        $pagedata .=  dacdb_birthdays($atts);
                        break;
                    case 'calendar':
                        $pagedata .= dacdb_calendar($atts);
                        break;
                    case 'cog':
                        $pagedata .=  dacdb_cog($atts);
                        break;
                    case 'club_meetings':
                        $pagedata .=  dacdb_club_meetings($atts);
                        break;
                    case 'club_presidents':
                        $pagedata .=  dacdb_club_presidents($atts);
                        break;
                    case 'clubleaders':
                        $pagedata .=  dacdb_clubleaders($atts);
                        break;
                    case 'committee':
                        $pagedata .=  dacdb_committee($atts);
                        break;
                    case 'committee_leaders':
                        $pagedata .=  dacdb_committee_leaders($atts);
                        break;
                    case 'committees':
                        $pagedata .=  dacdb_committees($atts);
                        break;
                    case 'events':
                    case 'd_events':
                        // If the case is 'd_events', set type to 'district'
                        if ($show === 'd_events') {
                            $atts['type'] = 'district';
                        }
                        $pagedata .=  dacdb_events($atts);
                        break;
                    case 'd_leaders':
                        $pagedata .=  dacdb_d_leaders($atts);
                        break;
                    case 'dcc':
                        $pagedata .=  dacdb_dcc($atts);
                        break;
                    case 'documents':
                        $pagedata .=  dacdb_documents($atts);
                        break;
                    case 'leaders':
                        $pagedata .=  dacdb_leaders($atts);
                        break;
                    case 'map':
                        $pagedata .=  dacdb_map($atts);
                        break;
                    case 'meeting_info':
                        $pagedata .=  dacdb_meeting_info($atts);
                        break;
                    case 'members':
                        $pagedata .=  dacdb_members($atts);
                        break;
                    case 'newsletter':
                    case 'newsletters':
                        $pagedata .=  dacdb_newsletter($atts);
                        break;
                    case 'sponsors':
                        $pagedata .=  dacdb_sponsors($atts);
                        break;
                    case 'speakers':
                        $pagedata .=  dacdb_speakers($atts);
                        break;
                    case 'stories':
                        $pagedata .= dacdb_stories($atts);
                        break;
                    case 'wcm':
                        $pagedata .=  dacdb_wcm($atts);
                        break;
                    case 'jsonclubleaders':
                        $pagedata .=  dacdb_jsonclubleaders($atts);
                        break;

                    default:
                        throw new InvalidShortcodeException("Invalid shortcode 'show' value encountered: <em>{$show}</em>");
                        //NOTE - wcm master, club_meetings and meeting_info deprecated
                }
            } catch (InvalidShortcodeException $e) {
                // Handle the exception, such as logging the error or displaying a user-friendly message
                $pagedata .= "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>{$e->getMessage()}</div>";
            }

            return $pagedata;
        }
    }
}


//!SECTION - Class dacdb_plus


//SECTION Process Shortcode Functions

//ANCHOR - Show Areas
function dacdb_areas($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $areas = '';

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && $atts['imgwidth'] > 0 ? $atts['imgwidth'] : 150);
    $rolekeys   = isset($atts['rolekeys']) ? $atts['rolekeys'] : 'AG';
    $region     = isset($atts['region']) ? $atts['region'] : '0';
    $style      = isset($atts['style']) ? $atts['style'] : '1';

    if ($fDebug) {
        $areas .= "=================================================================<BR>";
        $areas .= "function dacdb_areas called<br>";
        $areas .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $areas .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $areas .= "imgWidth=" . $thumbnail_width . "<br>";
        $areas .= "RoleKeys=" . $rolekeys . "<br>";
        $areas .= "Style=" . $style . "<br>";
        $areas .= "Thumbnail Width =" . $options['thumbnail_width'] . "<br>";
        $areas .= "url=" . $data_path . 'wp_areav2.cfm?AccountID=' . $options['dacdb_district'] . '&rolekeys=' . $rolekeys . '&Region=' . $region . "<br>";
        $areas .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_areav2.cfm?AccountID=' . $options['dacdb_district'] . '&rolekeys=' . $rolekeys . '&Region=' . $region . '&R=' . rand());
    if (strlen($xml) == 0) {
        $areas .= 'There are no areas/regions to display at this time.';
        return $areas;
    }


    // Display areas based on the provided style
    switch ($style) {

        case '0':   // linear list of AGs (1 column)
        case '1':   // linear list of AGs (1 column)
            $counter = 1;
            $areas .= '<table  style="vertical-align: top;padding:0;border:0 !important;">';
            foreach ($xml->area as $area) {
                $officer_total = count($area->officers);
                if ($officer_total > 0) {
                    foreach ($area->officers->officer as $officer) {
                        $areas .= '<tr><td style="padding-right:15px;width:150px;vertical-align: top;padding:5px;border:0 !important;"><img src="' . $officer->imgpath . '' . $officer->image . '" style="aspect-ratio: 4 / 5; width: ' . $thumbnail_width  . 'px; object-fit: cover;" width="' . $thumbnail_width  . '"></td>';
                        $areas .= '<td valign="top" style="vertical-align: top;padding:0;border:0 !important;">';
                        $areas .= '<strong>'. $officer->areaposition . ' ' .  $area->regionlabel . ' ' . $area->area . '</strong><br>' . $officer->membername . '';
                        $areas .= '<br><strong>Club:</strong> ' . $officer->clubname . '<br><strong>Area ' . $area->area . ' Clubs:</strong> ' . $area->areaclubs . '';
                        $areas .= '<br><br><a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $officer->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
                        $areas .= '</td></tr>';
                        $areas .= '<tr><td colspan="2" style="vertical-align: top;padding:0;border:0 !important;"><hr></td></tr>';
                        $counter = $counter + 1;
                    }
                }
            }
            $areas .= '</table>';
            return $areas;
            break;

        case '2':    // areas grouped
            $counter = 1;
            foreach ($xml->area as $area) {
                $areas .= '<h3>'. $area->regionlabel . ' ' . $area->area . '</h3><br>';
                $areas .= '<table  style="border:0 !important; vertical-align: top;padding:0;border:5 !important;" width="100%">';
                $areas .= '    <tr>';
                $areas .= '        <td style="border:0 !important;vertical-align: top; padding:0;" >';

                $officer_total = count($area->officers);
                if ($officer_total > 0) {
                    $areas .= '            <table style="width: 400px; vertical-align: top;padding:0; border:0">';
                    foreach ($area->officers->officer as $officer) {
                        $areas .= '            <tr>';
                        $areas .= '                <td style="padding-right:15px;width:150px;vertical-align: top;padding:5px; border:0 !important;"><img src="' . $officer->imgpath . '' . $officer->image . '" style="aspect-ratio: 4 / 5; width: ' . $thumbnail_width  . 'px; object-fit: cover;" width="' . $thumbnail_width  . '"></td>';
                        $areas .= '                <td valign="top" style="width: 250px; vertical-align: top;padding:0;border:0 !important;">';
                        $areas .= '                    <strong>'. $officer->areaposition . '</strong><br/>';
                        $areas .= '                    '. $officer->membername . '<br/>';
                        $areas .= '                    <strong>Club:</strong> ' . $officer->clubname . '<br/>';
                        $areas .= '                    <a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $officer->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
                        $areas .= '                </td>';
                        $areas .= '            </tr>';
                        $counter = $counter + 1;
                    }
                    $areas .= '        </table>';
                }
                $areas .= '        </td>';
                $areas .= '        <td style="border:0 !important;vertical-align: top; padding:0;">';
                $areas .= '            <strong>Area ' . $area->area . ' Clubs:</strong> <br />';
                $areas .= '            ' . $area->areaclubs . '<br />';
                $areas .= '        </td>';
                $areas .= '    </tr>';
                $areas .= '<tr><td colspan="2" style="vertical-align: top;padding:0;border:0 !important;"><hr></td></tr>';
                $areas .= '</table>';
            }
            return $areas;
            break;

            case '3':    // areas grouped - list clubs
                $counter = 1;
                foreach ($xml->area as $area) {
                    $clubs = explode(', ', $area->areaclubs);

                    $areas .= '<h3>'. $area->regionlabel . ' ' . $area->area . '</h3><br>';
                    $areas .= '<table  style="vertical-align: top;padding:0;border: 0 !important;">';
                    $areas .= '    <tr>';
                    $areas .= '        <td style="border:0 !important; vertical-align: top; padding:0; width: 400px;" >';

                    $officer_total = count($area->officers);
                    if ($officer_total > 0) {
                        $areas .= '            <table style="vertical-align: top;padding:0; border:0 ">';
                        foreach ($area->officers->officer as $officer) {
                            $areas .= '            <tr>';
                            $areas .= '                <td style="padding-right:15px;width:150px;vertical-align: top;padding:5px; border:0 !important;"><img src="' . $officer->imgpath . '' . $officer->image . '" style="aspect-ratio: 4 / 5; width: ' . $thumbnail_width  . 'px; object-fit: cover;" width="' . $thumbnail_width  . '"></td>';
                            $areas .= '                <td valign="top" style="width: 250px; vertical-align: top;padding:0;border:0 !important;">';
                            $areas .= '                    <strong>'. $officer->areaposition . '</strong><br/>';
                            $areas .= '                    '. $officer->membername . '<br/>';
                            $areas .= '                    <strong>Club:</strong> ' . $officer->clubname . '<br/>';
                            $areas .= '                    <a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $officer->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
                            $areas .= '                </td>';
                            $areas .= '            </tr>';
                            $counter = $counter + 1;
                        }
                        $areas .= '        </table>';
                    }
                    $areas .= '        </td>';
                    $areas .= '        <td align="left" style="border: 0!important;vertical-align: top; padding:0;">';
                    $areas .= '            <strong>Area ' . $area->area . ' Clubs:</strong> <br />';
                    $areas .= '            <UL>';
                    foreach ($clubs as $Club) {
                        $areas .= '            <LI>' .  $Club . '</LI>';
                      }
                    $areas .= '            </UL>';
                    $areas .= '        </td>';
                    $areas .= '    </tr>';
                    $areas .= '<tr><td colspan="2" style="vertical-align: top;padding:0;border:0 !important;"><hr></td></tr>';
                    $areas .= '</table>';
                }
                return $areas;
                break;
        default:
            $areas .= "=================================================================<BR>";
            $areas .= "&nbsp;&nbsp;&nbsp;Invalid style selected [" . $style . "]<BR>";
            $areas .= "=================================================================<BR>";
            return $areas;
            break;
    }
    return $areas;
}



//ANCHOR - Show Birthdays
function dacdb_birthdays($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $members = '';
    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && isset($atts['imgwidth']) > 0 ? $atts['imgwidth'] : 150);

    if ($fDebug) {
        $members .= '<div class="info-msg"><i class="fa fa-info-circle"></i>Debug Mode is On</div>';
        $members .= '<div class="debug">function <em>dacdb_birthdays</em> called<br>';
        $members .= 'AccountID: ' . $options['dacdb_district'] . '<br>';
        $members .= 'ClubID: ' . $options['dacdb_club'] . '<br>';
        $members .= 'URL: <a href="' . $data_path . 'wp_birthdays.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '" target="DEBUG">' . $data_path . 'wp_birthdays.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '</a><br>';
        $members .= "</div>";
    }

    $xml = simplexml_load_file($data_path . 'wp_birthdays.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
    if (strlen($xml) == 0) {
        $members .= 'There are no upcoming birthdays at this time.';
        return $members;
    }

    $counter = 1;
    $members .= '<div class="grid">';
    foreach ($xml->birthday as $birthday) {
        $members .= '<div class="dac-col-6-12" style="overflow:hidden;margin-bottom:20px;">';
        if ($birthday->image == '') {
            $members .= '<div style="width:200px; float:left; min-height: 100px;"><img src=' . plugins_url('img/no_image.jpg', __FILE__) . '" style="aspect-ratio: 4 / 5; width: ' . $thumbnail_width  . 'px; object-fit: cover;" width="' . $thumbnail_width  . '"></div>';
        } else {
            $members .= '<div style="width:200px; float:left; min-height: 100px;"><img src="' . $birthday->image . '" style="aspect-ratio: 4 / 5; width: ' . $thumbnail_width  . 'px; object-fit: cover;" width="' . $thumbnail_width  . '"></div>';
        }
        $members .= '<strong>' . $birthday->membername . '</strong><br>';
        if ($birthday->clubid > 0)
            $members .= $birthday->clubname . '<br />';
        $members .= $birthday->birthday . '<br>';
        $members .= '</div>';
        $counter = $counter + 1;
    }
    $members .= '</div>';
    return $members;
}

//ANCHOR - Show Leaders
/**
 * Generates and displays a list of leaders for a club, chapter, or branch.
 *
 * @param array $atts An associative array of attributes for the function.
 * @return string The HTML markup for displaying the list of leaders.
 */
function dacdb_leaders($atts)
{
    global $fDebug, $data_path, $file_path, $options;
    $members = ''; // Initialize the variable to store the generated HTML markup for leaders

    $account_id = $options['dacdb_district']; // Retrieve the AccountID from options
    $club_id    = $options['dacdb_club']; // Retrieve the ClubID from options

    // Set leaders_per_row attribute or use default value from options if not specified
    // If leaders_per_row is not set, use the default from the options, or 1 if options is empty.

    if (isset($atts['leaders_per_row']) && $atts['leaders_per_row'] == '') {
        if (isset($options['leaders_per_row']) && $options['leaders_per_row'] != '') {
            $atts['leaders_per_row'] = $options['leaders_per_row'];
        } else {
            $atts['leaders_per_row'] = 1;
        }
    }

    // Set default value for leaders_per_row if not specified in options
    if (isset($options['leaders_per_row']) && $options['leaders_per_row'] == '')
        $atts['leaders_per_row'] = 1;

    // Set leader_pics attribute or use default value from options if not specified
    if (isset($atts['leader_pics']) && $atts['leader_pics'] == '')
        $atts['leader_pics'] = $options['leader_pics'];

    // Set default value for leader_pics if not specified in options
    if (isset($atts['leader_pics']) && $options['leader_pics'] == '')
        $atts['leader_pics'] = 1;

    // Set leaders_contact_link attribute or use default value from options if not specified
    if (isset($atts['leaders_contact_link']) && $atts['leaders_contact_link'] == '')
        $atts['leaders_contact_link'] = $options['leaders_contact_link'];

    // Set default value for leaders_contact_link if not specified in options
    if (isset($atts['leaders_contact_link']) && $options['leaders_contact_link'] == '')
        $atts['leaders_contact_link'] = 1;

    // Set flex attribute or use 'N' as default value if not specified
    if (isset($atts['flex']) && $atts['flex'] == '')
        $atts['flex'] = 'N';

    // Check if the ClubID is 0, and return an error message if so
    if ($club_id == 0) {
        $members .= "=================================================================<BR>";
        $members .= "Error: This function can only be used to display club, chapter, branch leaders. The ClubID configured is  0.<br>";
        $members .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $members .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $members .= "=================================================================<BR>";
        return $members;
    }

    // If debug mode is enabled, generate a debug message with function information
    if ($fDebug) {
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_leaders called<br>";
        $members .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $members .= "data_file=" . $data_file . "<br>";
        $members .= "data_path=" . $data_path . "<br>";
        $members .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $members .= "leaders_per_row=" . $options['leaders_per_row'] . "<br>";
        $members .= "leaders_per_row override=" . $atts['leaders_per_row'] . "<br>";
        $members .= "leader_pics=" . $options['leader_pics'] . "<br>";
        $members .= "leader_pics override=" . $atts['leader_pics'] . "<br>";
        $members .= "flex=" . $atts['flex'] . "<br>";
        $members .= "URL=" . $data_path . 'wp_leaders.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '<br>';
        $members .= "=================================================================<BR>";
    }

    // Load the XML data containing leaders information
    $xml = simplexml_load_file($data_path . 'wp_leaders.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&R=' . rand());

    // If XML is empty, return a message indicating no leaders to display
    if (strlen($xml) == 0) {
        $members .= 'There are no club leaders to display at this time.';
        return $members;
    }

    // Loop through each leader and generate HTML markup for their information
    $counter = 1;
    $lastCounter = count($xml->leader);
    $grid_counter = 0;
    foreach ($xml->leader as $leader) {
        $grid_counter = $grid_counter + 1;

        // Force single row if leaders_per_row is set to 1
        if ($options['leaders_per_row'] == 1) {
            $grid_counter = 1;
        }

        // Open a new row div if it's the first leader in the row
        if ($grid_counter == 1) {
            $members .= '<div class="dac-row">';
        }

        // Set the width of div and image based on leaders_per_row value
        $setDivWidth = 160;
        $setImgWidth = 150;

        // Adjust div and image width for different leaders_per_row values
        if ($options['leaders_per_row'] == 4) {
            $members .= '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
            $setDivWidth = 120;
            $setImgWidth = 110;
        } else if ($options['leaders_per_row'] == 3) {
            $members .= '<div class="members dac-col-xs-12 dac-col-sm-12 dac-col-md-4">';
        } else if ($options['leaders_per_row'] == 2) {
            $members .= '<div class="members dac-col-xs-12 dac-col-sm-6">';
        } else {
            $members .= '<div class="members dac-col-xs-12">';
        }

        // Generate HTML markup for leader information and append it to $members variable
        if ($options['leader_pics'] == 1) {
            if ($leader->image == '') {
                $members .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" style="max-width:' . $setImgWidth . 'px; aspect-ratio: 4 / 5; width: 160px; height: 200px; object-fit: cover;" class="leadership_image portrait"></td>';
            } else {
                $members .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . $leader->imgpath . '' . $leader->image . '" style="max-width:' . $setImgWidth . 'px; aspect-ratio: 4 / 5; width: 160px; height: 200px; object-fit: cover;" class="leadership_image portrait"></td>';
            }
        }
        $members .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td><td style="border:0 !important;vertical-align: top;padding:0;"><strong>' . $leader->username . '</strong><br>' . $leader->clubposition . '<br>';

        // Append contact link if leaders_contact_link is enabled
        if ($options['leaders_contact_link'] == 1) {
            $members .= '<a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $leader->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
        }

        $members .= '</td></tr></table></div>';

        // Close the row div if it's the last leader in the row
        if ($grid_counter == $options['leaders_per_row']) {
            $members .= '</div>';
            $grid_counter = 0;
        }

        $counter = $counter + 1;
    }

    // Append a comment with counter values for debugging purposes
    $members .= '<!-- ' . $lastCounter . '-' . $counter . '-' . $grid_counter . ' -->';

    // Close any remaining open divs
    if ($grid_counter > 0) {
        $members .= '</div><!-- end  -->';
    }

    // Calculate the total number of leaders
    $leader_total = count($xml->leader);

    // If there are no leaders, append a message indicating so
    if ($leader_total == 0) {
        $members .= 'There are no leaders to display at this time.';
    }

    // Return the generated HTML markup for leaders
    return $members;
}

//ANCHOR - Show Club Leaders
/**
 * Retrieves and displays club leaders' information.
 *
 * @param array $atts An array of attributes (optional).
 *
 * @return string The HTML representation of club leaders' information.
 */
function dacdb_clubleaders($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $members = '';

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    $rolekeys   = isset($atts['rolekeys']) ? $atts['rolekeys'] : 'P,S';
    $style      = isset($atts['style']) ? $atts['style'] : 1; //NOTE - Syles are built 

    // Debug information
    if ($fDebug) {
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_clubleaders called <br>";
        $members .= "AccountID=" . $account_id . "<br>";
        $members .= "ClubID=" . $club_id . "<br>";
        $members .= "Style=" . $style . "<br>";
        $members .= "RoleKeys=" . $rolekeys . "<br>";
        $members .= "URL=" . $data_path . 'wp_clubleaders.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . '&rolekeys=' . $rolekeys . "<br>";
        $members .= "=================================================================<BR>";
    }

    // Retrieve XML data from the data source
    $xml = simplexml_load_file($data_path . 'wp_clubleaders.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . '&rolekeys=' . $rolekeys . '&R=' . rand());

    // Check if the XML data is empty or loading failed
    if (empty($xml)) {
        $members .= 'There are no club leaders to display at this time.';
        return $members;
    }
    // Generate the HTML representation of club leaders' information
    $members .= dacdb_DisplayClub($xml, $style, $atts); // <clubs><club>...<officers /></club?</clubs>

    return $members;
}


//ANCHOR - Show Map
/**
 * Generates a map HTML and JavaScript code.
 *
 * @param array $atts An array of attributes.
 *
 * @return string The generated map HTML and JavaScript code.
 */
function dacdb_map($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $map = '';

    // Retrieve global variables
    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    $style      = isset($atts['style']) ? $atts['style'] : 1;

    // Append debug information if debugging is enabled
    if ($fDebug) {
        $map .= "=================================================================<BR>";
        $map .= "function dacdb_map called<br>";
        $map .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $map .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $map .= "ApiKey=" . $options['map_api'] . "<br>";
        $map .= "Style=" . $style . "<br>";
        $map .= "URL=" . $data_path . 'MapClub.cfm?AccountID=' . $options['dacdb_district'] . '&xsl=ClubData.xsl&callback=showPopUpData&zlevel=0' . "<br>";
        $map .= "URL=" . $data_path . 'MapPopUp.cfm?AccountID=' . $options['dacdb_district'] . '&xsl=ClubData.xsl&callback=showPopUpData&zlevel=0' . "<br>";
        $map .= "=================================================================<BR>";
    } else {
        // Display a message if the Google Map API key is missing
        if ($options['map_api'] == '') {
            $map .= "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>Google Map API Key missing</div>";
        }
    }

    // Generate HTML and JavaScript code for the map
    $map .= '
        <div id="Map"></div>
        <div id="map_canvas" style="min-height:600px;"></div>
        <div id="MapData" style="display:none;"></div>
        <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="  crossorigin="anonymous"></script>
        <script defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=' . $options['map_api'] . '"></script>

        <script type="text/javascript">
            var temp = "";
            function showMap(json) {
                console.log(json);
                temp = json.text;
            }
            function showPopUpData(json) {
                document.getElementById(\'MapData\').innerHTML = json.text;
            }
            $(document).ready(function() {
                eval(temp);
                $("#Map").hide();
                $("#MapData").hide();
            });
        </script>
        <script src="' . $data_path . 'MapClub.cfm?AccountID=' . $options['dacdb_district'] . '&xsl=ClubInteractive2.xsl&callback=showMap&zlevel=0" type="text/javascript"></script>
        <script src="' . $data_path . 'MapPopUp.cfm?AccountID=' . $options['dacdb_district'] . '&xsl=ClubData.xsl&callback=showPopUpData&zlevel=0" type="text/javascript"></script>
    ';

    return $map;
}

//ANCHOR - Show Committee Members
/**
 * Generates and displays a committee's members.
 *
 * @param array $atts An array of attributes passed to the function.
 *
 * @return string The HTML markup for displaying the committee members.
 */
function dacdb_committee($atts)
{
    // Global variables used within the function
    // Global variables used within the function
    global $fDebug, $data_path, $file_path, $options;

    // Retrieve attribute values from the $atts array
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    $cid = isset($atts['cid']) ? strtolower($atts['cid']) : ""; // Committee ID obtained from the shortcode (always lowercase)
    $members = ""; // HTML markup for displaying the committee members
    // Check if Committee ID is missing
    if (empty($cid)) {
        return "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>CommitteeID (cid=) is missing</div>";
    }

    // Set default values for committee members per row if not specified in options
    $options['committee_members_per_row'] = $options['committee_members_per_row'] ?? 1;

    // Handle deprecated attribute values (rows and row)
    $options['committee_members_per_row'] = $atts['rows'] ?? $atts['row'] ?? $options['committee_members_per_row'];

    // Set committee members per row based on the provided attribute value (cols)
    $options['committee_members_per_row'] = $atts['cols'] ?? $options['committee_members_per_row'];

    // Set committee members' committee position based on the provided attribute value (committeeposition)
    $options['committee_members_committeeposition'] = $atts['committeeposition'] ?? $options['committee_members_committeeposition'];

    // Set show club position based on the provided attribute value (clubposition)
    $ShowClubPos = $atts['clubposition'] ?? 0;

    // Set global show district number based on the provided attribute value (district)
    $options['committee_global_show_district_number'] = $atts['district'] ?? $options['committee_global_show_district_number'];

    // Retrieve additional options
    $cols = $options['committee_members_per_row'];

    // Construct path to xml feed
    $xml_path = $data_path . 'wp_ById.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&id=' . $cid . '&R=' . rand();

    // Display debugging information
    if ($fDebug) {
        $members .= "<div class=\"debug\">";
        $members .= "<h5>function <em>dacdb_committee</em> called</h5><pre>";
        $members .= "AccountID= " . $account_id . "<br>";
        $members .= "ClubID= " . $club_id . "<br>";
        $members .= "cid= " . $cid . "<br>";
        $members .= "xml_path= <a href=\"" . $xml_path . "\" target=\"debug-window\">" . $xml_path . "</a><br>";
        $members .= "cols= " . $cols . "<br>";
        $members .= "Pics= " . $options['committee_members_pics'] . "<br>";
        $members .= "CommitteeName= " . $options['committee_global_name'] . "<br>";
        $members .= "Description= " . $options['committee_global_description'] . "<br>";
        //TODO: Create ATT for -> $members .= "Committeeposition=" . $ShowCommPos . "<br>";
        $members .= "Show Clubposition= " . $ShowClubPos . "<br>";
        $members .= "Show DistrictNumber= " . $options['committee_global_show_district_number'] . "<br>";
        $members .= "BusPos= " . $options['committee_members_busposition'] . "<br>";
        $members .= "Classification= " . $options['committee_members_classification'] . "<br>";
        $members .= "Contact= " . $options['leaders_contact_link'] . "<br>";
        $members .= "</pre></div>";
    }

    // Load XML data from the specified URL
    $xml = simplexml_load_file($xml_path);

    // Check if XML data is empty
    if (strlen($xml) == 0) {
        $members .= 'There are no committee members to display at this time.';
        return $members;
    }

    // Set the div and image widths based on the number of columns
    $setDivWidth = 160;
    $setImgWidth = 150;
    $div = '<div class="col">';

    if ($cols == 1) {
        $div = '<div class="members dac-col-xs-12">';
        $setDivWidth = 155;
        $setImgWidth = 150;
    } else if ($cols == 2) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-6">';
        $setDivWidth = 140;
        $setImgWidth = 135;
    } else if ($cols == 3) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-12 dac-col-md-4">';
        $setDivWidth = 125;
        $setImgWidth = 120;
    } else if ($cols == 4) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
        $setDivWidth = 110;
        $setImgWidth = 105;
    }
    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && isset($atts['imgwidth']) > 0 ? $atts['imgwidth'] : 150);
    // Counter for tracking members
    $counter = 0;

    // Display committee name if enabled
    if ($options['committee_global_name'] == 1) {
        $members .= '<div class="dac-row">';
        $members .= '   <div class="dac-col-xs-12">';
        $members .= '       <h1 style="display:none;">' . $xml->committeemembers->committeename . ' Committee Members</h1>';
        $members .= '   </div>'; // dac-col-xs-12
        $members .= '</div>'; // dac-row
    }

    // Display committee description if enabled
    if ($options['committee_global_description'] == 1) {
        $members .= '<div class="dac-row">';
        $members .= '    <div class="dac-col-xs-12">';
        $members .=         $xml->committeemembers->description . '<br><br>';
        $members .= '   </div>'; // dac-col-xs-12
        $members .= '</div>'; // dac-row
    }

    // Display committee members
    $members .= '<div class="dac-row">';

    foreach ($xml->committeemembers as $member) {
        $members .= $div; // members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3
        $members .= '<table border="0" cellpadding="0" cellspacing="0">';
        $members .= '<tr>';

        if ($options['committee_members_pics'] == 1) {
            $members .=   '<td style="border:0 !important;vertical-align: top; padding:0; width:' . $setDivWidth . 'px;">';

            if ($member->image == '') {
                $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '"  style="aspect-ratio: 4 / 5; width: ' . $setImgWidth . 'px; object-fit: cover;" width="' . $setImgWidth . '"></div>';
            } else {
                $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . $member->image . '"  style="aspect-ratio: 4 / 5; width: ' . $setImgWidth . 'px; object-fit: cover;" width="' . $setImgWidth . '"></div>';
            }

            $members .=   '</td>';
        }

        $members .='    <td style="border:0 !important; text-align: left; vertical-align: top; padding:0;">';
        $members .= '       <strong>' . $member->membername . '</strong><BR>';

        $formattedUrl = formatDomainToUrl($member->cluburl); 
        if (!empty($formattedUrl)) {
            $members .= '<a href="' . $formattedUrl . '" target="new">' . $member->clubname . '</a><br>';
        } else {
            $members .= '<span class="clubname">' . $member->clubname . '<br></span>';
        }

        if ($options['committee_global_show_district_number'] == 1) {
            if ($member->accountid != '') {
                $members .= 'District ' . $member->accountid . '<br />';
            }
        }

        if ($options['committee_members_committeeposition'] == 1) {
            if ($member->committeeposition != '') {
                $members .= $member->committeeposition . '<br />';
            }
        }

        if ($ShowClubPos == 1) {
            if ($member->clubposition != '') {
                $members .= $member->clubposition . ' club position<br />';
            }
        }

        if ($options['committee_members_busposition'] == 1) {
            if ($member->busposition != '') {
                $members .= $member->busposition . '<br />';
            }
        }

        if ($options['committee_members_classification'] == 1) {
            if ($member->classification != '') {
                $members .= $member->classification . '<br />';
            }
        }

        if ($options['leaders_contact_link'] == 1) {
            $members .= '<a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $member->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
        }

        $members .=   '</td>';
        $members .= '</tr>';
        $members .= '</table>';
        $members .= '</div>'; // members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3
        $counter = $counter + 1;
    }

    $members .= '</div>'; // dac-row
    return $members;
}

//ANCHOR - Show Committees
/**
 * Generates a list of committees based on attributes and options.
 *
 * @param array $atts An associative array of attributes.
 * @return string The generated list of committees.
 */
function dacdb_committees($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $committees = ''; // Initialize an empty string to store the generated list of committees.

    $account_id = $options['dacdb_district']; // Retrieve the district account ID from options.
    $club_id    = $options['dacdb_club']; // Retrieve the club ID from options.

    $description = $_GET['description'] ?? $atts['description'] ?? $options['committee_global_description'] ?? '0';

    $orgyear = isset($atts['orgyear']) ? $atts['orgyear'] : ''; // Retrieve the "orgyear" attribute from the function arguments.
    $members = isset($_GET["members"]) ? $_GET["members"] : ''; // Get the "members" value from the query string parameters.

    $options['committee_members_per_row'] ??= 1;
    $current_url = "";

    if ($fDebug) {
        // Generate debug information if debugging is enabled.
        $committees .= "=================================================================<BR>";
        $committees .= "function dacdb_committees called<br>";
        $committees .= "AccountID=" . $account_id . "<br>";
        $committees .= "ClubID=" . $club_id . "<br>";
        $committees .= "description=" . $description . "<br>";
        $committees .= "orgyear=" . $orgyear . "<br>";
        $committees .= "members=" . $members . "<br>";
        if ($members)
            $committees .= "URL=" . $data_path . 'wp_ById2.cfm?AccountID=' .$account_id . '&ClubID=' . $club_id . '&id=' . $members . '&RoleKey=' . "<br>";
        else
            $committees .= "URL=" . $data_path . 'wp_committees.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . "<br>";
        $committees .= "=================================================================<BR>";
    }

    if ($members) {
        // List members on the selected committee.
        $counter = 1;
        $grid_counter = 0;

        $xml = simplexml_load_file($data_path . 'wp_ById2.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&id=' . $members . '&R=' . rand());

        if (strlen($xml) == 0) {
            $committees .= 'There are no committee members to display at this time.';
            return $committees;
        }

        $committees .= '<style>h1.entry-title { display:none !important; }</style>';
        $lastCounter = count($xml->committeemembers);

        foreach ($xml->committeemembers as $member) {
            if ($counter == 1) {
                if ($options['committee_global_name'] == 1) {
                    $committees .= '<div style="overflow: auto;margin-bottom:10px;"><h1>' . $member->committeename . ' Committee Members</h1></div>';
                }
                $url = strtok($_SERVER["REQUEST_URI"], '?');

                if ($description == 1) {
                    $committees .= '<div style="overflow: auto;">' . $member->description . '</div><br><br>';
                }
                $counter = 2;
            }

            $grid_counter = $grid_counter + 1;

            if ($options['committee_members_per_row'] == 1) {
                $grid_counter = 1;
            }

            if ($grid_counter == 1) {
                $committees .= '<div class="dac-row"><!-- ' . $grid_counter . ' -->';
            }

            // Set the width for the committee member div and image based on the number of members per row.
            $setDivWidth = 150;
            $setImgWidth = 140;

            if ($options['committee_members_per_row'] == 1) {
                $committees .= '<div class="members dac-col-xs-12">';
            } else if ($options['committee_members_per_row'] == 2) {
                $committees .= '<div class="members dac-col-xs-12 dac-col-sm-6">';
            } else if ($options['committee_members_per_row'] == 3) {
                $committees .= '<div class="members dac-col-xs-12 dac-col-sm-12 dac-col-md-4">';
            } else if ($options['committee_members_per_row'] == 4) {
                $committees .= '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
                $setDivWidth = 120;
                $setImgWidth = 110;
            }

            if ($options['committee_members_pics'] == 0) {
                $committees .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr>';
            } else {
                if ($member->image == '') {
                    $committees .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" width="' . $setImgWidth . '"></td>';
                } else {
                    $committees .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . $member->imgpath . '' . $member->image . '" width="' . $setImgWidth . '"></td>';
                }
            }

            if ($options['committee_members_contact_link'] == 1) {
                $committees .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td><td style="border:0 !important;vertical-align: top;padding:0;"><a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $member->userid . '" class="iframe3 cboxElement"><strong>' . $member->username . '</strong></a>';
            } else {
                $committees .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td><td style="border:0 !important;vertical-align: top;padding:0;"><strong>' . $member->username . '</strong>';
            }

            // Display additional information based on the configured options.
            if ($options['committee_members_committeeposition'] == 1) {
                if ($member->committeeposition != '') {
                    $committees .= '<br>' . $member->committeeposition . '';
                }
            }

            $formattedUrl = formatDomainToUrl($member->cluburl);
            if (!empty($formattedUrl)) {
                $committees .= '<br><a href="' . $formattedUrl . '" target="new">' . $member->clubname . '</a><br>';
            } else {
                $committees .= '<span class="clubname"><br>' . $member->clubname . '<br></span>';
            }

            if ($options['committee_global_show_district_number'] == 1) {
                if ($member->accountid != '') {
                    $committees .= '<br>District ' . $member->accountid . '';
                }
            }
            if ($options['committee_members_busposition'] == 1) {
                if ($member->busposition != '') {
                    $committees .= '<br>' . $member->busposition . '';
                }
            }
            if ($options['committee_members_classification'] == 1) {
                if ($member->classification != '') {
                    $committees .= '<br>' . $member->classification . '';
                }
            }
            if ($options['committee_members_contact_link'] == 1) {
                $committees .= '<br><a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $member->userid . '" class="iframe3 cboxElement">Contact</a>';
            }

            $committees .= '</td></tr></table>';
            $committees .= '</div>';

            if ($grid_counter == $options['committee_members_per_row']) {
                $committees .= '</div><!--even-->';
                $grid_counter = 0;
            }
        }

        if ($grid_counter > 0) {
            $committees .= '</div><!--end-->';
        }
    } else {
        // List all committees - Club or District.
        $xml = simplexml_load_file($data_path . 'wp_committees.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());

        if (strlen($xml) == 0) {
            $committees .= 'There are no committees to display at this time.';
            return $committees;
        }

        $counter = 1;
        $committees .= '<table width="100%" class="dcc" style="vertical-align: top;padding:0;">';

        foreach ($xml->committee as $committee) {
            $pad = "";
            // level is being returned as 0 right now.
            //if ( $committee->level > 0 ) {
            //    $w = $committee->level*30;
            //    $pad = 'style="padding-left:$wpx;"';
            //}

            if ($committee->gdg == "Y") {
                $committees .= '<tr><td ' . $pad . ' style="vertical-align: top;padding:0;"><span style="color:red"><strong>' . $committee->name . '</strong></span></td>';
            } else {
                $committees .= '<tr><td ' . $pad . ' style="vertical-align: top;padding:0;"><a href="' . $current_url . '?members=' . $committee->committeeid . '"><strong>' . $committee->name . '</strong></a></td>';
            }

            if ($orgyear == 1 || strtoupper($orgyear) == 'Y') {
                $committees .= '<td style="vertical-align: top; padding:0; width: 100px">' . $committee->year . '</td>';
            }

            $committees .= '</tr>';

            if ($description == 1 || strtoupper($description) == 'Y') {
                if (strlen(trim($committee->description)))
                    $committees .= '<tr><td>' . trim($committee->description) . '</td></tr>';
            }

            $counter = $counter + 1;
        }

        $committees .= '</table>';
        $committee_total = count($xml->committee);
    }

    return $committees; // Return the generated list of committees.
}

//ANCHOR - Show DCC
/**
 * Generate HTML code for displaying DCC officers.
 *
 * @param array $atts Array of attributes.
 * @return string HTML code representing DCC officers display.
 */
function dacdb_dcc($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $dccs = ''; // Stores the generated HTML code for DCC officers

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && isset($atts['imgwidth']) > 0 ? $atts['imgwidth'] : 150);

    if ($fDebug) {
        // Debug information
        $dccs .= "=================================================================<BR>";
        $dccs .= "function dacdb_dcc called<br>";
        $dccs .= "AccountID=" . $account_id . "<br>";
        $dccs .= "ClubID=" . $club_id . "<br>";
        $dccs .= "URL=" . $data_path . 'wp_dcc.cfm?AccountID=' . $account_id . "<br>";
        $dccs .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_dcc.cfm?AccountID=' . $account_id . '&R=' . rand());

    if (strlen($xml) == 0) {
        $dccs .= 'There are no DCC officers to display at this time.';
        return $dccs;
    }

    $counter = 1; // Counter for tracking iterations
    $grid_counter = 0; // Counter for tracking grid positions
    $lastCounter = count($xml->dcc); // Total number of DCC officers

    foreach ($xml->dcc as $dcc) {
        $grid_counter = $grid_counter + 1;

        if ($options['dcc_per_row'] == 1) {
            $grid_counter = 1; // Force single row if dcc_per_row is 1
        }

        if ($grid_counter == 1) {
            $dccs .= '<div class="dac-row"><!-- start -->'; // Start a new row
        }

        $setDivWidth = 160; // Width of table cell
        $setImgWidth = 150; // Width of image

        if ($options['dcc_per_row'] == 1) {
            $dccs .= '<div class="members dac-col-xs-12">'; // One column per row
        } else if ($options['dcc_per_row'] == 2) {
            $dccs .= '<div class="members dac-col-xs-12 dac-col-sm-6">'; // Two columns per row
        } else if ($options['dcc_per_row'] == 3) {
            $dccs .= '<div class="members dac-col-xs-12 dac-col-sm-12 dac-col-md-4">'; // Three columns per row
        } else if ($options['dcc_per_row'] == 4) {
            $dccs .= '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">'; // Four columns per row
            $setDivWidth = 120; // Adjusted table cell width for four columns
            $setImgWidth = 110; // Adjusted image width for four columns
        }

        if ($dcc->image == '') {
            // Display default image if officer's image is empty
            $dccs .= '<table style="vertical-align: top;padding-right:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '"  style="aspect-ratio: 4 / 5; width: ' . $thumbnail_width  . 'px; object-fit: cover;" width="' . $thumbnail_width  . '"></td>';
        } else {
            // Display officer's image
            $dccs .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . $dcc->imgpath . '' . $dcc->image . '"  style="aspect-ratio: 4 / 5; width: ' . $thumbnail_width  . 'px; object-fit: cover;" width="' . $thumbnail_width  . '"></td>';
        }

        $dccs .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td><td style="border:0 !important;vertical-align: top;padding:0;"><strong>' . $dcc->committeename . '</strong><br><strong>' . $dcc->membername . '</strong>';
        $dccs .= '<br>' . $dcc->committeeposition . '<br>';
        $dccs .= '</td>';
        $dccs .= '</tr></table></div>';

        if ($grid_counter == $options['dcc_per_row']) {
            $dccs .= '</div>'; // Close the row
            $grid_counter = 0; // Reset grid counter
        }

        $counter = $counter + 1;
    }

    if ($grid_counter > 0) {
        $dccs .= '</div><!-- end  -->'; // Close the last row if incomplete
    }

    return $dccs; // Return the generated HTML code for DCC officers
}

//ANCHOR - Show COG
function dacdb_cog($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $cogs = '';

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];

    if ($fDebug) {
        $cogs .= "=================================================================<BR>";
        $cogs .= "function dacdb_cog called<br>";
        $cogs .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $cogs .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $cogs .= "URL=" . $data_path . 'wp_cog.cfm?AccountID=' . $options['dacdb_district'] . "<br>";
        $cogs .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_cog.cfm?AccountID=' . $options['dacdb_district'] . '&R=' . rand());
    if (strlen($xml) == 0) {
        $cogs .= 'There are no COGs to display at this time.';
        return $cogs;
    }

    $counter = 1;
    $grid_counter = 0;
    foreach ($xml->cog as $cog) {
        $grid_counter = $grid_counter + 1;
        if ($options['cog_per_row'] == 1) {
            $grid_counter = 1; // force single row
        }
        if ($grid_counter == 1) {
            $cogs .= '<div class="dac-row"><!-- start -->';
        }

        $setDivWidth = 160;
        $setImgWidth = 150;

        if ($options['cog_per_row'] == 1) {
            $cogs .= '<div class="members dac-col-xs-12">';
        } else if ($options['cog_per_row'] == 2) {
            $cogs .= '<div class="members dac-col-xs-12 dac-col-sm-6">';
        } else if ($options['cog_per_row'] == 3) {
            $cogs .= '<div class="members dac-col-xs-12 dac-col-sm-12 dac-col-md-4">';
        } else if ($options['cog_per_row'] == 4) {
            $cogs .= '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
            $setDivWidth = 120;
            $setImgWidth = 110;
        }
        if ($cog->image == '') {
            $cogs .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" style="max-width:' . $setImgWidth . 'px"></td>';
        } else {
            $cogs .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . $cog->imgpath . '' . $cog->image . '" style="max-width:' . $setImgWidth . 'px"></td>';
        }
        $cogs .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td><td style="border:0 !important;vertical-align: top;padding:0;"><strong>' . $cog->membername . '</strong>';

        $cogs .= '<br><strong>Year of Service:</strong> ' . $cog->yos . '<br>';
        $cogs .= '<br>' . $cog->clubname . '<br><br></td>';
        $cogs .= '</tr></table></div>';
        if ($grid_counter == $options['cog_per_row']) {
            $cogs .= '</div>';
            $grid_counter = 0;
        }
        $counter = $counter + 1;
    }
    if ($grid_counter > 0) {
        $cogs .= '</div><!-- end  -->';
    }

    return $cogs;
}


//ANCHOR - Show Documents
function dacdb_documents($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $documents = '';
    $account_id = isset($options['dacdb_district']) ? $options['dacdb_district'] : '';
    $club_id = isset($options['dacdb_club']) ? $options['dacdb_club'] : '';
    $icon = isset($atts['icon']) ? $atts['icon'] : '0';
    $size = isset($atts['size']) ? $atts['size'] : '0';
    $date = isset($atts['date']) ? $atts['date'] : '0';
    $folder = isset($_GET['folder']) ? $_GET['folder'] : (isset($atts['folder']) ? $atts['folder'] : '');
    $folder2 = isset($_GET['folder2']) ? isset($_GET['folder2']) : (isset($atts['folder2']) ? isset($atts['folder2']) : '');
    $level = isset($folder) ? 1 : 0;
    $sort = "";
    $current_url = "";

    if ($fDebug) {
        $documents .= "=================================================================<BR>";
        $documents .= "function dacdb_documents called<br>";
        $documents .= "AccountID=" . (isset($options['dacdb_district']) ? $options['dacdb_district'] : '') . "<br>";
        $documents .= "ClubID=" . (isset($options['dacdb_club']) ? $options['dacdb_club'] : '') . "<br>";
        $documents .= "folder=" . (isset($folder) ? $folder : '') . "<br>";
        $documents .= "icon=" . (isset($icon) ? $icon : '') . "<br>";
        $documents .= "size=" . (isset($size) ? $size : '') . "<br>";
        $documents .= "date=" . (isset($date) ? $date : '') . "<br>";
        $documents .= "current_url=" . (isset($current_url) ? $current_url : '') . "<br>";
        $documents .= "path=" . (isset($file_path) ? $file_path : '') . "<br>";
        $documents .= "url=" . (isset($data_path) ? $data_path : '') . 'documents.php?AccountID=' . (isset($options['dacdb_district']) ? $options['dacdb_district'] : '') . '&ClubID=' . (isset($options['dacdb_club']) ? $options['dacdb_club'] : '') . '&folder=' . (isset($folder) ? $folder : '') . '&folder2=' . (isset($folder2) ? $folder2 : '') . '&sort=' . (isset($sort) ? $sort : '') . "<br>";
        $documents .= "=================================================================<BR>";
    }


    $xml = simplexml_load_file((isset($data_path) ? $data_path : '') . 'documents.php?AccountID=' . (isset($options['dacdb_district']) ? $options['dacdb_district'] : '') . '&ClubID=' . (isset($options['dacdb_club']) ? $options['dacdb_club'] : '') . '&Folder=' . (isset($folder) ? $folder : '') . '&Folder2=' . (isset($folder2) ? $folder2 : '') . '&sort=' . (isset($sort) ? $sort : '') . '&R=' . rand());
    if ($xml->count() == 0) {
        $documents .= 'There are no documents to display at this time.';
        return $documents;
    }


    $counter = 1;
    //
    // Breadcrumbs
    //
    $documents .= '<div class="breadcrumbs"> ';
    if ($level == 1) {
        if ($folder && $folder2 ==  '') {
            $documents .= '' . $folder;
        } elseif ($folder2) {
            $documents .= '
            <a href="' . $current_url . '?folder=' . $folder . '">' . $folder . '</a> > ' . $folder2 . '';
        }
    } else {
        if ($folder && $folder2 ==  '') {
            $documents .= '<a href="' . $file_path . '">Documents</a> > ' . $folder;
        } elseif ($folder2) {
            $documents .= '
            <a href="' . $file_path . '&">Documents</a> >
            <a href="' . $file_path . '&folder=' . $folder . '">' . $folder . '</a> > ' . $folder2 . '';
        }
    }
    $documents .= '</ul></div>';

    //
    // Process all the documents returned
    //

    $icon_header = ($icon == 1) ? '<th width="36">&nbsp;</th>' : '';
    $size_header = ($size == 1) ? '<th data-sort="int">Size</th>' : '';
    $date_header = ($date == 1) ? '<th data-sort="int">Modified</th>' : '';

    $documents .= '<div class="row">
        <div class="dac-col-md-12">
        <table class="table">
            <thead>
            <tr>
            ' . $icon_header . '
            <th data-sort="string">File Name</th>
            ' . $size_header . '
            ' . $date_header . '
            </tr>
            </thead>
            <tbody>';

    if (!empty($xml->document)) {
        foreach ($xml->document as $document) {
            $name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $document->name);

            if ($document->type == 0) {
                if ($folder && $folder2) {
                    // do nothing
                } else {
                    $documents .= '<tr>';
                    if ($icon == 1) {
                        if ($folder) {
                            $documents .= '<td><img src="' . plugins_url('img/folder.png', __FILE__) . '" width="32" style="max-width: 32px !important; width: 32px !important;"></td><td><a href="' . $current_url . '?folder=' . $folder . '&folder2=' . $document->name . '">' . $name . '</a>' . $current_url . '</td>';
                        } else {
                            $documents .= '<td><img src="' . plugins_url('img/folder.png', __FILE__) . '" width="32" style="max-width: 32px !important; width: 32px !important;"></td><td><a href="' . $current_url . '?folder=' . $name . '">' . $name . '</a></td>';
                        }
                    } else {
                        if ($folder) {
                            $documents .= '<td><a href="' . $current_url . '?folder=' . $folder . '&folder2=' . $document->name . '">' . trim($name) . '</a></td>';
                        } else {
                            $documents .= '<td><a href="' . $current_url . '?folder=' . $name . '">' . trim($name) . '</a></td>';
                        }
                    }

                    if ($size == 1) {
                        $documents .= '<td>-</td>';
                    }

                    if ($date == 1) {
                        $documents .= '<td>-</td>';
                    }
                    $documents .= '</tr>';
                    $counter = $counter + 1;
                }
            } else {
                $extension = substr(strrchr($document->name, '.'), 1);
                if ($extension == '') {
                    $extension = '__blank';
                }
                if ($icon == 1) {
                    $documents .= '<tr><td><img src="' . plugins_url('img/16px/' . $extension . '.png', __FILE__) . '" width="32" style="max-width: 32px !important; width: 32px !important;">' . $lastDotPos . '</td>';
                } else {
                    $documents .= '<tr>';
                }
                // $documents .= '<td><a href="'.$file_path.'.$options['dacdb_district'].'/Downloads/'.$options['dacdb_club'].'/'.$document->name.'" target="__blank">'.$document->name.'</a></td>';

                if ($extension == 'URL') {

                    // $docName = str_replace(" ", "%20",$document->name);

                    if ($folder && $folder2 ==  '') {
                        $getURL = file_get_contents($file_path . $options['dacdb_district'] . '/Downloads/' . rawurlencode($options['dacdb_club']) . '/' . rawurlencode($folder) . '/' . rawurlencode($document->name));
                    } elseif ($folder && $folder2) {
                        $getURL = file_get_contents($file_path . $options['dacdb_district'] . '/Downloads/' . rawurlencode($options['dacdb_club']) . '/' . rawurlencode($folder) . '/' . rawurlencode($folder2) . '/' . rawurlencode($document->name));
                    } else {
                        $getURL = file_get_contents($file_path . $options['dacdb_district'] . '/Downloads/' . rawurlencode($options['dacdb_club']) . '/' . rawurlencode($document->name));
                    }
                    if (strpos($getURL, "http://") === false && strpos($getURL, "https://") === false) {
                        $getURL = 'https://' . $getURL;
                    }
                } else {
                    if ($folder && $folder2 ==  '') {
                        $getURL = $file_path . $options['dacdb_district'] . '/Downloads/' . $options['dacdb_club'] . '/' . $folder . '/' . $document->name;
                    } elseif ($folder && $folder2) {
                        $getURL = $file_path . $options['dacdb_district'] . '/Downloads/' . $options['dacdb_club'] . '/' . $folder . '/' . $folder2 . '/' . $document->name;
                    } else {
                        $getURL = $file_path . $options['dacdb_district'] . '/Downloads/' . $options['dacdb_club'] . '/' . trim($document->name);
                    }
                }

                $documents .= '<td><a href="' . $getURL . '" target="__blank">' . $document->name . '</a></td>';
                if ($size == 1) {
                    $documents .= '<td>' . $document->size . '</td>';
                }
                if ($date == 1) {
                    $documents .= '<td>' . $document->modded . '</td>';
                }
                $documents .= '</tr>';
                $counter = $counter + 1;
            }
        }
    } else {
        $documents .= '<tr><td colspan="4"><strong>There are no documents available at this time.<strong></td></tr>';
    }
    $documents .= '</tbody></table></div></div>';
    return $documents;
}


//ANCHOR - Show Newsletter
function dacdb_newsletter($atts)
{
    global $fDebug, $data_path, $file_path, $options, $wp;

    $documents = '';
    
    $folder = isset($_GET["folder"]) ? $_GET["folder"] : '';
    $date   = isset($atts['date']) ? $atts['date'] : '0';
    $icon   = isset($atts['icon']) ? $atts['icon'] : '0';
    $location = ($options['dacdb_club'] == 0) ? 'newsletters' : 'bulletins';
    $size   = isset($atts['size']) ? $atts['size'] : '0';
    $url = $data_path . 'wp_newsletters.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&type=' . $location . '&Weeks=' . $options['newsletters_weeks_page'];
    $xml = simplexml_load_file( $url . '&R=' . rand());

    if ( $fDebug )  {
        $documents .= '
        <h5>function <em><strong>dacdb_newsletter</strong></em> called:</h5>
        <h4 class="drawer">Shortcode Settings</h4>
        <pre class="panel">
            <dl>
                <dt>$options[\'newsletters_weeks_page\']</dt><dd>' . $options['newsletters_weeks_page'] . '</dd>
                <dt>$options[\'newsletters_show_folders_page\']</dt><dd>' . $options['newsletters_show_folders_page'] . '</dd>
                <dt>$options[\'newsletters_order_folders_page\']</dt><dd>' . $options['newsletters_order_folders_page'] . '</dd>
                <dt>$options[\'newsletters_weeks_widget\']</dt><dd>' . $options['newsletters_weeks_widget'] . '</dd>
            </dl>
        </pre>';
        // Show shortcode attributes if there are any
        if (count($atts) > 1) { 
            $documents .= '<h4 class="drawer">Shortcode Attributes</h4>
                                <pre class="panel">
                                    <dl>';
            foreach ($atts as $key => $value) {
                $documents .= '    <dt>$_[\'' . $key . '\']</dt><dd>' . $value . '</dd>';
            }
            $documents .= '</dl>
                    </pre>'; // Close the drawer
        }
        // show URL parameters if there are any (Except Debug)
        if (count($_GET) > 1 || (count($_GET) == 1 && !array_key_exists("debug", $_GET))) {
            $documents .= '<h4 class="drawer">URL Parameters</h4>
                                <pre class="panel">
                                    <dl>';
            foreach ($_GET as $key => $value) {
                if ($key == "debug") {
                    continue; // Skip the rest of the loop for this iteration
                }
                $documents .= '    <dt>$_[\'' . $key . '\']</dt><dd>' . $value . '</dd>';
            }
            $documents .= '</dl>
                </pre>'; // Close the drawer
        }
        $documents .= '
            <h4 class="drawer">Named Variables</h4>
            <pre class="panel">
                <dl>
                    <dt>$folder</dt><dd>' . (isset($folder) && $folder !== '' ? $folder : 'Not set') . '</dd>
                    <dt>$date</dt><dd>' . (isset($date) ? $date : 'Not set') . '</dd>
                    <dt>$icon</dt><dd>' . (isset($icon) ? $icon : 'Not set') . '</dd>
                    <dt>$location</dt><dd>' . (isset($location) ? $location : 'Not set') . '</dd>
                    <dt>$size</dt><dd>' . (isset($size) ? $size : 'Not set') . '</dd>
                </dl>
            </pre>
            <h4 class="drawer">URLs</h4>
            <pre class="panel">
                <dl>
                    <dt>$file_path</dt><dd>' . $file_path . '</dd>
                    <dt>$url</dt><dd><a href="' . $url . '" target="debug-tab">' . $url . '</a></dd>
                </dl>
            </pre>';

        // Debugging output for $xml->newsletter
        $documents .= '
        <h4 class="drawer">XML Output</h4>
            <div class="panel">';
            foreach ($xml->newsletter as $document) {
                $dom = new DOMDocument();
                $dom->preserveWhiteSpace = false; // Don't preserve whitespaces
                $dom->formatOutput = true; // Format output with indentation and line breaks
                $dom->loadXML($document->asXML()); // Load the XML string from SimpleXMLElement
                $formattedXml = $dom->saveXML(); // Save the formatted XML to a string
                $documents .= '<pre>' . htmlspecialchars($formattedXml) . '</pre>';
            }
        $documents .= '
            </div>
        </div>'; // Close the drawer and panel
    }
    
    if (strlen($xml) == 0) {
        $documents .= 'There are no newsletters to display at this time.';
        return $documents;
    }
    
    $documents .= '
    <section class="dacdb newsletters">
        <ul>';

    $counter = 1;
    
    if (empty($_GET["folder"])) { //
        foreach ($xml->newsletter as $document) {
            $name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $document->name);
            $extension = substr(strrchr($document->name, '.'), 1);
            $documents .= '<li>';
            if ($document->type == 'Dir') {
                $documents .= '<a href="' . $current_url . '?folder=' . $folder . '&folder2=' . $document->name . '" target="dacdb-newsletter"><img class="icon" alt="directory icon" src="' . plugins_url('img/folder.png', __FILE__) . '" width="32">' . trim($name) . '</a>' . $current_url;
            } else {
                if ($icon == 1) {
                    $documents .= '<a href="' . $document->path . '" aria-label="Download ' . $extension .': ' . trim($name) . '" target="dacdb-newsletter"><img class="icon" alt="' . $extension . ' icon" src="' . plugins_url('img/16px/' . $extension . '.png', __FILE__) . '">' . trim($name) . '</a>';
                } else {
                    $documents .= '<a href="' . $document->path . '" aria-label="Download ' . $extension .': ' . trim($name) . '" target="dacdb-newsletter">' . trim($name) . '</a>';
                }
            }
            if ($size == 1) {
                $documents .= FileSizeConvert($document->size) . $document->datelastmodified;
            }
            if ($date == 1) {
                $documents .= $document->datelastmodified;
            }
            $documents .= '</li>';
            $counter = $counter + 1;
        }
    }

    // get folders here
    if ($options['newsletters_show_folders_page'] == 1) {
        $page_title = esc_html(get_the_title());
        if ($folder) {
            $level = 1;
        } else {
            $level = 0;
        }
        $current_url = add_query_arg($wp->query_string, '', home_url($wp->request));
        if ($folder) {
            $documents .= '<div class="breadcrumbs" style="text-align:right;">';
            $documents .= '<a href="' . $current_url . '">' . $page_title . '</a> > ' . $folder;
            $documents .= '</div><br>';
        }
        try {
            if ($folder) {
                $nfxml = @simplexml_load_file($data_path . 'newsletter_folders.php?AccountID=' . $account_id . '&ClubID=' . $club_id . '&Folder=' . $folder . '&Sort=' . $options['newsletters_order_folders_page'] . '&R=' . rand());
            } else {
                $nfxml = @simplexml_load_file($data_path . 'newsletter_folders.php?AccountID=' . $account_id . '&ClubID=' . $club_id . '&Folder=&Sort=' . $options['newsletters_order_folders_page'] . '&R=' . rand());
            }
        } catch (Exception $e) {
            $nfxml = '';
        }
        if ($nfxml != NULL) {
            foreach ($nfxml->document as $document) {
                $name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $document->name);
                if ($document->type == 0) {

                    if (!$folder) {
                        if (is_front_page()) {
                            $documents .= '<div><strong><a href="' . $current_url . '?folder=' . $document->name . '">' . $document->name . '</a></strong><span class="pull-right" style="float:right;">-</span></div>';
                        } else {
                            $documents .= '<div><strong><a href="' . $current_url . '&folder=' . $document->name . '">' . $document->name . '</a></strong><span class="pull-right" style="float:right;">-</span></div>';
                        }
                        $documents .= '<hr>';
                    }
                } else {
                    $extension = substr(strrchr($document->name, '.'), 1);
                    if ($extension == '') {
                        $extension = '__blank';
                    }

                    if ($folder) {
                        $getURL = $file_path;
                        echo $getURL . "<br>";
                        $documents .= '<div><strong><a href="' . $getURL . '" target="__blank">' . $document->name . '</a></strong> - ' . $document->size . '<span class="pull-right" style="float:right;">' . $document->modded . '</span></div>';
                        $documents .= '<hr>';
                    } else {
                        if ($extension == 'pdf') {
                        }
                    }
                    $counter = $counter + 1;
                }
            }
        }
    }
    $documents .= '</section>';
    return $documents;
}

//ANCHOR - Show Sponsors
function dacdb_sponsors($atts)
{
    global $fDebug, $data_path, $file_path, $options;
    global $wp;

    $sponsors = '';

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    if ($fDebug) {
        $sponsors .= "=================================================================<BR>";
        $sponsors .= "function dacdb_xxxxx called<br>";
        $sponsors .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $sponsors .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $sponsors .= "URL=" . $data_path . 'wp_sponsor.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&N=9999&SortBy=random' . "<br>";
        $sponsors .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_sponsor.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&N=9999&SortBy=random' . '&R=' . rand());
    if (strlen($xml) == 0) {
        $sponsors .= 'There are no sponsors to display at this time.';
        return $sponsors;
    }

    $counter = 0;
    $sponsors .= '<div class="dac-row">';
    foreach ($xml->sponsor as $sponsor) {
        if (strcmp($cat, $sponsor->category)) {
            $cat = $sponsor->category;
        }
        $sponsors .= '<div class="dac-col-xs-12 dac-col-sm-12 dac-col-md-6">';
        if ($sponsor->image == '') {
            $sponsors .= '<a href="' . $data_path . 'SponsorPop.cfm?SponsorID=' . $sponsor->sponsorid . '" target="_blank" class="iframe3 cboxElement">' . $sponsor->sponsorname . '</a><br><br>';
        } else {
            $sponsors .= '<a href="' . $data_path . 'SponsorPop.cfm?SponsorID=' . $sponsor->sponsorid . '" target="_blank" class="iframe3 cboxElement"><img src="' . $sponsor->imagepath . '' . $sponsor->image . '"></a><br><br>';
        }
        $sponsors .= '</div>';
    }
    $sponsors .= '</div>';
    return $sponsors;
}

//ANCHOR - Show WCM
function dacdb_wcm($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $meetings = '';
    $sort = 'club';
    if ($options['wcm_show_layout'] == 'default') {
        $sort = 'club';
    } elseif ($options['wcm_show_layout'] == 'area') {
        $sort = 'area';
    } elseif ($options['wcm_show_layout'] == 'date') {
        $sort = 'date';
    } elseif ($options['wcm_show_layout'] == 'detail') {
        $sort = 'detail';
    } elseif ($options['wcm_show_layout'] == 'club') {
        $sort = 'club';
    } elseif ($options['wcm_show_layout'] == 'officers') {
        $sort = 'officers';
    }

    if ($fDebug) {
        $meetings .= "==================================================================<BR>";
        $meetings .= "function dacdb_wcm called<br>";
        $meetings .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $meetings .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $meetings .= "sort=" . $sort . "<br>";
        $meetings .= "URL=" . $data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&SortBy=' . $sort . '<br>';
        $meetings .= "==================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&SortBy=' . $sort . '&R=' . rand());
    if (strlen($xml) == 0) {
        $meetings .= 'There are no club meetings to display at this time.';
        return $meetings;
    }

    if ($options['wcm_show_title'] == 'No') {
        $meetings .= '<style>h1.entry-title { display:none !important; }</style>';
        $meetings .= '<style>.entry-header { display:none !important; }</style>';
    }

    $meetings .= '<table width="100%" class="table" style="border:0;">';
    if ($sort == 'area') {
        $meetings .= '<tr style="background-color:#cccccc;"><td><strong>Day</strong></td>';
        $meetings .= '<td><strong>Time</strong></td>';
        $meetings .= '<td><strong>Club</strong></td>';
        $meetings .= '<td><strong>Meeting Place</strong></td></tr>';
    }
    if ($sort == 'date') {
        $meetings .= '<tr style="background-color:#cccccc;"><td><strong>Time</strong></td>';
        $meetings .= '<td><strong>Club</strong></td>';
        $meetings .= '<td><strong>Meeting Place</strong></td>';
        $meetings .= '<td><strong>City</strong></td></tr>';
    }

    $this_area = '';
    $this_day = '';
    $counter = 1;

    foreach ($xml->meeting as $wcm) {

        if ($sort == 'area') {
            if (intval($wcm->region) == $this_area) {
            } else {
                $meetings .= '<tr><td style="background-color:#e3e3e3;" colspan="4">AREA ' . $wcm->region . '</td></tr>';
                $this_area = $wcm->region;
            }
            $meetings .= '<tr>';
            $meetings .= '<td valign="top">' . $wcm->meetingday . '</td>';
            $meetings .= '<td valign="top" nowrap>' . $wcm->meetingtime . '</td>';
            if ($wcm->cluburl != '') {
                $meetings .= '<td valign="top"><a href="' . $wcm->cluburl . '" target="new">' . $wcm->clubname . '</a></td>';
            } else {
                $meetings .= '<td valign="top">' . $wcm->clubname . '</td>';
            }
            $meetings .= '<td valign="top">' . $wcm->meetingplace . '</td>';
            $meetings .= '</tr>';
        } elseif ($sort == 'date') {
            if (trim($wcm->meetingday) === $this_day) {
            } else {
                $meetings .= '<tr><td style="background-color:#e3e3e3;" colspan="4">' . $wcm->meetingday . '</td></tr>';
                $this_day = trim($wcm->meetingday);
            }
            $meetings .= '<tr>';
            $meetings .= '<td valign="top" nowrap>' . $wcm->meetingtime . '</td>';
            if ($wcm->cluburl != '') {
                $meetings .= '<td valign="top"><a href="' . $wcm->cluburl . '" target="new">' . $wcm->clubname . '</a></td>';
            } else {
                $meetings .= '<td valign="top">' . $wcm->clubname . '</td>';
            }
            $meetings .= '<td valign="top">' . $wcm->meetingplace . '</td>';
            $meetings .= '<td valign="top">' . $wcm->meetingcity . '</td>';
            $meetings .= '</tr>';
        } elseif ($sort == 'detail') {

            $meetings .= '<tr>';
            $meetings .= '<td valign="top" colspan="4" style="border:0;">';
            $meetings .= '
                <a href="' . $wcm->cluburl . '" target="new"><strong>' . $wcm->clubname . '</strong></a><br>
                <i>' . $wcm->clubaddress . '<br>
                ' . $wcm->clubcity . ', ' . $wcm->clubstatecode . '</i><br>
                <strong>Where We Meet </strong><br>
                ' . $wcm->meetingplace . '<br>';
            if ($wcm->meetingaddress != '') {
                $meetings .= '' . $wcm->meetingaddress . '<br>';
            }
            $meetings .= '' . $wcm->meetingcity . ', ' . $wcm->meetingstatecode . ' ' . $wcm->meetingpostalcode . '<br>
                <strong>When</strong><br>
                ' . $wcm->meetingday . ' at ' . $wcm->meetingtime . '';
            $meetings .= '<span style="float: right;"><a href="http://maps.google.com/maps?q=' . $wcm->latitude . ',' . $wcm->longitude . '" target="new">Map It</a></span>';
            $meetings .= '<hr style="margin:10px 0 5px 0;"></td></tr>';
        } elseif ($sort == 'officers') {
            $setDivWidth = 100;
            $setImgWidth = 95;

            $meetings .= '<tr>';
            $meetings .= '<td valign="top" align="left" width="40%">';
            $officer_total = count($wcm->officers);

            if ($officer_total > 0) {
                $meetings .= '<table border="1" cellpadding="0" cellspacing="0">';
                foreach ($wcm->officers->officer as $wcmofficer) {
                    $meetings .= '<tr>';
                    $meetings .= '<td style="border:0 !important;vertical-align: top; padding:0; width:' . $setDivWidth . 'px;">';
                    if ($wcmofficer->image == '') {
                        $meetings .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" width="' . $setImgWidth . '"></div>';
                    } else {
                        $meetings .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . $wcmofficer->image . '" width="' . $setImgWidth . '"></div>';
                    }
                    $meetings .= '</td>';
                    $meetings .= '<td style="border:0 !important; text-align: left; vertical-align: top; padding:0;">';
                    $meetings .= '<strong>' . $wcmofficer->username . '</strong><BR>';
                    $meetings .= $wcmofficer->clubposition . '<BR>';
                    $meetings .= '</td>';
                    $meetings .= '</tr>';
                }
                $meetings .= '</table>';
            }
            $meetings .= '</td>';

            $meetings .= '<td valign="top" width="60%">';
            $meetings .= '
                                    <a href="' . $wcm->cluburl . '" target="new"><strong>' . $wcm->clubname . '</strong></a><br>
                                    <i>' . $wcm->clubaddress . '<br>
                                    ' . $wcm->clubcity . ', ' . $wcm->clubstatecode . '</i><br>
                                    <strong>Where We Meet </strong><br>
                                    ' . $wcm->meetingplace . '<br>';
            if ($wcm->meetingaddress != '') {
                $meetings .= '' . $wcm->meetingaddress . '<br>';
            }
            $meetings .= '' . $wcm->meetingcity . ', ' . $wcm->meetingstatecode . ' ' . $wcm->meetingpostalcode . '<br>
                                    <strong>When</strong><br>
                                    ' . $wcm->meetingday . ' at ' . $wcm->meetingtime . '';
            $meetings .= '<span style="float: right;"><a href="https://maps.google.com/maps?q=' . $wcm->latitude . ',' . $wcm->longitude . '" target="new">Map It</a></span>';

            $meetings .= '</td>';
            $meetings .= '</tr>';
            $meetings .= '<tr><td colspan="2"><hr style="margin:10px 0 5px 0;"></td></tr>';
        } else {

            $meetings .= '<tr><td valign="top">';
            if ($wcm->cluburl != '') {
                $meetings .= '<a href="' . $wcm->cluburl . '" target="new">' . $wcm->clubname . '</a> - Area ';
            } else {
                $meetings .= '' . $wcm->clubname . ' - Area ';
            }
            $meetings .= '' . $wcm->region . ' ';
            $meetings .= '' . $wcm->meetingday . ' ';
            $meetings .= '' . $wcm->meetingplace . ' ';
            $meetings .= '</td></tr>';
        }
        $counter = $counter + 1;
    }
    $meetings .= '</table>';
    return $meetings;
}


//ANCHOR - Show Meeting Info
function dacdb_meeting_info($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $meetings = '';

    $club_id = $options['dacdb_club'];

    if ($fDebug) {
        $meetings .= "=================================================================<BR>";
        $meetings .= "function dacdb_meeting_info called<br>";
        $meetings .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $meetings .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $meetings .= "URL=" . $data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '<br>';
        $meetings .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
    if (strlen($xml) == 0) {
        $meetings .= 'There are no club meetings to display at this time.';
        return $meetings;
    }

    $counter = 1;
    $div  = '<div class="col">';
    foreach ($xml->meeting as $wcm) {
        $meetings .= '<div class="dac-row">';
        $meetings .= '    <div class="col">';
        $meetings .= '        <h4>' . $wcm->clubname . '</h4>';
        $meetings .= '    </div>';
        $meetings .= '</div>';

        $meetings .= '<div class="dac-row">';
        $meetings .= '  <div class="col">';
        $meetings .= '        <strong>Where We Meet </strong><br />';
        $meetings .= '       <div style="padding-left: 10px;">';
        if ($wcm->clubaddress != "") {
            $meetings .=    '<i>' . $wcm->clubaddress . '<br />' . $wcm->clubcity . ', ' . $wcm->clubstatecode . ' ' . $wcm->clubpostalzip . '</i>';
        }
        $meetings .= '        </div>';
        $meetings .= '      <strong>Where We Meet </strong><br/>';
        $meetings .= '      <div style="padding-left: 10px;">';
        $meetings .=            $wcm->meetingplace .'<br />';
        $meetings .=            $wcm->meetingaddress . '<br />' . $wcm->meetingcity . ', ' . $wcm->meetingstatecode . ' ' . $wcm->meetingpostalcode;
        $meetings .= '      </div>';

        $meetings .= '      <strong>When</strong><br />';
        $meetings .= '      <div style="padding-left: 10px;">';
        $meetings .=            $wcm->meetingday . 's at ' . $wcm->meetingtime . '';
        if ($wcm->latlng != "") {
            $meetings .=        '<span style="float:right;"><a href="' . $wcm->latlng . '" target="new">Map It</a></span>';
        }
        $meetings .= '      </div>';
        $meetings .= '  </div>';
        $meetings .= '</div>';
        $meetings .= '<hr>';
        $counter = $counter + 1;
    }
    return $meetings;
}

//ANCHOR - Show Club Meetings
function dacdb_club_meetings($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $meetings = '';

    if ($fDebug) {
        $meetings .= "=================================================================<BR>";
        $meetings .= "function dacdb_club_meetings called<br>";
        $meetings .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $meetings .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $meetings .= "URL=" . $data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '<br>';
        $meetings .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
    if (strlen($xml) == 0) {
        $meetings .= 'There are no club meetings to display at this time.';
        return $meetings;
    }
    $counter = 1;
    foreach ($xml->meeting as $wcm) {
        $meetings .= '<div style="overflow:hidden;margin-bottom:20px;border:">';
        if ($wcm->cluburl != "") {
            $meetings .= '<div style="width:200px;float:left;"><strong><a href="' . $wcm->cluburl . '" target="new">' . $wcm->clubbadgename . '</a></strong>';
        } else {
            $meetings .= '<div style="width:200px;float:left;"><strong>' . $wcm->clubbadgename . '</strong>';
        }
        if ($wcm->clubaddress != "") {
            $meetings .=    '<br><i>' . $wcm->clubaddress . '</i><br>';
            if ($wcm->clubaddress2 != "")
                $meetings .=    '<i>' . $wcm->clubaddress2 . '</i><br>';
            if ($wcm->clubaddress3 != "")
                $meetings .=    '<i>' . $wcm->clubaddress3 . '</i><br>';
            $meetings .=    '<i>' . $wcm->clubcity . ', ' . $wcm->clubstatecode . ' &nbsp; ' . $wcm->clubpostalzip . '</i><br />';
        }

        $meetings .=    '</div>';
        $meetings .=    '<div style="overflow:hidden;padding-left: 40px;"><strong>Where: </strong> ' . $wcm->meetingplace;
        if ($wcm->meetingaddress != "") {
            $meetings .=    '<br><i>' . $wcm->meetingaddress . '</i><br>';
            if ($wcm->meetingaddress2 != "")
                $meetings .=    '<i>' . $wcm->meetingaddress2 . '</i><br>';
            if ($wcm->meetingaddress3 != "")
                $meetings .=    '<i>' . $wcm->meetingaddress3 . '</i><br>';
            $meetings .=    '<i>' . $wcm->meetingcity . ', ' . $wcm->meetingstatecode . ' &nbsp; ' . $wcm->meetingpostalzip . '</i><br />';
        }

        $meetings .=        '<strong>When:</strong> ' . $wcm->meetingday . 's at ' . $wcm->meetingtime . '';
        if ($wcm->latlng != "") {
            $meetings .=        '<span style="float:right; padding-right: 20px;"><a href="' . $wcm->latlng . '" target="new">Map It</a></span>';
        }
        $meetings .=    '</div>';
        $meetings .= '</div>';
        $meetings .= '<hr>';
        $counter = $counter + 1;
    }
    return $meetings;
}

//ANCHOR - Show Members
function dacdb_members($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $members = '';

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && isset($atts['imgwidth']) > 0 ? $atts['imgwidth'] : 150);
    $membertypes = $_GET['membertypes'] ?? $atts['membertypes'] ?? $options['membertypes'] ?? '';

    if ($fDebug) {
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_members called<br>";
        $members .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $members .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $members .= "Membertypes=" . $membertypes . "<br>";
        $members .= "URL=" . $data_path . 'wp_club_members.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . '&MemberTypeIDs=' . $membertypes . '<br>';
        $members .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_club_members.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&MemberTypeIDs=' . $options['membertypes'] . '&R=' . rand());
    if (strlen($xml) == 0) {
        $members .= 'There are no members to display at this time.';
        return $members;
    }

    $counter = 1;
    $lastCounter = count($xml->member);
    $pag_total = count($xml->member);
    $pag_pages = $pag_total / $options['mem_per_page'];
    $pag_pages = round_down($pag_pages, 0);
    $temp_pag_pages = ($pag_pages * $options['mem_per_page']);
    if ($temp_pag_pages > 0) {
        $pag_pages = $pag_pages + 1;
    }

    $members .= '<script>mypagenumber = ' . $pag_pages . ';</script>';
    $pagcounter = $options['mem_per_page'];
    $pagcountersec = 1;

    // check member cound start pagnation

    add_action('wp_footer', 'myscript', 200);
    if ($pag_pages != 0) {
        if ($options['pagnationposition_tb'] == 'Top') {
            if ($options['pagnationposition'] == 'Right') {
                $members .= '<div style="text-align:right;"><div class="pagination-dac-right" style="display:inline-block;"><ul id="pagination-dacdb" class="pagination-dac pagination"></ul></div></div>';
            } else {
                $members .= '<div><ul id="pagination-dacdb" class="pagination-dac pagination"></ul></div>';
            }
        }
    }

    $members .= '<div id="page-wrapper">';
    $grid_counter = 0;
    foreach ($xml->member as $member) {
        if ($pagcounter == $options['mem_per_page']) {
            $members .= '<div class="page-content"  id="pagsec' . $pagcountersec . '">';
            $pagcountersec = $pagcountersec + 1;
        } else {
            if ($pagcounter % $options['mem_per_page'] == 0) {
                $members .= '<div class="page-content"  id="pagsec' . $pagcountersec . '" style="display:none;">';
                $pagcountersec = $pagcountersec + 1;
            }
        }
        $grid_counter = $grid_counter + 1;
        if ($options['members_per_row'] == 1) {
            $grid_counter = 1; // force single row
        }
        if ($grid_counter == 1) {
            $members .= '<div class="dac-row">';
        }

        $setDivWidth = 150;
        $setImgWidth = 140;

        if ($options['members_per_row'] == 1) {
            $members .= '<div class="members dac-col-xs-12">';
        } else if ($options['members_per_row'] == 2) {
            $members .= '<div class="members dac-col-xs-12 dac-col-sm-6">';
        } else if ($options['members_per_row'] == 3) {
            $members .= '<div class="members dac-col-xs-12 dac-col-sm- dac-col-md-4">';
        } else if ($options['members_per_row'] == 4) {
            $members .= '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
            $setDivWidth = 120;
            $setImgWidth = 110;
        }

        if ($options['member_pics'] == 1) {
            if ($member->image == '') {
                $members .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth  . 'px; object-fit: cover;" width="' . $setImgWidth  . '"></td>';
            } else {
                $members .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . $member->image . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth  . 'px; object-fit: cover;" width="' . $setImgWidth  . '"></td>';
            }
        }

        $members .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td><td style="border:0 !important;vertical-align: top;padding:0;"><strong>' . $member->username . '</strong><br>';

        if ($options['member_club_pos'] == 1) {
            if ($member->clubposition != '') {
                $members .= '(' . $member->clubposition . ')<br>';
            }
        }
        if ($options['members_since'] == 1) {
            $startdate = strtotime($member->startdate);
            if ($options['members_since_format'] == 1) {
                $newformat = date('n/j/Y', $startdate);
            } elseif ($options['members_since_format'] == 2) {
                $newformat = date('n/Y', $startdate);
            } else {
                $newformat = date('Y', $startdate);
            }
            $members .= 'Member Since: ' . $newformat . '<br>';
        }
        if ($options['member_bus_name'] == 1) {
            if ($member->busweb != '') {
                if (strpos($member->busweb, "http://") == false) {
                    $newURL = 'http://' . $member->busweb;
                }
                $members .= '<a href="' . $newURL . '" target="_blank">' . $member->busname . '</a><br>';
            } else {
                $members .= $member->busname . '<br>';
            }
        }
        if ($options['member_bus_name'] == 0 && $options['member_bus_url'] == 1) {
            if ($member->busweb != '') {
                if (strpos($member->busweb, "http://") == false) {
                    $newURL = 'http://' . $member->busweb;
                }
                $members .= '<a href="' . $newURL . '" target="_blank">' . $member->busweb . '</a><br>';
            }
        }

        if ($options['member_bus_pos'] == 1) {
            if ($member->busposition != '') {
                $members .= $member->busposition . '<br>';
            }
        }

        if ($options['member_class'] == 1) {
            if ($member->classification != '') {
                $members .= $member->classification . '<br>';
            }
        }

        if ($options['members_contact_link'] == 1) {
            $members .= '<a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $member->userid . '" name="cmc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
        }
        $members .= '</td></tr></table></div>';
        $counter = $counter + 1;
        $pagcounter = $pagcounter + 1;

        if ($pagcounter % $options['mem_per_page'] == 0) {
            $members .= '</div>';
        }

        if ($grid_counter == $options['members_per_row']) {
            $members .= '</div>';
            $grid_counter = 0;
        }
    }
    $members .= '<!-- ' . $lastCounter . '-' . $counter . '-' . $grid_counter . ' -->';
    if ($grid_counter > 0) {
        $members .= '</div><!-- end  -->';
    }
    $members .= '</div>';
    $members .= '</div>';

    if ($pag_pages != 0) {
        if ($options['pagnationposition_tb'] == 'Bottom') {
            if ($options['pagnationposition'] == 'Right') {
                $members .= '<div style="text-align:right;"><div class="pagination-dac-right" style="display:inline-block;"><ul id="pagination-dacdb" class="pagination-dac pagination"></ul></div></div>';
            } else {
                $members .= '<div><ul id="pagination-dacdb" class="pagination-dac pagination"></ul></div>';
            }
        }
    }
    return $members;
}

//ANCHOR - Show Club Presidents
/**
 * Generate HTML content for displaying club presidents.
 *
 * @param array $atts The attributes passed to the function (none used in this case).
 * @return string The HTML content for displaying club presidents.
 */
function dacdb_club_presidents($atts)
{
    global $fDebug, $data_path, $options;

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    $leaders = '';

    if ($fDebug) {
        $leaders .= "=================================================================<BR>";
        $leaders .= "function dacdb_club_presidents called<br>";
        $leaders .= "AccountID=" . $account_id . "<br>";
        $leaders .= "leaders_contact_link=" . $options['leaders_contact_link'] . "<br>";
        $leaders .= "data_path=" . $data_path . "<br>";
        $leaders .= "ClubID=" . $club_id . "<br>";
        $leaders .= "URL=" . $data_path . 'wp_leaders.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id . '<br>';
        $leaders .= "=================================================================<BR>";
    }
    
    try {
        $xml = simplexml_load_file($data_path . 'wp_ccp.cfm?AccountID=' . $account_id . '&RoleKey=P&SortBy=C' . '&R=' . rand());
        if (strlen($xml) == 0) {
            $leaders .= 'There are no club presidents to display at this time.';
            return $leaders;
        }
    } catch (Exception $e) {
        return 'Error: ' . $e->getMessage();
    }
    $counter = 1;
    $cnt = 0;
    $lastCounter = count($xml->ccp);
    foreach ($xml->ccp as $ccp) {
        $grid_counter = isset($grid_counter) ? $grid_counter + 1 : 1;

        $presidentsPerRow = isset($options['club_presidents_per_row']) ? $options['club_presidents_per_row'] : 1;

        if ($presidentsPerRow == 1) {
            $grid_counter = 1; // force single row
        }

        if ($grid_counter == 1) {
            $leaders .= '<div class="dac-row">';
        }

        $presidentClasses = [
            1 => 'members dac-col-xs-12',
            2 => 'members dac-col-xs-12 dac-col-sm-6',
            3 => 'members dac-col-xs-12 dac-col-sm-12 dac-col-md-4',
            4 => 'members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3'
        ];

        $leaders .= '<div class="' . ($presidentClasses[$presidentsPerRow] ?? 'members') . '">';

        // Adjust div and image widths based on number of presidents per row
        $setDivWidth = ($presidentsPerRow == 4) ? 120 : 150;
        $setImgWidth = ($presidentsPerRow == 4) ? 110 : 140;

        if (
            $ccp->image == ''
        ) {
            $leaders .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth  . 'px; object-fit: cover;" width="' . $setImgWidth  . '"></td>';
        } else {
            $leaders .= '<table style="vertical-align: top;padding:0;border:0 !important;"><tr><td style="border:0 !important;vertical-align: top;padding:0;max-width:' . $setDivWidth . 'px;width:' . $setDivWidth . 'px"><img src="' . $ccp->imgpath . '' . $ccp->image . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth  . 'px; object-fit: cover;" width="' . $setImgWidth  . '"></td>';
        }
        $leaders .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;">&nbsp;</td>';
        $leaders .= '<td style="border:0 !important;vertical-align: top;padding:0;">';
        $leaders .= '<strong>' . $ccp->membername . '</strong><br>' . $ccp->clubname . '<br>';
        if ($options['leaders_contact_link'] == 1) {
            $leaders .= '       <a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $ccp->userid . '" name="dlc-inline-link-' . $cnt . '" class="iframe3 cboxElement">Contact</a>';
        }
        $leaders .= '</td>';


        $leaders .= '</tr></table></div>';
        $cnt++;
        if ($grid_counter == $options['club_presidents_per_row']) {
            $leaders .= '</div>';
            $grid_counter = 0;
        }
    }
    if ($grid_counter > 0) {
        $leaders .= '</div><!-- end  -->';
    }
    return $leaders;
}

//ANCHOR - Show Speakers
function dacdb_speakers($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $speakers = '';

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];

    $N = 0;
    if (isset($atts['n'])) {            // No of Speakers
        $N = $atts['n'];
    }

    if ($fDebug) {
        $speakers .= "=================================================================<BR>";
        $speakers .= "function dacdb_speakers called<br>";
        $speakers .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $speakers .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $speakers .= "CatIDs=" . $options['speaker_cats'] . "<br>";
        $speakers .= "Mo=" . $options['speakers_months'] . "<br>";
        $speakers .= "N=" . $N . "<br>";
        $speakers .= $data_path . 'wp_speakers.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&CatIDs=' . $options['speaker_cats'] . '&Mo=' . $options['speakers_months'] . "<br>";
        $speakers .= "=================================================================<BR>";
    }
    $xml = simplexml_load_file($data_path . 'wp_speakers.cfm?AccountID=' . $options['dacdb_district'] . '&Mo=' . $options['speakers_months'] . '&CatIDs=' . $options['speaker_cats'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
    if (strlen($xml) == 0) {
        $speakers .= 'There are no speakers at this time.';
        return  $speakers;
    }

    $counter = 0;
    foreach ($xml->speakerinfo as $speakerinfo) {
        $speakers .= '<div class="dacdb_plus_event">';

        if ($options['events_global_date'] == 1) {
            $speakers .= date("F jS Y", strtotime($speakerinfo->eventdate)) . ' at ' . date("g:i a", strtotime($speakerinfo->eventdate));
            $speakers .= '<br>';
        }
        $speakers .= '<strong>' . $speakerinfo->eventname . '</strong>';
        if ($options['speaker_page_full'] == 0) {
            $speakers .= '<br><strong>Speaker: ' . $speakerinfo->speaker . '</strong>';
            $speakers .= '<br>' . $speakerinfo->topic;
        }

        $speakers .= '<br>';
        if ($options['events_global_date'] == 0) {
            $speakers .= date("F jS Y", strtotime($speakerinfo->eventdate)) . ' at ' . date("g:i a", strtotime($speakerinfo->eventdate));
            $speakers .= '<br>';
        }
        if ($options['speaker_page_full'] == 1) {
            $speakers .= '' . $speakerinfo->description;
        } else {
            $speakers .= '<a class="iframe cboxElement" href="' . $data_path . 'R_Event.cfm?EventID=' . $speakerinfo->eventid . '">More info</a>';
        }
        $speakers .= '</div>';
        $speakers .= '<hr>';
        $counter = $counter + 1;
        if ($N > 0 and $counter >= $N) {
            return $speakers;
        }
    }
    return $speakers;
}

//ANCHOR - Show Events
function dacdb_events($atts)
{
    global $fDebug, $data_path, $file_path, $options;
    $events = '';
    
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    
    // Validate and sanitize $type
    $type = $_GET['type'] ?? $atts['type'] ?? ($club_id == 0 ? 'district' : 'club');
    $type = in_array($type, ['district', 'club']) ? trim($type) : 'district';

    // Validate and sanitize $district_catids
    $district_catids = $_GET['catids'] ?? $atts['catids'] ?? $options['district_events_types_page'] ?? '';
    $district_catids = preg_replace('/[^0-9,]/', '', $district_catids);

    // Validate and sanitize $club_catids
    $club_catids = $_GET['catids'] ?? $atts['catids'] ?? $options['club_events_types_page'] ?? '';
    $club_catids = preg_replace('/[^0-9,]/', '', $club_catids);

    // Validate and sanitize $categoryids
    $categoryids = $type === 'district' ? $district_catids : $club_catids;
    $categoryids = preg_replace('/[^0-9,]/', '', $categoryids);

    // Validate and sanitize $wk
    $wk = $_GET['wk'] ?? $atts['wk'] ?? 0;
    $wk = in_array($wk, [0, 1]) ? intval($wk) : 0;

    // Validate and sanitize $showTZ
    $showTZ = $_GET['showTZ'] ?? $atts['showTZ'] ?? 0;
    $showTZ = in_array($showTZ, [0, 1]) ? intval($showTZ) : 0;

    // Validate and sanitize $showGMT
    $showGMT = $_GET['showgmt'] ?? $atts['showgmt'] ?? 0;
    $showGMT = in_array($showGMT, [0, 1]) ? intval($showGMT) : 0;

    // Sanitize $mo
    $mo = $_GET['Mo'] ?? $atts['Mo'] ?? $options['district_events_months'] ?? '';
    $mo = trim($mo);
    
    $xml_params = [
        'AccountID' => $account_id,
        'ClubID' => $club_id,
        'R' => rand(),
    ];
    
    if (!empty($categoryids)) {
        $xml_params['CatIDs'] = $categoryids;
    }
    
    $request_url = $data_path . 'wp_event.cfm?' . http_build_query($xml_params);
    
    $xml = $wk > 0
        ? simplexml_load_file("$request_url&wk=$wk")
        : simplexml_load_file("$request_url&Mo=$mo");
    
    if (empty($xml)) {
        $events .= 'There are no events at this time.';
        return $events;
    }

    if ($fDebug) {
        $debug_vars = [
            'type' => $type,
            'district_catids' => $district_catids,
            'club_catids' => $club_catids,
            'categoryids' => $categoryids,
            'wk' => $wk,
            'showTZ' => $showTZ,
            'showGMT' => $showGMT,
            'mo' => $mo,
            'xml_params' => $xml_params,
            'request_url' => $request_url,
            'xml' => $xml, // Assuming you have the XML content in a variable named $xml
            // Add any other variables you wish to debug
        ];

        dacdb_debug('dacdb_events', $atts, $options, $debug_vars, $xml);
    }

    $counter = 1;
    foreach ($xml->event as $event) {
        $events .= '<div class="dacdb_plus_event">';
    
        if ($options['events_global_date'] == 1) {
            $startDateTime = date("Y-m-d H:i", strtotime($event->startdate));
            $events .= '<time datetime="' . $startDateTime . '">';
            $events .= date("F jS Y, g:i a", strtotime($event->startdate));
            $events .= '</time>';
    
            if ($showTZ)
                $events .= ' ' . $event->tz;
            if ($showGMT)
                $events .= ' ' . $event->gmtoffset;
            $events .= '<br>';
        }
    
        $events .= '<strong>' . $event->eventname . '</strong>';
    
        if ($event->description != '') {
            $events .= '<br>' . $event->description;
        }
    
        if ($options['club_events_show_speakers_info'] == 1) {
            if ($event->speaker != '') {
                $events .= '<br><strong>Speaker: ' . $event->speaker . '</strong>';
            }
            if ($event->topic != '') {
                $events .= '<br>Topic: ' . $event->topic;
            }
        }
    
        if ($options['events_global_date'] == 0) {
            $startDateTime = date("Y-m-d H:i", strtotime($event->startdate));
            $events .= '<br><time datetime="' . $startDateTime . '">';
            $events .= date("F jS Y \a\\t g:i a", strtotime($event->startdate));
            $events .= '</time>';
    
            if ($showTZ)
                $events .= ' ' . $event->tz;
            if ($showGMT)
                $events .= ' ' . $event->gmtoffset;
        }
    
        $events .= '<br>';
        $events .= '<a class="iframe cboxElement" sandbox="allow-top-navigation" href="' . $data_path . 'R_Event.cfm?EventID=' . $event->eventid . '">More info</a>';
        $events .= '<br></div>';
        $events .= '<hr class="dacdb_plus_event_hr">';
        $counter = $counter + 1;
    }
    
    return $events;
}    


//ANCHOR - Show Committee Leaders
function dacdb_committee_leaders($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];

    $style      = isset($atts['style']) ? $atts['style'] : 1;
    $rolekeys   = isset($atts['rolekeys']) ? $atts['rolekeys'] : 'DLT';
    $members = '';

    if ($fDebug) {
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_d_leaders called<br>";
        $members .= "AccountID=" . $account_id . "<br>";
        $members .= "data_file=" . $data_file . "<br>";
        $members .= "data_path=" . $data_path . "<br>";
        $members .= "ClubID=" . $club_id . "<br>";
        $members .= "RoleKey=" . $rolekeys . "<br>";
        $members .= "Style=" . $style . "<br>";
        $members .= "URL=" . $data_path . 'wp_committeeleaders.cfm?AccountID=' . $account_id . '&rolekey=' . $rolekeys . '<br>';
        $members .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_committeeleaders.cfm?AccountID=' . $account_id . '&rolekey=' . $rolekeys . '&R=' . rand());
    if (strlen($xml) == 0) {
        $members .= 'There are no committee leaders to display at this time.';
        return $members;
    }

    $cnt = 0;
    $records = count($xml->dlc);
    $members .= dacdb_DisplayMembers($xml, $style, $atts);    // hard coded style=2 Kees' flag
    return $members;
}

//ANCHOR - Show District Leaders
function dacdb_d_leaders($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $leaders = '';

    $account_id = $options['dacdb_district'];
    $club_id    = $options['dacdb_club'];
    if (isset($atts['leaders_per_row']) && $atts['leaders_per_row'] !== '') {
        $atts['leaders_per_row'] = $atts['leaders_per_row'];
    } elseif (isset($options['leaders_per_row']) && $options['leaders_per_row'] !== '') {
        $atts['leaders_per_row'] = $options['leaders_per_row'];
    } else {
        $atts['leaders_per_row'] = 1;
    }

    if (isset($atts['leader_pics']) && $atts['leader_pics'] !== '') {
        $atts['leader_pics'] = $atts['leader_pics'];
    } elseif (isset($options['leader_pics']) && $options['leader_pics'] !== '') {
        $atts['leader_pics'] = $options['leader_pics'];
    } else {
        $atts['leader_pics'] = 1;
    }


    if ($fDebug) {
        $leaders .= "=================================================================<BR>";
        $leaders .= "function dacdb_d_leaders called<br>";
        $leaders .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $leaders .= "data_file=" . $data_file . "<br>";
        $leaders .= "data_path=" . $data_path . "<br>";
        $leaders .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $leaders .= "leaders_per_row=" . $options['leaders_per_row'] . "<br>";
        $leaders .= "leaders_per_row override=" . $atts['leaders_per_row'] . "<br>";
        $leaders .= "URL=" . $data_path . 'wp_dlc.cfm?AccountID=' . $options['dacdb_district'] . '<br>';
        $leaders .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_dlc.cfm?AccountID=' . $options['dacdb_district'] . '&R=' . rand());
    if (strlen($xml) == 0) {
        $leaders .= 'There are no district leaders to display at this time.';
        return $leaders;
    }

    $cnt = 0;
    $records = count($xml->dlc);
    //$leaders .= 'cols='. $cols.'<br />';
    //$leaders .= 'count='. $records.'<br />';

    $leaders .= '<div class="dac-row">';

    foreach ($xml->dlc as $member) {

        $cols = $atts['leaders_per_row'];
        if ($options['leaders_per_row'] == 1) {
            $leaders .= '<div class="members dac-col-xs-12">';
            $setDivWidth = 155;
            $setImgWidth = 150;
        } else if ($options['leaders_per_row'] == 2) {
            $leaders .= '<div class="members dac-col-xs-12 dac-col-sm-6">';
            $setDivWidth = 140;
            $setImgWidth = 135;
        } else if ($options['leaders_per_row'] == 3) {
            $leaders .= '<div class="members dac-col-xs-12 dac-col-sm-12 dac-col-md-4">';
            $setDivWidth = 125;
            $setImgWidth = 120;
        } else if ($options['leaders_per_row'] == 4) {
            $leaders .= '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
            $setDivWidth = 110;
            $setImgWidth = 105;
        }

        // $leaders .= $member->membername.'<br />';
        $leaders .= '<table style="vertical-align: top; padding:0;  !important;">';
        $leaders .=  '  <tr>';
        if ($atts['leader_pics'] == 1) {
            $leaders .=  '      <td style="vertical-align: top; padding:0; max-width:' . $setDivWidth . 'px; width:' . $setDivWidth . 'px">';
            if ($member->image == '') {
                $leaders .= '       <img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" width="' . $setImgWidth . '" style="border:1; max-width:' . $setImgWidth . 'px">';
            } else {
                $leaders .= '       <img src="' . $member->imgpath . '' . $member->image . '" width="' . $setImgWidth . '" style="border:1; max-width:' . $setImgWidth . 'px">';
            }
            $leaders .=  '      </td>';
        }

        $leaders .= '       <td style="vertical-align: top;  max-width: 150px; padding: 0;">';
        $leaders .= '           <strong>' . $member->membername . '</strong><br>';

        $formattedUrl = formatDomainToUrl($member->cluburl); 
        if (!empty($formattedUrl)) {
            $leaders .= '<a href="' . $formattedUrl . '" target="new">' . $member->clubname . '</a><br>';
        } else {
            $leaders .= '<span class="clubname">' . $member->clubname . '<br></span>';
        }

        $leaders .= '           ' . $member->committeeposition . '<br>';

        if ($options['leaders_contact_link'] == 1) {
            $leaders .= '       <a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $member->userid . '" name="dlc-inline-link-' . $cnt . '" class="iframe3 cboxElement">Contact</a>';
        }

        $leaders .=  '      </td>';
        $leaders .=  '  </tr>';
        $leaders .=  '</table>';
        $leaders .= '</div>'; // <!-- col -->

        $cnt++;
        if (($cnt % $cols) == 0  & $cnt < $records) {
            $leaders .= '</div><div class="dac-row">';
        }
    }

    $leaders .= '</div>'; //<!-- dac-row  -->
    return $leaders;

    /*
    $counter = 1;
    $grid_counter = 0;
    foreach($xml->dlc as $member) {
        $grid_counter = $grid_counter + 1;
        if ($options['leaders_per_row'] == 1) {
            $grid_counter = 1; // force single row
        }
        if ( $grid_counter == 1 ) {
            $leaders .= '<div class="dac-row">';
        }
        if ($options['leader_pics'] == 1) {
            if ( $dlc->image == '' ) {
                $leaders .= '<div class="dac-col-6-12" style="width:'.$setDivWidth.'px; float:left;"><img src="'. plugins_url( 'img/no_image.jpg', __FILE__ ) .'" width="'.$setImgWidth.'"></div>';
            } else {
                $leaders .= '<div class="dac-col-6-12" style="width:'.$setDivWidth.'px; float:left;"><img src="'.$dlc->imgpath.''.$dlc->image.'" width="'.$setImgWidth.'"></div>';
            }
        }
        $leaders .= '<td style="border:0 !important;max-width:1px;width:1px;padding:0;"></td><td style="border:0 !important;vertical-align: top;padding:0;"><strong>'.$dlc->membername.'</strong><br>'.$dlc->committeeposition;
        $leaders .= '<br>Club: <a href="'.$dlc->cluburl.'" target="new">'.$dlc->clubname.'</a><br><br>';
        if ($options['leaders_contact_link'] == 1) {
            $leaders .= '<a href="'.$data_path.'R_Emailer.cfm?UserID='.$dlc->userid.'" name="dlc-inline-link-'.$counter.'" class="iframe3 cboxElement">Contact</a>';
        }
        $leaders .= '</td></tr></table>';
        $leaders .= '</div>';
        if ( $grid_counter == $options['leaders_per_row'] ) {
            $leaders .= '</div>';
            $grid_counter = 0;
        }
        $counter = $counter + 1;
    }
    return $leaders;
*/
}

//ANCHOR - Show Stories
//TODO - STORIES: Refactor this to simplify functional responsibility
/**
 * Returns a string containing stories
 *
 * @param array $atts
 * @return int
 * @throws Exception If element in array is not an integer
 */
function dacdb_stories($atts)
{
    global $fDebug, $data_path, $file_path, $options;
    $stories = '';
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];

    $story_sep = $_GET['story_sep'] ?? $atts['story_sep'] ?? $options['story_sep'] ?? '';
    $story_image = $_GET['story_image'] ?? $atts['story_image'] ?? $options['story_image'] ?? '';
    $story_open = $_GET['story_open'] ?? $atts['story_open'] ?? $options['story_open'] ?? '';
    $story_limit = $_GET['story_limit'] ?? $atts['story_limit'] ?? $options['story_limit'] ?? '';
    $story_url = $_GET['story_url'] ?? $atts['story_url'] ?? $options['story_url'] ?? '';
    $catid = $_GET['storyid'] ?? $_GET['catid'] ?? $atts['catid'] ?? $options['catid'] ?? '';
    $storyid = $_GET['storyid'] ?? $atts['storyid'] ?? $options['storyid'] ?? '';
    $smstyle = $_GET['smstyle'] ?? $atts['smstyle'] ?? $options['smstyle'] ?? 1;
    $share_value = $_GET['share'] ?? $atts['share'] ?? $options['story_share'] ?? '1';
    $share = in_array($share_value, ['Y', '1']) ? 'Y' : 'N';

    // Base URL
    $url = $data_path . 'wp_stories.cfm';

    // Query parameters
    $params = [
        'AccountID' => $account_id,
        'ClubID' => $club_id,
        'CatIDs' => isset($catid) && $catid !== '' ? $catid : null,
        'StoryID' => isset($storyid) && $storyid !== '' ? $storyid : null,
        'N' => isset($story_limit) && $story_limit !== '' ? $story_limit : null
    ];

    // Filter out null values and build query string
    $query = http_build_query(array_filter($params));

    // Concatenate base URL with query string
    $url .= '?' . $query;
    $xml = simplexml_load_file($url . '&R=' . rand());

    if ($fDebug) {
        $stories .= '
        <h5>function <em><strong>dacdb_stories</strong></em> called:</h5>
        <h4 class="drawer">Shortcode Settings</h4>
        <pre class="panel">
            <dl>
                <dt>$options[\'story_sep\']</dt><dd>' . (!empty($options['story_sep']) ? $options['story_sep'] : 'Not set') . '</dd>
                <dt>$options[\'story_image\']</dt><dd>' . (isset($options['story_image']) ? $options['story_image'] : 'Not set') . '</dd>
                <dt>$options[\'story_open\']</dt><dd>' . (isset($options['story_open']) ? $options['story_open'] : 'Not set') . '</dd>
                <dt>$options[\'story_share\']</dt><dd>' . (isset($options['story_share']) ? $options['story_share'] : 'Not set') . '</dd>
                <dt>$options[\'story_limit\']</dt><dd>' . (isset($options['story_limit']) ? $options['story_limit'] : 'Not set') . '</dd>
                <dt>$options[\'story_url\']</dt><dd>' . (isset($options['story_url']) ? $options['story_url'] : 'Not set') . '</dd>
            </dl>
        </pre>';
        // Show shortcode attributes if there are any
        if (count($atts) > 1) {
            $stories .= '<h4 class="drawer">Shortcode Attributes</h4>
                                <pre class="panel">
                                    <dl>';
            foreach ($atts as $key => $value) {
                $stories .= '    <dt>$_[\'' . $key . '\']</dt><dd>' . $value . '</dd>';
            }
            $stories .= '</dl>
                    </pre>'; // Close the drawer
        }
        // show URL parameters if there are any (Except Debug)
        if (count($_GET) > 1 || (count($_GET) == 1 && !array_key_exists("debug", $_GET))) {
            $stories .= '<h4 class="drawer">URL Parameters</h4>
                                <pre class="panel">
                                    <dl>';
            foreach ($_GET as $key => $value) {
                if ($key == "debug") {
                    continue; // Skip the rest of the loop for this iteration
                }
                $stories .= '    <dt>$_[\'' . $key . '\']</dt><dd>' . $value . '</dd>';
            }
            $stories .= '</dl>
                </pre>'; // Close the drawer
        }
        $stories .= '
            <h4 class="drawer">Named Variables</h4>
            <pre class="panel">
                <dl>
                    <dt>$story_sep</dt><dd>' . (isset($story_sep) ? $story_sep : 'Not set') . '</dd>
                    <dt>$story_image</dt><dd>' . (isset($story_image) ? $story_image : 'Not set') . '</dd>
                    <dt>$story_open</dt><dd>' . (isset($story_open) ? $story_open : 'Not set') . '</dd>
                    <dt>$story_share</dt><dd>' . (isset($story_share) ? $story_share : 'Not set') . '</dd>
                    <dt>$story_limit</dt><dd>' . (isset($story_limit) ? $story_limit : 'Not set') . '</dd>
                    <dt>$story_url</dt><dd>' . (!empty($story_url) ? $story_url : 'Not set') . '</dd>
                    <dt>$storyid</dt><dd>' . (!empty($storyid) ? $storyid : 'Not set') . '</dd>
                    <dt>$catid</dt><dd>' . (isset($catid) ? $catid : 'Not set') . '</dd>
                    <dt>$share</dt><dd>' . (isset($share) ? $share : 'Not set') . '</dd>
                    <dt>$smstyle</dt><dd>' . (isset($smstyle) ? $smstyle : 'Not set') . '</dd>
                    <dt>$hrstyle</dt><dd>' . (isset($hrstyle) ? $hrstyle : 'Not set') . '</dd>
                </dl>
            </pre>
            <h4 class="drawer">URLs</h4>
            <pre class="panel">
                <dl>
                    <dt>$file_path</dt><dd>' . $file_path . '</dd>
                    <dt>$url</dt><dd><a href="' . $url . '" target="debug-tab">' . $url . '</a></dd>
                </dl>
            </pre>
            <h4 class="drawer">XML Output</h4>
            <div class="panel">';
        foreach ($xml->story as $story) {
            $dom = new DOMDocument();
            $dom->preserveWhiteSpace = false; // Don't preserve whitespaces
            $dom->formatOutput = true; // Format output with indentation and line breaks
            $dom->loadXML($story->asXML()); // Load the XML string from SimpleXMLElement
            $formattedXml = $dom->saveXML(); // Save the formatted XML to a string
            $stories .= '<pre>' . htmlspecialchars($formattedXml) . '</pre>';
        }
        $stories .= '
            </div>
        </div>'; // Close the drawer and panel
    }

    if (strlen($xml) == 0) {
        $stories .= 'There are no stories at this time.';
    } else {
        $counter = 1;
        foreach ($xml->story as $story) {
            $stories .= '<div class="" style="overflow:hidden; padding: 10px; margin-bottom: 20px;">';
            $stories .= '    <div class="row" style="width:100%; margin: 0 auto;">';
            $stories .= '        <div style="width: 75%; float: left; text-align: left;"> ';
            $stories .= '            <h1 class="dacdb-story-header">' . $story->headline . '</h1>';
            $stories .= '        </div>';
            $stories .= '        <div class="mmp-share" style="width: 25%; float: right; text-align: right; "> ';
            //$stories .= ' id='. $story->storyid;
            if ($share == 'Y') {
                $stories .= dacdb_SMIcons($share, $smstyle, $story->smsoptions, $story->storyid, $story->headline );    //SM ICONS HER
            }
            $stories .= '        </div>';
            $stories .= '    </div>';

            if ($story->bitstorydate == 1) {
                $stories .= '<div class="row" style="margin-left: 0px; margin-bottom: 20px; >';
                $stories .= '    <span class="posted-on">';
                $stories .=             $story->storydate;
                $stories .= '    </span>';
                $stories .= '</div> ';
            }
            if ($story->bitbyline == 1) {
                $stories .= ' <span class="posted-by">';
                if ($story->biteditedby == 1) {
                    $stories .= 'By: ' . $story->modifiedby;
                } else {
                    $stories .= 'By: ' . $story->submittedby;
                }
                $stories .= '</span><br/>';
            }

            if ($story->image != '') {
                if ($options['story_image'] == 2) {
                    $stories .= '<img src="' . $story->image . '" align="right" width="150" style="padding-left:10px;width:150px;">';
                } elseif ($options['story_image'] == 1) {
                    $stories .= '<img src="' . $story->image . '" align="left"  width="150" style="float:left;padding-right:10px;width:150px;">';
                } else {
                    if ($counter % 2 == 0) {
                        $stories .= '<img src="' . $story->image . '" align="right" width="150" style="padding-left:10px;width:150px;">';
                    } else {
                        $stories .= '<img src="' . $story->image . '" align="left" width="150" style="float:left;padding-right:10px;width:150px;">';
                    }
                    $counter++;
                }
            }
            $stories .= $story->summary;
            if (trim($story->description) != '') {
                if ($storyid && isset($display) && $display == 'Y') {
                    $stories .= $story->summary;
                } else {
                    $stories .= '<div id="description-' . $story->storyid . '" class="stories-summary" style="display:none;">' . $story->description . '</div>';
                    if ($options['story_open'] == 0) {
                        $stories .= '<br><br><a href="#" onclick="return showdiv(' . $story->storyid . ')" id="more-' . $story->storyid . '">Read More</a>';
                    } elseif ($options['story_open'] == 1) {
                        $stories .= '<br><br><a href="?storyid=' . $story->storyid . '"  id="more-' . $story->storyid . '">Read More</a>';
                    } elseif ($options['story_open'] == 2) {
                        $stories .= '<br><br><a href="?storyid=' . $story->storyid . '"  id="more-' . $story->storyid . '" target="_blank">Read More</a>';
                    }
                }
            }
            //if ($options['story_share']) {
            //    $stories .= '<span style="float: right!important;"><a href="?storyid=' . $story->storyid . '">Share</a></span>';
            //}
            // if ($_GET["storyid"]) {
            //if ($storyid) {
            //    $stories .= '<style>h1.entry-title { display:none !important; }</style>';
            //    $stories .= '<style>.entry-header { display:none !important; }</style>';
            //}

            //if ( $pagetitle == 'N') {
            //    $stories .= '<style>h1.entry-title { display:none !important; }</style>';
            //}

            $stories .= '</div>';
            $separator = isset($options['story_sep']) ? $options['story_sep'] : 'no';
            if (!$storyid && $separator != 'no') {
                if ($story->bitinchr == 1 && isset($options['story_sep'])) {
                    $hrstyles = array(
                        "1" => 'style-one',
                        "2" => 'style-two',
                        "3" => 'style-three',
                        "4" => 'style-four',
                        "5" => 'style-five',
                        "6" => 'style-six',
                        "7" => 'style-seven',
                        "8" => 'style-eight'
                    );
                    $hrstyle = isset($hrstyles[$options['story_sep']]) ? $hrstyles[$options['story_sep']] : '';
                    $stories .= '<hr class="' . $hrstyle . '">';
                }
            }
        }
    }
    return $stories;

} // END function dacdb_stories

//ANCHOR - Show Calendar
/**
 * Generates the HTML markup for a FullCalendar.
 *
 * @param array $atts An associative array of attributes
 *
 * @return string The generated calendar HTML.
 */
function dacdb_calendar($atts){
    global $fDebug, $data_path, $file_path, $options;
    $calendar = "";
    $views = "dayGridMonth,listMonth";

    // plugin parameters
    // All variable values are set in order: 
    //    URL string > shortcode attribute > plugin settings > default value.

    // Determine the club ID to render in the calendar (if any)
    $club_id = isset($_GET['club_id']) ? $_GET['club_id'] : (isset($atts['club_id']) ? $atts['club_id'] : $options['dacdb_club']);

    // Determine the default event category IDs
    $eids = isset($_GET['catids']) ? $_GET['catids'] : (isset($_GET['catid']) ? $_GET['catid'] : (isset($atts['catids']) ? $atts['catids'] : (isset($atts['catid']) ? $atts['catid'] : ($club_id == 0 ? $options['district_events_types_page'] : $options['club_events_types_page']))));

    // Set the layout of the rendered calendar
    $view = (isset($_GET['view']) && in_array($_GET['view'], ['list', 'listMonth', '1'])) ? 'listMonth' : (isset($atts['view']) && in_array($atts['view'], ['list', 'listMonth', '1']) ? 'listMonth' : (isset($_GET['view']) && in_array($_GET['view'], ['month', '0', 'dayGridMonth']) || (isset($atts['view']) && in_array($atts['view'], ['month', '0', 'dayGridMonth'])) ? 'dayGridMonth' : (!empty($options['cal_display']) && in_array($options['cal_display'], ['listMonth', 'dayGridMonth']) ? $options['cal_display'] : 'dayGridMonth')));

    // Set the default calendar limit
    $callimit = (isset($_GET['cal_limit']) && $_GET['cal_limit'] >= 1 && $_GET['cal_limit'] <= 9) ? $_GET['cal_limit'] : (isset($atts['cal_limit']) && $atts['cal_limit'] >= 1 && $atts['cal_limit'] <= 9 ? $atts['cal_limit'] : (!empty($options['cal_limit']) && $options['cal_limit'] >= 1 && $options['cal_limit'] <= 9 ? $options['cal_limit'] : 5));

    $sector = isset($_GET['sector']) ? $_GET['sector'] : (isset($atts['sector']) ? $atts['sector'] : '');

    // Build URLs for XML and json sources
    $event_url = $data_path."R_GetEventsV2.cfm?AccountID=".$options['dacdb_district']."&ClubID=" . $club_id . "&EventCategoryIDs=" . $eids;
    if ($sector != '') {
        $event_url .= "&Sector=" . $sector;
    }

    $eventID_json = $data_path."wp_eventcategory.cfm?D=" .$options['dacdb_district'];
    if ( $fDebug )  {
        $calendar .= '<h5>function <em><strong>dacdb_calendar</strong></em> called:</h5>
                <pre>
                    <dl>
                        <dt>$options[\'club_id\']</dt><dd>' . $options['dacdb_club'] . ' <em>(from settings)</em></dd>
                        <dt>$_GET[\'club_id\']</dt><dd>' . (isset($_GET['club_id']) ? $_GET['club_id'] : 'Not set') . ' <em>(Query string)</em></dd>
                        <dt>$atts[\'club_id\']</dt><dd>' . (isset($atts['club_id']) ? $atts['club_id'] : 'Not set') . ' <em>(Short Code Attribute)</em></dd>
                        <dt>$club_id</dt><dd>' . $club_id . ' <em>(working value)</em></dd>
                        <dt>view</dt><dd>' . (isset($view) ? $view : 'Not set') . '</dd>
                        <dt>limit</dt><dd>' . (isset($callimit) ? $callimit : 'Not set') . '</dd>
                        <dt>sector</dt><dd>' . (isset($sector) ? $sector : 'Not set') . '</dd>
                        <dt>data_path</dt><dd>' . $data_path . '</dd>
                        <dt>Events URL</dt><dd><a href="' . $event_url . '" target="debug-tab">' . $event_url . '</a></dd>
                        <dt>Event Category ID List<br><em>($eventID_json)</em></dt><dd><a href="' . $eventID_json . '" target="debug-tab">' . $eventID_json . '</a></dd>
                    </dl>
                </pre>
            </div>';
    } 

    $calendar .= "<style>
                    .entry-content tr td {padding: 4px 4px !important;}        // override a style to reduce the cell padding
                    .fc-timegrid-event {
                        line-height: 1.1em;
                    }
                    </style>";
    $calendar .= "<div id='Calendar' style='width=90% max-width: 950px;'></div>";
    $calendar .= "<div id='colorKey'></div>";

    /* version 6.1.8 full calendar */
    $calendar .= "<script src='https://unpkg.com/popper.js/dist/umd/popper.min.js'></script> ";
    $calendar .= "<script src='https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js' ></script> ";
    $calendar .= "<script src='https://code.jquery.com/jquery-3.7.1.min.js' integrity='sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo='  crossorigin='anonymous'></script>";
    $calendar .= '<link rel="stylesheet" id="dacdb-tooltip" href="' . plugins_url('css/tooltip.css?ver=' . $GLOBALS['plugin_version'], __FILE__) . '" type="text/css" media="all" />';
    $calendar .= "<script type='text/javascript'>
        const isMobile = window.matchMedia('only screen and (max-width: 760px)').matches;
        jQuery(function($) {
            //document.addEventListener('DOMContentLoaded', function() {
            $.getJSON('".$eventID_json."', function( data ) {
                console.log ( data );
                showColorKey( data );
            });

            var calendarEl = document.getElementById('Calendar');
            var calendar = new FullCalendar.Calendar(calendarEl, {
                timeZone: 'UTC',
                eventTimeFormat: {
                    hour: '2-digit',
                    minute: '2-digit',
                    meridiem: 'narrow'
                },
                height: 'auto',
                handleWindowResize: true,
                slotMinTime: '06:00',
                slotMaxTime: '20:00',
                // stickyHeaderDates: false, // for disabling
                headerToolbar:
                {
                    left: 'prev,next today',
                    center: 'title',
                    right: '" .$views. "'
                },

                views: {
                    listDay: { buttonText: 'list day' },
                    listWeek: { buttonText: 'list week' }
                },

                initialView:     isMobile ? '".'listMonth'."' : '".$view. "',
                navLinks:         true,         // can click day/week names to navigate views
                businessHours:     true,         // display business hours
                editable:         false,
                selectable:     true,
                //nowIndicator:     true,
                dayMaxEvents:    false,
                eventDisplay:   'block',

                eventDidMount: function(info) {
                    var tooltip = new Tooltip(info.el, {
                        title: info.event.title,
                        placement: 'top',
                        trigger: 'hover',
                        container: 'body'
                    });
                }

                ,eventSources: [
                {
                    url: '".$data_path."R_GetEventsV2.cfm?r'+Math.random(),
                    method: 'GET',
                    extraParams:
                    {
                        AccountID:'"        .$options['dacdb_district']."',
                        ClubID:'"            .$club_id."',
                        EventCategoryIDs:'"    .$eids."',
                        Sector:'"            .$sector."'
                    }
                }
                ]

                ,eventClick: function(info) {     // open in new window on a phone
                    if ( !isMobile ) {
                        info.jsEvent.preventDefault();                    //prevent the browser from navigating to the click
                        $.colorbox({ width:'90%', height:'905', iframe:true, href:info.event.url });
                    }
                }
            });
            calendar.render();
        });
    
        function showColorKey(json) {
            var statusHTML = [];
            console.log (json.length);
                for (var i=0; i<json.length; i++)
                {
                    var p = json[i];
                    console.log (p);
                    var catDisplay = p.EVENTCATEGORY.trim();
                    console.log (catDisplay);
                    statusHTML.push('<div style=\"display:inline-block;margin-right:10px;\"><span class=\"dac-label\" style=\"background-color:'+p.BGCOLOR+';color:'+p.FGCOLOR+';font-weight:normal;border: 1px solid #3a87ad;\">'+catDisplay+'</span></div>');
                }
            console.log (statusHTML);
            if ( $('#colorKey').length ) {
                document.getElementById('colorKey').innerHTML = statusHTML.join('');
            }
        }
    </script>";
   return $calendar;
}  
//!SECTION Process Shortcode Functions

//ANCHOR - Global variables
/**
 * Sets the data and file paths based on the given conditions.
 *
 * @global bool   $fDebug         Flag indicating whether debug mode is enabled.
 * @global string $data_path      The data path URL.
 * @global string $file_path      The file path URL.
 * @global array  $options        An array of options.
 *
 * @return void
 */

//SECTION - JavaScript Functions
function setDataPath()
{
    global $fDebug, $data_path, $file_path, $options;

    // default to DACdb
    $data_path = 'https://www.IsMyRotaryClub.org/wp_api_1-2/';
    $file_path = 'https://www.dacdb.com/Accounts/';
    $image_path = 'https://www.dacdb.com/images/';                // future, was caded but fa had the icon needed

    if (isset($options['dacdb_system']) && ($options['dacdb_system'] == 'iMembersDB')) {
        $data_path   = 'https://www.emembersdb.com/wp_api_1-2/';
        $file_path   = 'https://www.imembersdb.com/Accounts/';
        $public_path = 'https://www.emembersdb.com/';
        $acct_label  = 'Account';
    }
    if (isset($options['dacdb_system']) && ($options['dacdb_system'] == 'DACdb')) {
        $data_path      = 'https://www.IsMyRotaryClub.org/wp_api_1-2/';
        $file_path      = 'https://www.dacdb.com/Accounts/';
        $public_path = 'https://www.IsMyRotaryClub.com/';
        $acct_label  = 'District';
    }
    $data_path = trim($data_path);
    if (isset($_GET['debug'])) {
        $fDebug = True;
    }
    return;
} // setDataPath

//ANCHOR - Javascript storyscript
/**
 * Generates a JavaScript script to handle the show/hide functionality for a specific element.
 *
 * This function checks if the jQuery script has been loaded and executed.
 * If the jQuery script is loaded, it generates a JavaScript script containing a function called "showdiv".
 * The "showdiv" function toggles the visibility of a specified element and updates the content of another element accordingly.
 *
 * @return void
 */

function storyscript()
{
    //if (wp_script_is('jquery', 'done')) {        // jquery is loaded and stories have been rendered
    ?>
        <script defer type="text/javascript">
            /**
             * Toggles the visibility of an element and updates the content of another element.
             *
             * @param {string} divid - The ID of the element to toggle.
             * @return {boolean} - Returns false to prevent default behavior.
             */
            function showdiv(divid) {
                console.log("showdiv=" + divid);
                $("#description-" + divid).toggle();
                console.log($("#more-" + divid).html());
                var t = $("#more-" + divid).html();
                if (t == 'Read More')
                    $("#more-" + divid).html("Less");
                else
                    $("#more-" + divid).html("Read More");
                return false;
            }
        </script>
    <?php
    //}
}

//ANCHOR - JavaScript Pagination
/**
 * Outputs a JavaScript code block that initializes the twbsPagination plugin for pagination.
 *
 * This function checks if the jQuery script is loaded and executed before outputting the JavaScript code.
 * The twbsPagination plugin creates a pagination element with specified total pages, visible pages, and other options.
 * When a page is clicked, the corresponding page content is shown and the current page content is hidden.
 *
 * @since 1.0.0
 */
function myscript()
{
    if (wp_script_is('jquery', 'done')) {
    ?>
        <script defer type="text/javascript">
            (function($) {
                $('#pagination-dacdb').twbsPagination({
                    totalPages: mypagenumber,
                    visiblePages: "7",
                    hideOnlyOnePage: true,
                    onPageClick: function(event, page) {
                        $('.page-content').hide();
                        $('#pagsec' + page).show();
                    }
                });
            })(jQuery);
        </script>
    <?php
    }
}
//!SECTION - JavaScript Functions

//ANCHOR - Plugin Registration Functions
if (class_exists('dacdb_plus')) {
    // Installation and uninstallation hooks
    register_activation_hook(__FILE__, array('dacdb_plus', 'activate'));
    register_deactivation_hook(__FILE__, array('dacdb_plus', 'deactivate'));
    // instantiate the plugin class
    $dacdb_plus = new dacdb_plus();
}

// DO WIDGETS
class dacdb_plus_widget extends WP_Widget
{
    function __construct()
    {
        parent::__construct(
            // Base ID of your widget
            'dacdb_plus_widget',
            // Widget name will appear in UI
            __('DACdb Plus', 'dacdb_plus_widget'),
            // Widget description
            array('description' => __('Allows you to display your DACdb Plus Wigets in your sidebars', 'dacdb_plus_widget'),)
        );
    }
    // Creating widget front-end
    // This is where the action happens
    public function widget($args, $instance)
    {
        global $fDebug, $data_path, $file_path, $options;

        $options = get_mmp_options();
        error_log(print_r($options, true)); // Check the PHP error log to see the output

        $title = apply_filters('widget_title', $instance['title']);

        $show = $instance['show'];
        $count = $instance['count'];
        $club_id = isset($instance['club_id']) && $instance['club_id'] !== '' ? $instance['club_id'] : $options['dacdb_club'];

        
        setDataPath();   // ShortCode DACdb or iMembersDB paths

        if ($data_path == '') {
            $pagedata .= "=================================================================<BR>";
            $pagedata .=  "Missing System selction under Plugin Settings!<BR>";
            $pagedata .=  "=================================================================<BR>";
            $pagedata .=  "<BR>";
        }

        // $subscription = file_get_contents($data_path.'wp_subscription.cfm?AccountId='.$options['dacdb_district'].'&ClubID='.$options['dacdb_club']);
        $xml = simplexml_load_file($data_path . 'wp_subscription2.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
        //  if ( $subscription != '1' )  {
        if ($xml->status != '1') {
            $pagedata .= "=================================================================<BR>";
            $pagedata .=  "&nbsp; &nbsp;  Missing subscription record. System=" . $options['dacdb_system'] . ", AccountID=" . $options['dacdb_district'] . ", ClubID=" . $options['dacdb_club'] . "<BR>";
            $pagedata .=  "&nbsp; &nbsp;  Please contact: support@memberminderpro.com<BR>";
            $pagedata .=  "subscription=" . $xml->status . "<br>";
            if ($fDebug) {
                $pagedata .=  "&nbsp; &nbsp;  url=" . $data_path . 'wp_subscription2.cfm?AccountId=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . "<BR>";
            }
            $pagedata .=  "=================================================================<BR>";
            $pagedata .=  "<BR>";
        }

        if ($fDebug) {
            $pagedata .=  "=================================================================<BR>";
            $pagedata .=  "Version=" . $plugin_version . "<br>";
            $pagedata .=  "Show=" . $show . "<br>";
            $pagedata .=  "CatID=" . $catid . "<br>";
            $pagedata .=  "System=" . $options['dacdb_system'] . "<BR>";
            $pagedata .=  "data_path=" . $data_path . "<BR>";
            $pagedata .=  "file_path=" . $file_path . "<BR>";
            $pagedata .=  "subscription=" . $xml->status . "<BR>";
            $pagedata .=  "=================================================================<BR>";
        }

        // before and after widget arguments are defined by themes
        echo $args['before_widget'];
        if (!empty($title))

            echo $args['before_title'] . $title . $args['after_title'];
        $show_stories = 0;
        $show_events = 0;
        $show_speakers = 0;
        $show_leaders = 0;
        $show_members = 0;
        $show_birthdays = 0;
        $show_club_meetings = 0;
        $show_newsletters = 0;
        $show_sponsors = 0;
        //            $subscription = file_get_contents($data_path.'wp_conf.cfm?AccountId='.$options['dacdb_district'].'&ClubID='.$options['dacdb_club']);
        //Handle Shortcode story show
        if ($show == 'stories') {
            $show_stories = 1;
        } elseif ($show == 2) {
            $show_events = 1;
        } elseif ($show == 3) {
            $show_d_events = 1;
        } elseif ($show == 7) {
            $show_speakers = 1;
        } elseif ($show == 5) {
            $show_leaders = 1;
        } elseif ($show == 4) {
            $show_birthdays = 1;
        } elseif ($show == 1) {
            $show_meeting_info = 1;
        } elseif ($show == 6) {
            $show_newsletters = 1;
        } elseif ($show == 8) {
            $show_sponsors = 1;
        }

        if (isset($show_meeting_info) && $show_meeting_info == 1) {
            if (!$club_id) {
                $club_id = $options['dacdb_club'];
            }

            if ($fDebug) {
                $meetings = "";
                $meetings .= "=======================<BR>";
                $meetings .= "function widget show_meeting_info<br>";
                $meetings .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $meetings .= "ClubID=" . $options['dacdb_club'] . "<br>";
                // $meetings .= "sort=".$sort."<br>";
                $meetings .= "URL=" . $data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&SortBy=' . $sort . '<br>';
                $meetings .= "=======================<BR>";
                echo $meetings;
            }
            $xml = simplexml_load_file($data_path . 'wp_club_meetings.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&R=' . rand());
            $meetings = array();
            $counter = 1;
            foreach ($xml->meeting as $wcm) {
                echo '<div class="side-meeting-info">';
                echo '<span class="side-meeting-info-dt">' . $wcm->meetingday . 's at ' . $wcm->meetingtime . '</span><br/>';
                echo '<strong>' . $wcm->meetingplace . '</strong><br>';
                echo $wcm->meetingaddress . '<br>';
                echo $wcm->meetingcity . ', ' . $wcm->meetingstatecode . ' ' . $wcm->meetingpostalcode . '<br/>';
                if ($wcm->latlng != "") {
                    echo '<span style="float:right;"><a href="' . $wcm->latlng . '" target="new">Map It</a></span>';
                }
                echo '<br></div>';
                $counter = $counter + 1;
            }
            $meet_total = count($xml->meeting);
            if ($meet_total == 0) {
                echo 'There are no club meetings to display at this time.';
            }
        }

        if (isset($show_events) && $show_events == 1) {
            if (!$club_id) {
                $club_id = $options['dacdb_club'];
            } else {
                $byShowSpeaker = 1;
            }

            if ($club_id == 0) {
                $categoryids = $options['district_events_types_page'];
                $mo = $options['district_events_months_side'];
            } else {
                $categoryids = $options['club_events_types_page'];
                $mo = $options['club_events_months_side'];
            }

            if ($fDebug) {
                $events = "";
                $events .= "=======================<BR>";
                $events .= "function widget show_events<br>";
                $events .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $events .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $events .= "Mo=" . $options['club_events_months'] . "<br>";
                $events .= "categoryids=" . $categoryids . "<br>";
                $events .= $data_path . 'wp_event.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&CatIDs=' . $categoryids . '&Mo=' . $mo . '<br />';
                $events .= "=======================<BR>";
                echo $events;
            }

            $xml = simplexml_load_file($data_path . 'wp_event.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&CatIDS=' . $categoryids . '&Mo=' . $mo . '&R=' . rand());
            //                if ( $options['club_events_types_side'] == '') {
            //                    $xml = simplexml_load_file($data_path.'wp_event.cfm?AccountID='.$options['dacdb_district'].'&ClubID='.$club_id.'&Cat=3,5,4&Mo='.$options['club_events_months_side'].'&R='.rand());
            //                } else {
            //                    $xml = simplexml_load_file($data_path.'wp_event.cfm?AccountID='.$options['dacdb_district'].'&ClubID='.$club_id.'&Cat='.$options['club_events_types_side'].'&Mo='.$options['club_events_months_side'].'&R='.rand());
            //                }
            $events = array();
            $counter = 1;
            $showEvent = 1;

            $event_total = count($xml->event);
            foreach ($xml->event as $event) {
                if ($options['club_events_show_speakers_side'] == 0 && $event->speaker != '') {
                    $showEvent = 0;
                } else if ($options['club_events_show_speakers_side'] == 0 && $event->speaker == '') {
                    $showEvent = 1;
                }

                if ($byShowSpeaker = 1 && $event->speaker == '') {
                    $showEvent = 1;
                }

                if ($showEvent == 1) {
                    if ($count >= $counter) {
                        echo '<div class="side-club-event" style="line-height:1.5;">';
                        if ($options['events_global_date'] == 1) {
                            if (date("Y-m-d", strtotime($event->startdate)) == date("Y-m-d", strtotime($event->enddate))) {
                                echo date("F jS Y", strtotime($event->startdate)) . ' ' . date("g:i a", strtotime($event->startdate));
                            } else {
                                echo date("M jS", strtotime($event->startdate)) . ' - ' . date("M jS Y", strtotime($event->enddate)) . ' ' . date("g:i a", strtotime($event->startdate));
                            }
                            echo '<br>';
                        }

                        echo '<strong>' . $event->eventname . '</strong>';

                        if ($options['club_events_show_speakers_side_info'] == 1) {
                            if ($event->speaker != "") {
                                echo '<br><strong>Speaker: ' . $event->speaker . '</strong>';
                            }
                            if ($event->topic != "") {
                                echo '<br>Topic: ' . $event->topic;
                            }
                        }

                        if ($options['events_global_date'] == 0) {
                            echo '<br>';
                            if (date("Y-m-d", strtotime($event->startdate)) == date("Y-m-d", strtotime($event->enddate))) {
                                echo date("F jS Y", strtotime($event->startdate)) . ' ' . date("g:i a", strtotime($event->startdate));
                            } else {
                                echo date("M jS", strtotime($event->startdate)) . ' - ' . date("M jS Y", strtotime($event->enddate)) . ' ' . date("g:i a", strtotime($event->startdate));
                            }
                        }

                        echo '<br>';
                        echo '<a class="iframe2 cboxElement" href="' . $data_path . 'R_Event.cfm?EventID=' . $event->eventid . '" style="float:right;">More info</a>';
                        echo '<br>';
                        if ($count > $counter && $counter < $event_total) {
                            echo '<hr>';
                        }
                        $counter = $counter + 1;
                        echo '</div>';
                    }
                }
            }
            if ($event_total == 0) {
                echo 'There are no events at this time.';
            }
        }
        if (isset($show_d_events) && $show_d_events == 1) {

            if ($club_id == 0) {
                $categoryids = $options['district_events_types_page'];
                $mo = $options['district_events_months_side'];
            } else {
                $categoryids = $options['club_events_types_page'];
                $mo = $options['club_events_months_side'];
            }

            if ($fDebug) {
                $events = "";
                $events .= "=======================<BR>";
                $events .= "function widget show_d_events<br>";
                $events .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $events .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $events .= "Mo=" . $options['district_events_months'] . "<br>";
                $events .= "categoryids=" . $categoryids . "<br>";
                $events .= $data_path . 'wp_event.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&CatIDs=' . $categoryids . '&Mo=' . $mo . '<br />';
                $events .= "=======================<BR>";
                echo $events;
            }

            $xml = simplexml_load_file($data_path . 'wp_event.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&CatIDs=' . $categoryids . '&Mo=' . $mo . '&R=' . rand());
            //                if ( $options['district_events_types_side'] == '') {
            //                    $xml = simplexml_load_file($data_path.'wp_event.cfm?AccountID='.$options['dacdb_district'].'&ClubID='.$options['dacdb_club'].'&CatIDS,2,123&Mo='.$options['district_events_months_side'].'&R='.rand());
            //                } else {
            //                    $xml = simplexml_load_file($data_path.'wp_event.cfm?AccountID='.$options['dacdb_district'].'&ClubID='.$options['dacdb_club'].'&CatIDs='.$options['district_events_types_side'].'&Mo='.$options['district_events_months_side'].'&R='.rand());
            //                }
            $events = array();
            $counter = 1;
            $event_total = count($xml->event);
            foreach ($xml->event as $event) {
                if ($count >= $counter) {
                    echo '<div class="side-district-event" style="line-height:1.5;">';


                    if ($options['events_global_date'] == 1) {
                        if (date("Y-m-d", strtotime($event->startdate)) == date("Y-m-d", strtotime($event->enddate))) {
                            echo date("F jS Y", strtotime($event->startdate)) . ' ' . date("g:i a", strtotime($event->startdate));
                        } else {
                            echo date("M jS", strtotime($event->startdate)) . ' - ' . date("M jS Y", strtotime($event->enddate)) . ' ' . date("g:i a", strtotime($event->startdate));
                        }
                        echo '<br>';
                    }

                    echo '<strong>' . $event->eventname . '</strong>';

                    if ($options['events_global_date'] == 0) {
                        echo '<br>';
                        if (date("Y-m-d", strtotime($event->startdate)) == date("Y-m-d", strtotime($event->enddate))) {
                            echo date("F jS Y", strtotime($event->startdate));
                        } else {
                            echo date("M jS", strtotime($event->startdate)) . ' - ' . date("M jS Y", strtotime($event->enddate));
                        }
                    }
                    echo '<br>';
                    echo '<a class="iframe2 cboxElement" href="' . $data_path . 'R_Event.cfm?EventID=' . $event->eventid . '" style="float:right;">More info</a>';
                    echo '<br>';
                    if ($count > $counter && $counter < $event_total) {
                        echo '<hr>';
                    }
                    echo '</div>';
                }
                $counter = $counter + 1;
            }
            if ($event_total == 0) {
                echo 'There are no events at this time.';
            }
        }

        if ($show_birthdays == 1) {

            if ($fDebug) {
                $events = "";
                $events .= "=======================<BR>";
                $events .= "function widget show_birthdays<br>";
                $events .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $events .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $events .= $data_path . 'wp_birthdays.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '<br />';
                $events .= "=======================<BR>";
                echo $events;
            }

            $xml = simplexml_load_file($data_path . 'wp_birthdays.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
            $birthdays = array();
            $birthday_total = count($xml->birthday);
            $counter = 1;
            echo '<div class="side-birthdays">';
            foreach ($xml->birthday as $birthday) {
                echo '<div style=""><strong>' . $birthday->membername . '</strong><br>' . $birthday->birthday . '<br><br></div>';
                if ($counter < $birthday_total) {
                    echo '<hr>';
                }
                $counter = $counter + 1;
            }
            if ($birthday_total == 0) {
                echo 'There are no upcoming birthdays at this time.';
            }
            echo '</div>';
        }
        if ($show_leaders == 1) {

            if ($fDebug) {
                $events = "";
                $events .= "=======================<BR>";
                $events .= "function widget show_leaders<br>";
                $events .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $events .= $data_path . 'wp_leaders.cfm?AccountID=' . $options['dacdb_district'] . '<br />';
                $events .= "=======================<BR>";
                echo $events;
            }

            if (!$club_id) {
                $club_id = $options['dacdb_club'];
            }

            echo '<div class="side-leaders">';
            if ($options['dacdb_club'] == 0) {
                $xml = simplexml_load_file($data_path . 'wp_leaders.cfm?AccountID=' . $options['dacdb_district'] . '&R=' . rand());
                $leaders = array();
                $counter = 1;
                $leader_total = count($xml->leader);
                foreach ($xml->leader as $leader) {
                    echo '<div class="row col-1-1" style="overflow:hidden;margin-bottom:20px;">';
                    echo '<div style="width:60px;float:left;"><img src="' . $leader->imgpath . '' . $leader->image . '" width="50"></div>';
                    echo '<div style=""><strong><a class="iframe cboxElement" href="' . $data_path . 'R_Emailer.cfm?UserID=' . $leader->userid . '">' . $leader->username . '</a></strong><br>' . $leader->clubposition . '</div>';
                    echo '</div>';
                }
                if ($leader_total == 0) {
                    echo 'There are no leaders to display at this time.';
                }
            } else {
                $xml = simplexml_load_file($data_path . 'wp_leaders.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&R=' . rand());
                $leaders = array();
                $counter = 1;
                $leader_total = count($xml->leader);
                foreach ($xml->leader as $leader) {
                    echo '<div class="row col-1-1" style="overflow:hidden;margin-bottom:20px;">';
                    echo '<div style="width:60px;float:left;"><img src="' . $leader->imgpath . '' . $leader->image . '" width="50"></div>';
                    echo '<div style=""><strong><a class="iframe cboxElement" href="' . $data_path . 'R_Emailer.cfm?UserID=' . $leader->userid . '">' . $leader->username . '</a></strong><br>' . $leader->clubposition . '</div>';
                    echo '</div>';
                }
                if ($leader_total == 0) {
                    echo 'There are no leaders to display at this time.';
                }
            }
            echo '</div>';
        }
        if ($show_newsletters == 1) {

            $count = $options['newsletters_weeks_widget'];

            if ($fDebug) {
                $newsletters = "";
                $newsletters .= "=======================<BR>";
                $newsletters .= "function widget show_newsletters<br>";
                $newsletters .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $newsletters .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $newsletters .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $newsletters .= $data_path . 'wp_newsletters.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&Weeks=' . $options['newsletters_weeks_widget'] . '<br />';
                $newsletters .= "=======================<BR>";
                echo $newsletters;
            }

            $xml = simplexml_load_file($data_path . 'wp_newsletters.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&Weeks=' . $options['newsletters_weeks_widget'] . '&R=' . rand());

            $newsletters = array();
            $counter = 1;
            $newsletter_total = count($xml->newsletter);
            echo '<div class="side-newsletters">';
            foreach ($xml->newsletter as $newsletter) {
                if ($counter <= $count) {
                    echo '<span class="side-newsletters-link"><a href="' . $newsletter->path . '" target="new">' . $newsletter->name . '</a> </span>';
                    echo '<span class="pull-right" style="float:right;">' . $newsletter->datelastmodified . '</span>';
                    echo '<hr>';
                }
                $counter = $counter + 1;
            }
            if ($newsletter_total == 0) {
                echo 'There are no newsletters to display at this time.';
            }
            echo '</div>';
        }

        if ($show_speakers == 1) {

            if ($fDebug) {
                $speakers = "";
                $speakers .= "=======================<BR>";
                $speakers .= "function widget show_speakers<br>";
                $speakers .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $speakers .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $speakers .= "CatIDs=" . $options['speaker_cats'] . "<br>";
                $speakers .= $data_path . 'wp_speakers.cfm?AccountID=' . $options['dacdb_district'] . '&Mo=' . $options['speakers_months'] . '&CatIDs=' . $options['speaker_cats'] . '&ClubID=' . $options['dacdb_club'] . '<br/>';
                $speakers .= "=======================<BR>";
                echo $events;
            }

            $xml = simplexml_load_file($data_path . 'wp_speakers.cfm?AccountID=' . $options['dacdb_district'] . '&Mo=' . $options['speakers_months'] . '&CatIDs=' . $options['speaker_cats'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
            $speakers = array();
            $speaker_counter = 1;
            foreach ($xml->speakerinfo as $speakerinfo) {
                if ($count >= $speaker_counter) {
                    echo '<div class="side-speakers" style="line-height:1.5;">';

                    if ($options['events_global_date'] == 1) {
                        echo '' . date("M jS Y", strtotime($speakerinfo->eventdate)) . ' ' . date("g:i a", strtotime($speakerinfo->eventdate));
                        echo '<br>';
                    }
                    if ($speakerinfo->speaker != '')
                        echo '<strong>' . $speakerinfo->speaker . '</strong><br />';
                    if ($speakerinfo->topic != '')
                        echo $speakerinfo->topic . '<br/>';


                    if ($options['events_global_date'] == 0) {
                        echo '' . date("M jS Y", strtotime($speakerinfo->eventdate)) . ' ' . date("g:i a", strtotime($speakerinfo->eventdate)) . '<br />';
                    }
                    echo '<a class="iframe cboxElement" href="' . $data_path . 'R_Event.cfm?EventID=' . $speakerinfo->eventid . '" style="float:right;">More info</a><br />';
                    if ($count > $speaker_counter) {
                        echo '<hr>';
                    }
                    $speaker_counter = $speaker_counter + 1;
                    echo '</div>';
                }
            }
            $speakerinfo_total = count($xml->speakerinfo);
            if ($speakerinfo_total == 0) {
                echo '<div class="side-speakers">';
                echo 'There are no speakers at this time.';
                echo '</div">';
            }
        }

        if ($show_sponsors == 1) {

            if ($fDebug) {
                $sponsors = "";
                $sponsors .= "=======================<BR>";
                $sponsors .= "function widget show_sponsors<br>";
                $sponsors .= "AccountID=" . $options['dacdb_district'] . "<br>";
                $sponsors .= "ClubID=" . $options['dacdb_club'] . "<br>";
                $sponsors .= $data_path . 'wp_sponsor.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '<br />';
                $sponsors .= "=======================<BR>";
                echo $sponsors;
            }

            $xml = simplexml_load_file($data_path . 'wp_sponsor.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&R=' . rand());
            $sponsors = array();
            $counter = 1;
            foreach ($xml->sponsor as $sponsor) {
                echo '<div><center>';
                echo '<a href="' . $sponsor->website . '" target="_blank"><img src="' . $sponsor->imagepath . '' . $sponsor->image . '"></a><br><br>';
                echo '</center></div>';
                $counter = $counter + 1;
            }
            //echo '<small>Click on browser refresh tab to see more sponsors</small>';
            $sponsor_total = count($xml->sponsor);
            if ($sponsor_total == 0) {
                echo '<div class="side-sponsors">';
                echo 'There are no sponsors to display at this time.';
                echo '</div>';
            }
        }
        echo $args['after_widget'];
    }

    // Widget Backend
    public function form($instance)
    {
        $options = get_mmp_options();
        if (isset($instance['title'])) {
            $title = $instance['title'];
            $show = $instance['show'];
            $club_id = $instance['club_id'];
            $count = $instance['count'];
        } else {
            $title = __('', 'dacdb_plus_widget');
        }
    ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>">
            <label for="<?php echo $this->get_field_id('club_id'); ?>"><?php _e('^Club ID:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('club_id'); ?>" name="<?php echo $this->get_field_name('club_id'); ?>" value="<?php echo esc_attr($club_id); ?>">
            <label for="<?php echo $this->get_field_id('show'); ?>"><?php _e('Show:'); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id('show'); ?>" name="<?php echo $this->get_field_name('show'); ?>">
                <option value="<?php echo $show; ?>">
                    <?php if ($show == '1') {
                        echo 'Meeting Info';
                    } elseif ($show == '2') {
                        echo 'Events';
                    } elseif ($show == '3') {
                        echo 'District Events';
                    } elseif ($show == '4') {
                        echo 'Birthdays';
                    } elseif ($show == '5') {
                        echo 'Leadership';
                    } elseif ($show == '6') {
                        echo 'Newsletters';
                    } elseif ($show == '7') {
                        echo 'Speakers';
                    } elseif ($show == '8') {
                        echo 'Sponsors';
                    } else {
                        echo 'Select One';
                    } ?></option>
                <?php if ($options['dacdb_club'] == 0) { ?>
                    <option value="3">*District Events</option>
                    <option value="6">*Newsletters</option>
                    <option value="7">*Speakers</option>
                    <option value="8">Sponsors</option>
                <?php } else { ?>
                    <option value="1">^ Meeting Info</option>
                    <option value="5">^ Leadership</option>
                    <option value="4">Birthdays</option>
                    <option value="8">^ Sponsors</option>
                    <option value="2">*^ Events</option>
                    <option value="3">*District Events</option>
                    <option value="6">*Newsletters</option>
                    <option value="7">*Speakers</option>
                <?php } ?>
            </select>
            <label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('*Number of items to display:'); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>">
                <option></option>
                <option value="1" <?php if ($count == '1') {
                                        echo 'selected';
                                    } ?>>1</option>
                <option value="2" <?php if ($count == '2') {
                                        echo 'selected';
                                    } ?>>2</option>
                <option value="3" <?php if ($count == '3') {
                                        echo 'selected';
                                    } ?>>3</option>
                <option value="4" <?php if ($count == '4') {
                                        echo 'selected';
                                    } ?>>4</option>
                <option value="5" <?php if ($count == '5') {
                                        echo 'selected';
                                    } ?>>5</option>
                <option value="6" <?php if ($count == '6') {
                                        echo 'selected';
                                    } ?>>6</option>
                <option value="7" <?php if ($count == '7') {
                                        echo 'selected';
                                    } ?>>7</option>
                <option value="8" <?php if ($count == '8') {
                                        echo 'selected';
                                    } ?>>8</option>
                <option value="9" <?php if ($count == '9') {
                                        echo 'selected';
                                    } ?>>9</option>
                <option value="10" <?php if ($count == '10') {
                                        echo 'selected';
                                    } ?>>10</option>
                <option value="11" <?php if ($count == '11') {
                                        echo 'selected';
                                    } ?>>11</option>
                <option value="12" <?php if ($count == '12') {
                                        echo 'selected';
                                    } ?>>12</option>
                <option value="13" <?php if ($count == '13') {
                                        echo 'selected';
                                    } ?>>13</option>
                <option value="14" <?php if ($count == '14') {
                                        echo 'selected';
                                    } ?>>14</option>
                <option value="15" <?php if ($count == '15') {
                                        echo 'selected';
                                    } ?>>15</option>
                <option value="16" <?php if ($count == '16') {
                                        echo 'selected';
                                    } ?>>16</option>
                <option value="17" <?php if ($count == '17') {
                                        echo 'selected';
                                    } ?>>17</option>
                <option value="18" <?php if ($count == '18') {
                                        echo 'selected';
                                    } ?>>18</option>
                <option value="19" <?php if ($count == '19') {
                                        echo 'selected';
                                    } ?>>19</option>
                <option value="20" <?php if ($count == '20') {
                                        echo 'selected';
                                    } ?>>20</option>
            </select>
        </p>
<?php
    }
    // Updating widget replacing old instances with new
    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['show'] = (!empty($new_instance['show'])) ? strip_tags($new_instance['show']) : '';
        $instance['count'] = (!empty($new_instance['count'])) ? strip_tags($new_instance['count']) : '';
        $instance['club_id'] = (!empty($new_instance['club_id'])) ? strip_tags($new_instance['club_id']) : '';
        return $instance;
    }
}


//SECTION - Display Functions

function dacdb_SMIcons($share, $smstyle, $smOpt, $StoryID, $title)
{
    global $fDebug, $data_path, $file_path, $public_path, $options;

    $url = $public_path . 'sms.cfm?StoryID='. $StoryID;

    $icons = '';
    switch ($smstyle) {
        case '1':           // 1-dropdown
        case 'dropdown':    // 1-dropdown
                $icons .= '<div class="mmp-share dropdown" style="width: 80px;">';
                $icons .= '    <button class="dropbtn">Share <i class="fa-regular fa-circle-caret-down"></i></button>';
                $icons .= '    <div class="dropdown-content">';
                    if ( strpos ($smOpt,'FB') >= 0) {
                        $icons .= '<a href="https://www.facebook.com/sharer/sharer.php?u='.$url.'&amp;display=popup&amp;t='.$title.'&amp;" target="_blank" class="fa-brands fa-facebook facebook linear" style=" font-size: 10px !important;"> Facebook</a>';
                    }
                    if ( strpos ($smOpt,'TW') >= 0) {
                        $icons .= '<a href="https://twitter.com/intent/tweet?text='.$url.'&amp;text='.$title.'" target="_blank" class="fa-brands fa-twitter twitter linear" style=" font-size: 10px !important;"> Twitter</a>';
                    }
                    if ( strpos ($smOpt,'LI') >= 0) {
                        $icons .= '<a href="https://www.linkedin.com/shareArticle?mini=true&amp;url='.$url.'&amp;title='.$title.'" target="_blank" class="fa-brands fa-linkedin linkedin linear" style=" font-size: 10px !important;"> Linkedin</a>';
                    }
                    if ( strpos ($smOpt,'TU') >= 0) {
                        $icons .= '<a href="https://www.tumblr.com/share?v=3&amp;u='.$url.'&amp;t='.$title.'" target="_blank" class="fa-brands fa-tumblr tumblr linear" style=" font-size: 10px !important;"> Tumblr</a>';
                    }
                    if ( strpos ($smOpt,'RE') >= 0) {
                        $icons .= '<a href="http://www.reddit.com/submit?url='.$url.'&amp;title='.$title.'" target="_blank" class="fa-brands fa-reddit reddit linear" style=" font-size: 10px !important;"> Reddit</a>';
                    }
                    if ( strpos ($smOpt,'PT') >= 0) {
                        $icons .= '<a href="https://www.Pinterest.com/?url='.$url.'" target="_blank" class="fa-brands fa-pinterest pinterest linear" style=" font-size: 10px !important;"> Pinterest</a>';
                    }
                    if ( strpos ($smOpt,'PF') >= 0) {
                        $icons .= '<a href="http://www.printfriendly.com/print?url='.$url.'&amp;title='.$title.'"  target="_blank" class="fa-regular fa-print print linear" style=" font-size: 10px !important;"> PrintFriendly</a>';
                    }
                    if ( strpos ($smOpt,'EN') >= 0) {
                        $icons .= '<a href="https://www.evernote.com/clip.action?url='.$url.'&amp;title='.$title.'" class="fa-brands fa-evernote evernote linear" style="font-size: 10px !important;"> EverNote</a>';
                    }
                    if ( strpos ($smOpt,'GO') >= 0) {
                        $icons .= '<a href="https://plus.google.com/share?url='.$url.'&amp;title='.$title.'" target="_blank" class="fa-brands fa-google google linear" alt="Google" title="Google" style=" font-size: 10px !important;"> Google</a>';
                    }
                        $icons .= '</div>';
                    $icons .= '</div>';
                break;
        case '2':           // 2-ICONS
        case 'icons':       // 2-ICONS
            if ( strpos ($smOpt,'FB') >= 0) {
                $icons .= '<a  href="https://www.facebook.com/sharer/sharer.php?u='.$url.'&amp;display=popup&amp;t='.$title.'" rel="nofollow" target="_blank" alt="FaceBook" title="FaceBook"><span style="color: #3B5998 !important"><i class="fa-brands fa-facebook fa-2x"></i></span></a>&nbsp;';
            }
            if ( strpos ($smOpt,'TW') >= 0) {
                $icons .= '<a  href="https://twitter.com/intent/tweet?text='.$url.'&amp;text='.$title.'"  alt="Twitter" target="_blank"  title="Twitter" ><span style="color: #55ACEE !important"><i class="fa-brands fa-x-twitter fa-2x"></i></span></a>&nbsp;';
            }
            if ( strpos ($smOpt,'LI') >= 0) {
                $icons .= '<a  href="https://www.linkedin.com/shareArticle?mini=true&amp;url='.$url.'&amp;title='.$title.'"  target="_blank"   alt="LinkedIn" title="LinkedIn"><span style="color: #007bb5 !important"><i class="fa-brands fa-linkedin fa-2x"></i></span></a>&nbsp;';
            }
            if ( strpos ($smOpt,'TU') >= 0) {
                $icons .= '<a  href="https://www.tumblr.com/share?v=3&amp;u='.$url.'&amp;t='.$title.'"   alt="tumblr" target="_blank"  title="Tumnlr"><span style="color: #2c4762 !important"><i class="fa-brands fa-tumblr fa-2x"></i></span></a>&nbsp;';
            }
            if ( strpos ($smOpt,'RE') >= 0) {
                $icons .= '<a  href="http://www.reddit.com/submit?url='.$url.'&amp;title='.$title.'"   alt="Reddit"  target="_blank" title="Reddit"><span style="color: #ff5700 !important"><i class="fa-brands fa-reddit fa-2x"></i></a>&nbsp;';
            }
            if ( strpos ($smOpt,'PT') >= 0) {
                $icons .= '<a href="https://www.Pinterest.com/?url='.$url.'"   alt="Pinterest" title="Pinterest"  target="_blank" alt="ReddPinterestit" title="Pinterest"><span style="color: #cb2027 !important"><i class="fa-brands fa-pinterest fa-2x"></i></a>&nbsp;';
            }
            if ( strpos ($smOpt,'PF') >= 0) {
                $icons .= '<a href="http://www.printfriendly.com/print?url='.$url.'&amp;title='.$title.'"   alt="PrintFriendly"  target="_blank" title="PrintFriendly"><span style="color: #75AA33 !important"><i class="fa-regular fa-print fa-2x"></i></a>&nbsp;';
            }
            if ( strpos ($smOpt,'EN') >= 0) {
                $icons .= '<a  href="https://www.evernote.com/clip.action?url='.$url.'&amp;title='.$title.'" alt="EverNote"  target="_blank" title="EverNote"> <span style="color: #FC4242 !important"><i class="fa-brands fa-evernote fa-2x"></i></a>&nbsp;';
            }
            if ( strpos ($smOpt,'GO') >= 0) {
                $icons .= '<a  href="https://plus.google.com/share?url='.$url.'&amp;title='.$title.'" alt="Google"  target="_blank" title="Google" <span style="color: #dd4b39 !important"><i class="fa-brands fa-google fa-2x"></i></span></a>';
            }
            break;
        case '3':            // 3-Linear
        case 'linear':        // 3-Linear
                    if ( strpos ($smOpt,'FB') >= 0) {
                        $icons .= '<a href="https://www.facebook.com/sharer/sharer.php?u='.$url.'&amp;display=popup&amp;t='.$title.'" target="_blank"  alt="FaceBook" title="FaceBook" class="fa-brands fa-facebook facebook linear"></a>';
                    }
                    if ( strpos ($smOpt,'TW') >= 0) {
                        $icons .= '<a href="https://twitter.com/intent/tweet?text='.$url.'&amp;text='.$title.'" target="_blank"  alt="Twitter" title="Twitter" class="fa-brands fa-twitter twitter linear"></a>';
                    }
                    if ( strpos ($smOpt,'LI') >= 0) {
                        $icons .= '<a href="https://www.linkedin.com/shareArticle?mini=true&amp;url='.$url.'&amp;title='.$title.'" alt="LinkedIn" target="_blank"  title="LinkedIn" class="fa-brands fa-linkedin linkedin linear"></a>';
                    }
                    if ( strpos ($smOpt,'TU') >= 0) {
                        $icons .= '<a href="https://www.tumblr.com/share?v=3&amp;u='.$url.'&amp;t='.$title.'" alt="tumblr" title="Tumnlr" target="_blank"  class="fa-brands fa-tumblr tumblr linear"></a>';
                    }
                    if ( strpos ($smOpt,'RE') >= 0) {
                        $icons .= '<a href="http://www.reddit.com/submit?url='.$url.'&amp;title='.$title.'" alt="Reddit"  target="_blank" title="Reddit"class="fa-brands fa-reddit reddit linear"></a>';
                    }
                    if ( strpos ($smOpt,'PT') >= 0) {
                        $icons .= '<a href="https://www.Pinterest.com/?url='.$url.'" alt="ReddPinterestit" target="_blank"  title="Pinterest" class="fa-brands fa-pinterest pinterest linear"></a>';
                    }
                    if ( strpos ($smOpt,'PF') >= 0) {
                        $icons .= '<a href="http://www.printfriendly.com/print?url='.$url.'&amp;title='.$title.'" alt="PrintFriendly" target="_blank"  title="PrintFriendly" class="fa-regular fa-print print linear"></a>';
                    }
                    if ( strpos ($smOpt,'EN') >= 0) {
                        $icons .= '<a href="https://www.evernote.com/clip.action?url='.$url.'&amp;title='.$title.'" alt="EverNote" target="_blank" title="EverNote" class="fa-brands fa-evernote evernote linear"></a>';
                    }
                    if ( strpos ($smOpt,'GO') >= 0) {
                        $icons .= '<a href="https://plus.google.com/share?url='.$url.'&amp;title='.$title.'" alt="EveGooglerNote" target="_blank" title="Google" class="fa-brands fa-google google linear"></a>';
                    }
                    break;
        }
        return $icons;
}


//ANCHOR - Display Members
/**
 * Display member data in various styles
 *
 * @param SimpleXMLElement $xml    The XML data containing member information
 * @param int $style               The style to display the members, valid options are 0, 1, 3
 * @param array $atts              An associative array with keys 'cols' and 'pics' indicating the number of columns to display and whether to display pictures respectively
 *
 * @global bool $fDebug            A flag to indicate whether debug mode is on
 * @global string $data_path       A path used for data operations
 * @global string $file_path       A file path used for file operations
 * @global array $options          An array of options affecting the behavior and output of the function
 *
 * @return string                  An HTML string displaying member data
 */
function dacdb_DisplayMembers($xml, $style, $atts)
{
    global $fDebug, $data_path, $file_path, $options;

    // Initialize some variables
    $ldiv = "";
    $members = "";
    $cols = "1";
    $pics = "1";

    // Set defaults for 'cols' and 'pics' if not set
    if ($atts['cols'] == '')
        $atts['cols']  = 1;

    if ($atts['pics'] == '')
        $atts['pics']  = 1;

    // Add debug info if debug mode is enabled
    if ($fDebug) {
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_DisplayMembers called<br>";
        $members .= "cols=" . $atts['cols'] . "<br>";
        $members .= "pics=" . $atts['pics'] . "<br>";
        $members .= "=================================================================<BR>";
    }

    // Display members based on the provided style
    switch ($style) {

        case '0':   // Test Mode
            foreach ($xml->club as $member) {
                echo $member->clubname . "<br/>";
                echo count($member->officers->officer) . "<br>";
                foreach ($member->officers->officer as $officer) {
                    echo $officer->username . "<br/>";
                }
            }
            break;

        case '1':    // d_leaders, leaders
            $members .= '<div class="dac-row">';
            foreach ($xml->dlc as $member) {
                // Additional code with further complexity omitted for brevity
                // You would continue to add explanatory comments here as necessary
            }
            $members .= '</div>'; //<!-- dac-row  -->
            return $members;
            break;

        case '3':   // Kees Flag Display
            $cnt = 0;
            $records = count($xml->leader);
            // Additional code with further complexity omitted for brevity
            // You would continue to add explanatory comments here as necessary
            return $members;
            break;

        default:
            $members .= "=================================================================<BR>";
            $members .= "&nbsp;&nbsp;&nbsp;Invalid style selected [" . $style . "]<BR>";
            $members .= "=================================================================<BR>";
            break;
    }
    return $members;
}


//ANCHOR - Display Club
/**
 * Displays club information based on the provided XML data.
 *
 * @param SimpleXMLElement $xml   The XML data containing club information.
 * @param int|string       $style The style of display to use (0, 1, 3).
 * @param array            $atts  Additional attributes for customization.
 *
 * @return string The generated HTML for displaying club information.
 */
function dacdb_DisplayClub($xml, $style, $atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $ldiv = "";
    $members = "";
    $counter = 1;

    // Set default values for optional attributes
    $cols = isset($atts['leaders_per_row']) ? $atts['leaders_per_row'] : 1;
    $leader_pics = isset($atts['leader_pics']) ? $atts['leader_pics'] : 1;
    $leaders_per_row = isset($atts['leaders_per_row']) ? $atts['leaders_per_row'] : 1;
    $flex = isset($atts['leader_pics']) ? $atts['leader_pics'] : 1;
    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && isset($atts['imgwidth']) > 0 ? $atts['imgwidth'] : 150);
            
    if ($fDebug) {
        // Debug information
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_DisplayClubs called 2<br>";
        $members .= "cols=" . $leaders_per_row . "<br>";
        $members .= "leader_pics=" . $leader_pics . "<br>";
        $members .= "flex=" . $flex . "<br>";
        $members .= "style=" . $style . "<br>";
        $members .= "cols=" . $cols . "<br>";
        $members .= "imgWidth=" . $thumbnail_width . "<br>";
        $members .= "Thumbnail Width =" . $options['thumbnail_width'] . "<br>";
        $members .= "=================================================================<BR>";
    }

    switch ($style) {

        case '0':   // Test Mode
            foreach ($xml->club as $club) {
                // Display club and officer information
                echo $club->clubname . "<br/>";
                echo count($club->officers->officer) . "<br>";
                foreach ($club->officers->officer as $officer) {
                    echo $officer->username . "<br/>";
                }
            }
            break;

        case '1': //  dacdb_leaders display Aligned Columns
            $setDivWidth = 160;
            $setImgWidth = 150;

            $div  = '<div class="col">';
            if ($cols == 1) {
                $div = '<div class="members dac-col-xs-12">';
                $setDivWidth = 155;
                $setImgWidth = 150;
            } else if ($cols == 2) {
                $div = '<div class="members dac-col-xs-12 dac-col-sm-6">';
                $setDivWidth = 140;
                $setImgWidth = 135;
            } else if ($cols == 3) {
                $div = '<div class="members dac-col-xs-12 dac-col-sm-12 dac-col-md-4">';
                $setDivWidth = 125;
                $setImgWidth = 120;
            } else if ($cols == 4) {
                $div = '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3">';
                $setDivWidth = 110;
                $setImgWidth = 105;
            }

            $counter = 0;
            $records = count($xml->club);

            foreach ($xml->club as $club) {
                if ($records > 1) {
                    // if more than one club, show the club name
                    $members .= '<div class="dac-row">';
                    $members .= $div;
                    $members .=   '<h4>' . $club->clubname . '</h4>';
                    $members .= $div;
                    $members .= '</div>';
                }

                $members .= '<div class="dac-row">';
                foreach ($club->officers->officer as $officer) {
                    // Check if an officer name is available in membername, and if not, use username
                    $name = !empty($officer->membername) ? $officer->membername : $officer->username;
                    
                    $members .= $div;  // members dac-col-xs-12 dac-col-sm-6 dac-col-md-3 dac-col-lg-3
                    $members .= '<table border="0" cellpadding="0" cellspacing="0">';
                    $members .= '<tr>';
                    if ($leader_pics == 1) {
                        $members .=   '<td style="border:0 !important;vertical-align: top; padding:0; width:' . $setDivWidth . 'px;">';
                        if ($officer->image == '') {
                            $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth  . 'px; object-fit: cover;" width="' . $setImgWidth  . '"></div>';
                        } else {
                            $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . $officer->image . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth . '; object-fit: cover;"  width="' . $setImgWidth . '"></div>';
                        }
                        $members .=   '</td>';
                    }
                    $members .=   '<td style="border:0 !important; text-align: left; vertical-align: top; padding:0;">';
                    $members .=       '<strong>' . $name . '</strong><BR>';
                    $members .=    $officer->clubposition . '<BR>';
                    if ($options['leaders_contact_link'] == 1) {
                        $members .= '<a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $officer->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
                    }
                    $members .=   '</td>';
                    $members .= '</tr>';
                    $members .= '</table>';
                    $members .= '</div>';   // <div class="col">
                    $counter = $counter + 1;
                }
                $members .= '</div>';  // dac-row
            }

            $members .= '</div>'; // dac-cols...
            return $members;
            break;

        case '3':       //  New 2 columns
            $setDivWidth = 100;
            $setImgWidth = 95;
            $members .= '<div class="dac-row">';
            $members .= '<table border="5" cellpadding="3" cellspacing="0">';
            foreach ($xml->club as $club) {

                $members .= '<tr>';
                $members .= '<td valign="top" align="left" width="40%">';
                $members .= '<table border="1" cellpadding="3" cellspacing="0">';

                foreach ($club->officers->officer as $officer) {
                    // Check if an officer name is available in membername, and if not, use username
                    $name = !empty($officer->membername) ? $officer->membername : $officer->username;
                    
                    $members .= '<tr>';
                    if ($leader_pics  == 1) {
                        $members .= '<td style="border:0 !important;vertical-align: top; padding:0; width:' . $setDivWidth . 'px;">';
                        if ($officer->image == '') {
                            $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . plugins_url('img/no_image.jpg', __FILE__) . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth . '; object-fit: cover;" width="' . $setImgWidth . '"></div>';
                        } else {
                            $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . $officer->image . '" style="aspect-ratio: 4 / 5; width: ' . $setImgWidth . '; object-fit: cover;" width="' . $setImgWidth . '"></div>';
                        }
                        $members .= '</td>';
                    }
                    $members .= '<td style="border:0 !important; text-align: left; vertical-align: top; padding:0;">';
                    $members .= '<strong>' . $officer->username . '</strong><BR>';
                    $members .= $officer->clubposition . '<BR>';

                    if ($options['leaders_contact_link'] == 1) {
                        $members .= '<a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $officer->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact</a>';
                    }

                    $members .= '</td>';
                    $members .= '</tr>';
                    $counter = $counter + 1;
                }
                $members .= '</table>';
                $members .= '</td>';
                $members .= '<td valign="top" width="60%">';
                $members .= '<a href="' . $club->cluburl . '" target="new"><strong>' . $club->clubname . '</strong></a><br>';
                $members .= '<i>' . $club->clubaddress . '<br>';
                if ($club->clubcity != '')
                    $members .= '' . $club->clubcity . ', ' . $club->clubstatecode . ' ' . $club->clubpostalzip . '</i><br>';
                else
                    $members .= '' . $club->clubstatecode . ' ' . $club->clubpostalzip . '</i><br>';
                $members .= '<strong>Where We Meet </strong><br>';
                $members .= '' . $club->meetingplace . '<br>';

                if ($club->meetingaddress != '') {
                    $members .= '' . $club->meetingaddress . '<br>';
                }
                if ($club->meetingcity != '')
                    $members .= '' . $club->meetingcity . ', ' . $club->meetingstatecode . ' ' . $club->meetingpostalcode . '<br>';
                else
                    $members .= '' . $club->meetingstatecode . ' ' . $club->meetingpostalcode . '<br>';

                $members .= '<strong>When</strong><br>';
                $members .= '' . $club->meetingday . ' at ' . $club->meetingtime . '';
                $members .= '<span style="float: right;"><a href="https://maps.google.com/maps?q=' . $club->latitude . ',' . $club->longitude . '" target="new">Map It</a></span>';
                $members .= '</td>';
                $members .= '</tr>';
                $members .= '<tr><td colspan="2"><hr style="margin:10px 0 5px 0;"></td></tr>';
            }
            $members .= '</table>';
            $members .= '</div>'; // <!-- dac-row -->

            break;
        
        case '4':
            $counter = 0;
            $records = count($xml->club);
            
            // Determine the number of columns based on the $leaders_per_row variable
            $columns = 2 ; //$options['leaders_per_row'];
            
            // Calculate the appropriate column width based on the number of columns
            $columnWidth = 100 / $columns;
            
            foreach ($xml->club as $club) {
                if ($records > 1) {
                    // if more than one club, show the club name
                    $members .= '<div class="dac-row">';
                    $members .= $div;
                    $members .=   '<h4>' . $club->clubname . '</h4>';
                    $members .= $div;
                    $members .= '</div>';
                }
            
                foreach ($club->officers->officer as $officer) {
                    // Calculate the width for each officer card based on the number of columns
                    $cardWidth = "calc({$columnWidth}% - 10px)";
            
                    $members .= '<div class="clubleader-card" style="width: ' . $cardWidth . ';">';
                    
                    // Check if an officer name is available in membername, and if not, use username
                    $name = !empty($officer->membername) ? $officer->membername : $officer->username;
            
                    // Check if an officer image is available
                    if ($officer->image != '') {
                        // Display officer image to the left
                        $members .= '<div class="clubleader-image">';
                        $members .= '<img src="' . $officer->image . '" alt="' . $name . '">';
                        $members .= '</div>';
                    } else {
                        // If no image available, display gray div with "Image not available" text
                        $members .= '<div class="clubleader-no-image">';
                        $members .= 'Image not available';
                        $members .= '</div>';
                    }
                    // Display officer information to the right
                    $members .= '<div class="clubleader-info">';
                    // Officer Name
                    $members .= '<h4>' . $name . '</h4>';
                    
                    // Officer Position
                    $members .= '<p>' . $officer->clubposition . '</p>';
                    
                    // Contact Link (if needed)
                    if ($options['leaders_contact_link'] == 1) {
                        $members .= '<p><a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $officer->userid . '" name="dlc-inline-link-' . $counter . '" class="iframe3 cboxElement">Contact ' . $name . '</a></p>';
                    }
                    
                    $members .= '</div>'; // Closing officer-info div
                    
                    $members .= '</div>'; // Closing officer-card div
                    $counter = $counter + 1;
                }
            }
            return $members;
            break;
        

        default:
            $members .= "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>Invalid style selected: <pre>" . $style . "</pre></div>";

            break;
    }
    return $members;
}

function dacdb_debug($function_name, $atts, $options, $additional_vars, $xml) {
    if (!$GLOBALS['fDebug']) {
        return; // Exit if debugging is not enabled
    }

    echo "<h5>function <em><strong>$function_name</strong></em> called:</h5>";

    // Display options
    echo '<h4 class="drawer">Options</h4><pre class="panel">';
    foreach ($options as $key => $value) {
        echo "<dt>\$options['$key']</dt><dd>$value</dd>";
    }
    echo '</pre>';

    // Display shortcode attributes
    if (count($atts) > 0) {
        echo '<h4 class="drawer">Shortcode Attributes</h4><pre class="panel">';
        foreach ($atts as $key => $value) {
            echo "<dt>[\$atts] $key</dt><dd>$value</dd>";
        }
        echo '</pre>';
    }

    // Display additional variables
    if (count($additional_vars) > 0) {
        echo '<h4 class="drawer">Named Variables</h4><pre class="panel">';
        foreach ($additional_vars as $key => $value) {
            // Special handling for XML to format it nicely
            if ($key == 'xml') {
                echo "<dt>\$xml</dt><dd>";
                // Format and display XML
                // ... Add XML formatting and displaying code here ...
                echo "</dd>";
            } else {
                echo "<dt>\$$key</dt><dd>$value</dd>";
            }
        }
        echo '</pre>';
    }    // Display additional variables

    if (count($xml) > 0) {
        echo '<h4 class="drawer">XML Output</h4><div class="panel">';
        foreach ($xml->element as $content) {
            $dom = new DOMDocument();
            $dom->preserveWhiteSpace = false; // Don't preserve whitespaces
            $dom->formatOutput = true; // Format output with indentation and line breaks
            $dom->loadXML($content->asXML()); // Load the XML string from SimpleXMLElement
            $formattedXml = $dom->saveXML(); // Save the formatted XML to a string
            echo '<pre>' . htmlspecialchars($formattedXml) . '</pre>';
        }
        echo '</div>';
    }
}

function dacdb_debug_shortcode($post, $atts) {
    $pagedata = ''; // Initialize the variable to store debugging information

    // Check if the shortcode exists on the page
    if (has_shortcode($post->post_content, 'dacdb_plus')) {
        // Iterate through the provided parameters
        foreach ($atts as $param => $value) {
            if ($param !== 'show') {
                // $pagedata .= "Parameter: $param with value: $value<br>";
            }
        }

        // Display the shortcode name and its attributes
        $shortcode_name = 'dacdb_plus';
        $pagedata .= "<code>[$shortcode_name";
        foreach ($atts as $param => $value) {
            $pagedata .= " $param=\"$value\"";
        }
        $pagedata .= "]</code>";
    } else {
        // Shortcode not found on the page
        $pagedata .= "<code>[dacdb_plus]</code> shortcode not found on the page";
    }

    return $pagedata;
}


//ANCHOR - DISTRICT EVENTS
/**
 * Fetches and formats district event data.
 *
 * This function fetches XML data from a remote service, parses that data, and
 * then formats it into a specific HTML structure for display. It handles both
 * district events and club events depending on the value of `$club_id`.
 *
 * @param array $atts An associative array of attributes.
 * @global bool $fDebug A flag indicating whether debugging is enabled.
 * @global string $data_path The base path or URL for data files.
 * @global string $file_path The base path or URL for other files.
 * @global array $options An associative array of options.
 *
 * @return string A string of formatted HTML representing the events.
 */
function dacdb_d_events($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $d_events = '';

    if ($club_id == 0) {
        $categoryids = $options['district_events_types_page'];
        $mo = $options['district_events_months'];
    } else {
        $categoryids = $options['club_events_types_page'];
        $mo = $options['club_events_months'];
    }

    if ($fDebug) {
        $events .= "=================================================================<BR>";
        $events .= "function dacdb_d_events called<br>";
        $events .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $events .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $events .= "Mo=" . $options['club_events_months'] . "<br>";
        $events .= "categoryids=" . $categoryids . "<br>";
        $events .= $data_path . 'wp_event.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $club_id . '&CatIDs=' . $categoryids . '&Mo=' . $mo . "<br>";
        $events .= "=================================================================<BR>";
    }

    $xml = simplexml_load_file($data_path . 'wp_event.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&CatIDs=' . $categoryids . '&Mo=' . $mo . '&R=' . rand());
    if (strlen($xml) == 0) {
        $events .= 'There are no events at this time.';
        return  $events;
    }

    $counter = 1;
    foreach ($xml->event as $event) {
        $d_events .= '<div class="dacdb_plus_d_event">';

        if ($options['events_global_date'] == 1) {
            if (date("Y-m-d", strtotime($event->startdate)) == date("Y-m-d", strtotime($event->enddate))) {
                $d_events .= date("F jS Y", strtotime($event->startdate)) . ' at ' . date("g:i a", strtotime($event->startdate));
            } else {
                $d_events .= date("F jS", strtotime($event->startdate)) . ' - ' . date("F jS Y", strtotime($event->enddate)) . ' at ' . date("g:i a", strtotime($event->startdate));
            }
            $d_events .= '<br>';
        }
        $d_events .= '<strong>' . $event->eventname . '</strong>';
        if ($event->eventreg == 'Y') {
            // $d_events .= '<br><small>Requires Registration</small>';
        }
        if ($options['events_global_date'] == 0) {
            $d_events .= '<br>';
            if (date("Y-m-d", strtotime($event->startdate)) == date("Y-m-d", strtotime($event->enddate))) {
                $d_events .= date("F jS Y", strtotime($event->startdate));
            } else {
                $d_events .= date("F jS", strtotime($event->startdate)) . ' - ' . date("F jS Y", strtotime($event->enddate));
            }
        }
        $d_events .= '<br>';
        // $d_events .= '<br>';
        // $d_events .= ''.$event->eventdesc.'';
        $d_events .= '<a class="iframe cboxElement" href="' . $data_path . 'R_Event.cfm?EventID=' . $event->eventid . '">More info</a>';
        $d_events .= '<br></div>';
        $d_events .= '<hr class="dacdb_plus_d_event_hr">';
        $counter = $counter + 1;
    }
    $event_total = count($xml->event);
    if ($event_total == 0) {
        $d_events .= 'There are no events at this time.';
    }
    return $d_events;
}

//!SECTION - Display Functions

