<?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.2.2
 * 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();

if (!defined('MMPDB_PLUGIN_URL')) {
    define('MMPDB_PLUGIN_URL', plugin_dir_url(__FILE__));
}
if (!defined('MMPDB_PLUGIN_DIR')) {
    define('MMPDB_PLUGIN_DIR', plugin_dir_path(__FILE__));
}

$fDebug = false;
$data_path = '';
$data_file = '';
$public_path = '';
$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 MMPDB_PLUGIN_DIR . 'includes/utilities.php';
global $options;
$options = get_mmp_options();
function dacdb_enqueue_styles()
{
    global $post; // Ensure access to the global $post object

    // Enqueue Bootstrap styles from CDN
    wp_enqueue_style('dacdb-bootstrap', 'https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css', array(), '4.4.1');

    // Main DACDB styles with Bootstrap as a dependency
    wp_enqueue_style('dacdb-main', plugins_url('css/dacdbplus.css', __FILE__), array('dacdb-bootstrap'), MMPDB_PLUGIN_VERSION);

    // Social media styles depending on Bootstrap
    wp_enqueue_style('dacdb-social-media', plugins_url('css/sm.css', __FILE__), array('dacdb-bootstrap'), MMPDB_PLUGIN_VERSION);

    // Use the latest version of the Rotary Brand Assets
    wp_enqueue_style('mmp-rotary-colors', 'https://cdn.jsdelivr.net/gh/memberminderpro/rotary-brand-assets@latest/css/rotary-colors.css', array(), MMPDB_PLUGIN_VERSION);

    // Conditionally enqueue styles for shortcode
    if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'dacdb_stories')) {
        wp_enqueue_style('show-stories', plugin_dir_url(__FILE__) . 'css/show-stories.css', array('dacdb-bootstrap'), MMPDB_PLUGIN_VERSION, 'all');
    }
}

add_action('wp_enqueue_scripts', 'dacdb_enqueue_styles');
function enqueue_fontawesome()
{
    if (!wp_style_is('font-awesome', 'enqueued')) {
        wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css', array(), null);
    }
}
add_action('wp_enqueue_scripts', 'enqueue_fontawesome');


require_once MMPDB_PLUGIN_DIR . 'includes/admin.php';
$plugin = plugin_basename(__FILE__);

//SECTION - Error Handling
/**
 * Display 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
    }
}

class InvalidShortcodeException extends Exception {}
//!SECTION - Error Handling

require_once MMPDB_PLUGIN_DIR . 'includes/class-dacdb_plus.php';

//SECTION Process Shortcode Functions
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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.
}
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
}
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;
}
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;"></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;
}
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;
}
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;
}

require_once MMPDB_PLUGIN_DIR . 'includes/show-wcm.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-meeting_info.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-club_meetings.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-riThemeLogo.php';

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;
}
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;
}
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;
}
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;
}
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;
}
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;
*/
}
require_once MMPDB_PLUGIN_DIR . 'includes/show-newMemberFormList.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-stories.php';
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=' . MMPDB_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

//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;
} 
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=" . MMPDB_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
//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;
            $div = isset($div) ? $div : '';
            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;
}


//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
require_once MMPDB_PLUGIN_DIR . 'includes/debug.php';