<?php

/**
 * DAdb Plus
 *
 * @category  Plugin
 * @package   DACdbPlus
 * @author    Member Minder Pro, LLC <wordpress@memberminderpro.com>
 * @copyright 2025 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
 * GitHub Plugin URI:   memberminderpro/dacdbplus
 * Description:         Easily publish your organization's data to WordPress.
 * Version:             3.2.13
 * 
 * Author:              Member Minder Pro, LLC
 * Author URI:          https://memberminderpro.com
 * Text Domain:         mmpdb
 * Domain Path:         /languages
 * License:             Apache License 2.0
 * License URI:         https://www.apache.org/licenses/LICENSE-2.0
 * Requires PHP:        7.4
 * Requires at least:   6.4
 * Tested up to:        6.8
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';

// Set the plugin version constant early
if (!defined('MMPDB_PLUGIN_VERSION')) {
    $plugin_data = get_file_data(__FILE__, [
        'Version' => 'Version',
    ]);

    define('MMPDB_PLUGIN_VERSION', $plugin_data['Version']);
}

// Add backward compatibility for DACDBPLUS_VERSION
if (!defined('DACDBPLUS_VERSION')) {
    define('DACDBPLUS_VERSION', MMPDB_PLUGIN_VERSION);
}

/**
 * Load plugin text domain for translations.
 *
 * @since 3.2.4
 * @return void
 */
function dacdb_plus_load_textdomain()
{
    load_plugin_textdomain(
        'mmpdb',
        false,
        dirname(plugin_basename(__FILE__)) . '/languages'
    );
}

// Load translations with a later priority to ensure proper loading
add_action('init', 'dacdb_plus_load_textdomain', 15);

//SECTION - Global Variable Definitions
// Note: MMPDB_PLUGIN_VERSION is now set earlier in the file with get_file_data()

// Define essential plugin path constants for use throughout the plugin
// These are conditionally defined to prevent redefinition errors
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__));
}
// Add missing constant needed by enqueue.php
if (!defined('DACDBPLUS_PLUGIN_FILE')) {
    define('DACDBPLUS_PLUGIN_FILE', __FILE__);
}

$fDebug = false;
$data_path = '';
$data_file = '';
$public_path = '';
$catid = '';

//SECTION - Required Files and Libraries

require 'plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;

$myUpdateChecker = PucFactory::buildUpdateChecker(
    'https://github.com/memberminderpro/dacdbplus',
    __FILE__,
    'dacdbplus'
);

//Set the branch that contains the stable release.
$myUpdateChecker->setBranch('main');
$myUpdateChecker->setAuthentication('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');
$myUpdateChecker->getVcsApi()->enableReleaseAssets();

require_once MMPDB_PLUGIN_DIR . 'includes/utilities.php';
global $options;
$options = get_mmp_options();

// Load centralized asset enqueuing
require_once MMPDB_PLUGIN_DIR . 'includes/enqueue.php';

// All asset enqueuing is now handled in includes/enqueue.php

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

//SECTION - Enqueue Styles
// All asset enqueuing is now handled in includes/enqueue.php

//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') {
        printf(
            '<div class="notice notice-error is-dismissible">
                <p><span class="dashicons dashicons-warning"></span> <strong>DACdb Plus:</strong> %s</p>
            </div>',
            esc_html($error_message)
        );
    } else {
        printf(
            '<div class="notice notice-error is-dismissible" style="display: flex; justify-content: space-between; align-items: center;">
                <p style="margin: 0;"><span class="dashicons dashicons-warning"></span> <strong><a href="%s">DACdb Plus</a>:</strong> %s</p>
                <div>
                    <a href="%s" class="button button-primary" style="margin: 10px;">%s</a>
                    <a href="%s" class="button button-secondary" style="margin: 10px 0;">%s</a>
                </div>
            </div>',
            esc_url($settings_url),
            esc_html($error_message),
            esc_url($settings_url),
            esc_html__('Go to Settings', 'dacdbplus'),
            esc_url($support_url),
            esc_html__('Get Support', 'dacdbplus')
        );
    }
}
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';
require_once MMPDB_PLUGIN_DIR . 'includes/debug.php';

//SECTION Process Shortcode Functions

function dacdb_clubleaders($atts)
{
    global $fDebug, $data_path, $file_path;
    $options = get_mmp_options();
    $members = '';

    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    $rolekeys = $_GET['rolekeys'] ?? $atts['rolekeys'] ?? null;

    // Handle style parameter with proper default
    $style = $_GET['style'] ?? $atts['style'] ?? '1';  // Default to '1' if not set
    $style = (string) $style;  // Ensure it's a string

    // Debug style value at each step
    $style_get = isset($_GET['style']) ? $_GET['style'] : 'not set';
    $style_atts = isset($atts['style']) ? $atts['style'] : 'not set';

    // Ensure $atts is an array
    $atts = is_array($atts) ? $atts : array();

    // Set default attributes for display
    $display_atts = array(
        'leader_pics' => isset($_GET['leader_pics']) ? $_GET['leader_pics'] :
            (isset($atts['leader_pics']) ? $atts['leader_pics'] :
                (isset($options['leader_pics']) ? $options['leader_pics'] : 1)),
        'show_committee_name' => 1,
        'show_committee_position' => 1,
        'show_contact' => isset($options['leaders_contact_link']) ? $options['leaders_contact_link'] : 1
    );

    // Merge with original atts to preserve other parameters
    $atts = array_merge($atts, $display_atts);

    // Debug information
    if ($fDebug && current_user_can('manage_options')) {
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_clubleaders called <br>";
        $members .= "AccountID=" . $account_id . "<br>";
        $members .= "ClubID=" . $club_id . "<br>";
        $members .= "Style GET=" . $style_get . "<br>";
        $members .= "Style ATTS=" . $style_atts . "<br>";
        $members .= "Style FINAL=" . $style . "<br>";
        $members .= "Leaders per row=" . $atts['leaders_per_row'] . "<br>";
        if ($rolekeys) {
            $members .= "RoleKeys=" . $rolekeys . "<br>";
        }

        // Build API URL
        $api_url = $data_path . 'wp_clubleaders.cfm?AccountID=' . $account_id . '&ClubID=' . $club_id;
        if ($rolekeys) {
            $api_url .= '&rolekeys=' . $rolekeys;
        }
        $api_url .= '&R=' . rand();

        $members .= "URL= <a href='" . $api_url . "' target='_blank' class='modal-link'>" . $api_url . "</a><br>";
        $members .= "=================================================================<BR>";
    }

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

    $xml = simplexml_load_file($api_url);

    // 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 .= mmpro_display_members($xml, $style, $atts);

    return $members;
}
function dacdb_cog($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    $cogs = '';

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

    if ($fDebug && dacdb_is_admin()) {
        $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="' . MMPDB_PLUGIN_URL . 'img/avatar.svg" 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_committee($atts)
{
    // 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'];

    // Fix for cid parameter handling - accept either string or numeric values
    $cid = "";
    if (isset($atts['cid'])) {
        // Convert to string first if it's numeric, and ensure it's cleaned of any HTML
        $cid = (string) $atts['cid'];
        // Remove any HTML that might be in the parameter
        $cid = strip_tags($cid);
    }

    $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>";
    }

    $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>";
    }

    // Get attribute values, falling back to options or defaults only if attribute doesn't exist or is empty
    $committee_global_name = isset($atts['name']) && $atts['name'] !== '' ? intval($atts['name']) : ($options['committee_global_name'] ?? 1);
    $committee_global_description = isset($atts['description']) && $atts['description'] !== '' ? intval($atts['description']) : ($options['committee_global_description'] ?? 1);
    $committee_show_account_id = isset($atts['accountid']) ? intval($atts['accountid']) :
        (isset($atts['district']) ? intval($atts['district']) :
            (isset($atts['grandlodge']) ? intval($atts['grandlodge']) :
                ($options['committee_org_data_account'] ?? 0)));
    $committee_show_entity_name = isset($atts['entityname']) ? intval($atts['entityname']) :
        (isset($atts['lodgename']) ? intval($atts['lodgename']) :
            (isset($atts['clubname']) ? intval($atts['clubname']) :
                (isset($atts['chaptername']) ? intval($atts['chaptername']) :
                    ($options['committee_org_data_entity'] ?? 1))));
    $committee_members_per_row = isset($atts['cols']) ? intval($atts['cols']) :
        (isset($atts['rows']) ? intval($atts['rows']) :
            (isset($atts['row']) ? intval($atts['row']) :
                ($options['committee_members_per_row'] ?? 3)));
    if ($committee_members_per_row < 1 || $committee_members_per_row > 4) {
        $committee_members_per_row = 3; // Default to 3 if invalid value
    }

    // Boolean attributes that can be true/false strings or 1/0
    $committee_members_pics = isset($atts['pics']) ?
        (is_string($atts['pics']) ? strtolower($atts['pics']) === 'true' : intval($atts['pics'])) :
        ($options['committee_members_pics'] ?? 1);
    $committee_members_contact_link = isset($atts['contact']) ?
        (is_string($atts['contact']) ? strtolower($atts['contact']) === 'true' : intval($atts['contact'])) :
        ($options['committee_members_contact_link'] ?? 1);
    $committee_members_committeeposition = isset($atts['committeeposition']) ?
        (is_string($atts['committeeposition']) ? strtolower($atts['committeeposition']) === 'true' : intval($atts['committeeposition'])) :
        ($options['committee_members_committeeposition'] ?? 1);
    $committee_members_busposition = isset($atts['busposition']) ?
        (is_string($atts['busposition']) ? strtolower($atts['busposition']) === 'true' : intval($atts['busposition'])) :
        ($options['committee_members_busposition'] ?? 0);
    $committee_members_classification = isset($atts['classification']) ?
        (is_string($atts['classification']) ? strtolower($atts['classification']) === 'true' : intval($atts['classification'])) :
        ($options['committee_members_classification'] ?? 0);

    // Set committee_show_members based on attributes and options
    $committee_show_members = $options['committee_show_members'] ?? 2; // Default to show all members

    // Check for members/show_members attributes
    if (isset($atts['members']) || isset($atts['show_members'])) {
        $show_members = $atts['members'] ?? $atts['show_members'];
        if ($show_members === false || $show_members === '0' || $show_members === 0) {
            $committee_show_members = 0; // Don't show members
        } elseif ($show_members === true || $show_members === '1' || $show_members === 1) {
            $committee_show_members = 2; // Show all members
        }
    }

    // Check for leaders/show_leaders attributes
    if (isset($atts['leaders']) || isset($atts['show_leaders'])) {
        $show_leaders = $atts['leaders'] ?? $atts['show_leaders'];
        if ($show_leaders === true || $show_leaders === '1' || $show_leaders === 1) {
            $committee_show_members = 1; // Show leaders only
        } elseif ($show_leaders === false || $show_leaders === '0' || $show_leaders === 0) {
            // If leaders are explicitly hidden, and we were showing all members,
            // switch to showing no members
            if ($committee_show_members === 2) {
                $committee_show_members = 0;
            }
        }
    }

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

    // Debug output for committee
    if ($fDebug && dacdb_is_admin()) {
        $members .= "<div class=\"debug\">";
        $members .= "<h5>function <em>dacdb_committee</em> called</h5>";
        $members .= "<table class=\"debug-table\">";
        $members .= "<tr><th>Variable</th><th>Option</th><th>Attribute</th><th>Default</th><th>Value</th></tr>";

        // Committee ID
        $members .= "<tr>";
        $members .= "<td><code>cid</code></td>";
        $members .= "<td>N/A</td>";
        $members .= "<td>" . ($atts['cid'] ?? 'N/A') . "</td>";
        $members .= "<td>N/A</td>";
        $members .= "<td>" . $cid . "</td>";
        $members .= "</tr>";

        // Committee Name
        $members .= "<tr>";
        $members .= "<td><code>committee_global_name</code></td>";
        $members .= "<td>" . ($options['committee_global_name'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['name'] ?? 'N/A') . "</td>";
        $members .= "<td>1</td>";
        $members .= "<td>" . $committee_global_name . "</td>";
        $members .= "</tr>";

        // Committee Description
        $members .= "<tr>";
        $members .= "<td><code>committee_global_description</code></td>";
        $members .= "<td>" . ($options['committee_global_description'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['description'] ?? 'N/A') . "</td>";
        $members .= "<td>1</td>";
        $members .= "<td>" . $committee_global_description . "</td>";
        $members .= "</tr>";

        // Show Account ID
        $members .= "<tr>";
        $members .= "<td><code>committee_show_account_id</code></td>";
        $members .= "<td>" . ($options['committee_org_data_account'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['accountid'] ?? $atts['district'] ?? $atts['grandlodge'] ?? 'N/A') . "</td>";
        $members .= "<td>0</td>";
        $members .= "<td>" . $committee_show_account_id . "</td>";
        $members .= "</tr>";

        // Show Entity Name
        $members .= "<tr>";
        $members .= "<td><code>committee_show_entity_name</code></td>";
        $members .= "<td>" . ($options['committee_org_data_entity'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['entityname'] ?? $atts['lodgename'] ?? $atts['clubname'] ?? $atts['chaptername'] ?? 'N/A') . "</td>";
        $members .= "<td>1</td>";
        $members .= "<td>" . $committee_show_entity_name . "</td>";
        $members .= "</tr>";

        // Members Per Row
        $members .= "<tr>";
        $members .= "<td><code>committee_members_per_row</code></td>";
        $members .= "<td>" . ($options['committee_members_per_row'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['cols'] ?? $atts['rows'] ?? $atts['row'] ?? 'N/A') . "</td>";
        $members .= "<td>3</td>";
        $members .= "<td>" . $committee_members_per_row . "</td>";
        $members .= "</tr>";

        // Show Members
        $members .= "<tr>";
        $members .= "<td><code>committee_show_members</code></td>";
        $members .= "<td>" . ($options['committee_show_members'] ?? 'N/A') . "</td>";
        $members .= "<td>" . ($atts['show_members'] ?? $atts['members'] ?? 'N/A') . "</td>";
        $members .= "<td>2</td>";
        $members .= "<td>" . $committee_show_members . "</td>";
        $members .= "</tr>";

        $members .= "</table>";
        $members .= "</div>";

        // XML Path
        $members .= "<div class=\"debug-row\">";
        $members .= "<p><code>xml_path</code>: ";
        $members .= "<a href=\"" . $xml_path . "\" target=\"debug-window\">" . $xml_path . "</a></p>";
        $members .= "</div>";

        // Debug output for committee_members_per_row
        $members .= "<ul class=\"debug-row\"><li><code>committee_members_per_row</code> value: " . $committee_members_per_row . "</li>";
        $members .= "<li><code>committee_members_per_row</code> type: " . gettype($committee_members_per_row) . "</li></ul>";

    }

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

    // Check if XML data is empty
    if (strlen($xml) == 0) {
        $members .= '<div class="error-msg"><i class="fa fa-times-circle"></i>There are no committee members to display at this time.</div>';
        return $members;
    }

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

    if ($committee_members_per_row === 1) {
        $div = '<div class="members dac-col-xs-12">';
        $setDivWidth = 155;
        $setImgWidth = 150;
    } else if ($committee_members_per_row === 2) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-6">';
        $setDivWidth = 140;
        $setImgWidth = 135;
    } else if ($committee_members_per_row === 3) {
        $div = '<div class="members dac-col-xs-12 dac-col-sm-6 dac-col-md-4">';
        $setDivWidth = 125;
        $setImgWidth = 120;
    } else if ($committee_members_per_row === 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);
    $thumbnail_height = isset($options['thumbnail_height']) && $options['thumbnail_height'] > 0 ? $options['thumbnail_height'] : (isset($atts['imgheight']) && isset($atts['imgheight']) > 0 ? $atts['imgheight'] : 150);

    // Counter for tracking members
    $counter = 0;

    // Display committee name if enabled
    if ($committee_global_name == 1) {
        $members .= '<div class="dac-row">';
        $members .= '   <div class="dac-col-xs-12">';
        $members .= '       <h3>' . $xml->committeemembers->committeename . '</h3>';
        $members .= '   </div>';
        $members .= '</div>';
    }

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

    // Display committee members
    if ($committee_show_members > 0) {
        $members .= '<div class="dac-row">';

        foreach ($xml->committeemembers as $member) {
            // Skip non-leaders if we're only showing leaders
            if ($committee_show_members == 1 && strtolower($member->committeeposition ?? '') === 'member') {
                continue;
            }

            $members .= $div; // Add the Bootstrap classes div here
            $members .= '<table border="0" cellpadding="0" cellspacing="0">';
            $members .= '<tr>';

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

                if ($member->image == '') {
                    $members .= '<div style="width:' . $setDivWidth . 'px;"><img src="' . MMPDB_PLUGIN_URL . 'img/avatar.svg"  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 ($committee_show_account_id == 1) {
                if ($member->accountid != '') {
                    $members .= 'District ' . $member->accountid . '<br />';
                }
            }

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

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

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

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

            $members .= '</td>';
            $members .= '</tr>';
            $members .= '</table>';
            $members .= '</div>'; // Close the Bootstrap classes div
            $counter = $counter + 1;
        }

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

    return $members;
}
function dacdb_committee_leaders($atts)
{
    global $fDebug, $data_path, $file_path, $options, $data_file;

    $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 && dacdb_is_admin()) {
        $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);

    // Make sure we explicitly set committee name display preference
    $display_atts = array(
        'cols' => isset($atts['leaders_per_row']) ? $atts['leaders_per_row'] : 1,
        'pics' => isset($atts['pics']) ? $atts['pics'] : 1,
        'show_committee_name' => 1, // Show committee name for leaders
        'show_committee_position' => 1,
        'show_contact' => isset($options['leaders_contact_link']) ? $options['leaders_contact_link'] : 1
    );

    // Merge custom attributes with our defaults
    $display_atts = array_merge($display_atts, $atts);

    $members .= mmpro_display_members($xml, $style, $display_atts);
    return $members;
}
function dacdb_d_leaders($atts)
{
    global $fDebug, $data_path, $file_path, $options, $data_file;

    $leaders = '';

    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    if (isset($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'] !== '') {
    } elseif (isset($options['leader_pics']) && $options['leader_pics'] !== '') {
        $atts['leader_pics'] = $options['leader_pics'];
    } else {
        $atts['leader_pics'] = 1;
    }


    if ($fDebug && dacdb_is_admin()) {
        $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 />';

    // Add explicit committee name display setting
    $atts['show_committee_name'] = 1; // Always show committee name for district leaders
    $atts['show_committee_position'] = 1; // Always show position

    $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="' . MMPDB_PLUGIN_URL . 'img/avatar.svg" 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="modal-link">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="'. MMPDB_PLUGIN_URL . 'img/avatar.svg" 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="modal-link">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;
*/
}
function dacdb_dcc($atts)
{
    global $fDebug, $data_path, $file_path, $options;

    // Ensure member display function is available
    if (!function_exists('mmpro_display_members')) {
        // Don't include here - we now handle this earlier in the plugin loading
        // require_once(plugin_dir_path(__FILE__) . 'includes/display/member-cards.php');

        // If the function still doesn't exist, provide an error message
        return '<div class="error-msg"><i class="fa fa-times-circle"></i>Error: Member display functionality is not available. Please contact support.</div>';
    }

    // Parse attributes with defaults
    $atts = shortcode_atts(array(
        'style' => '',                  // Card display style (1-5)
        'imgwidth' => 150,              // Image width
        'description' => '0',           // Show description
        'show_members' => '2'           // Show members: 0=None, 1=Leaders only, 2=All members
    ), $atts, 'dacdb_dcc');

    $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);

    if ($fDebug && dacdb_is_admin()) {
        // 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>";
    } else {
        $dccs = '';
    }

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

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

    // Register required assets (similar to mmpro_register_committee_assets)
    if (!wp_style_is('show-members', 'registered')) {
        wp_register_style(
            'show-members',
            plugins_url('css/display/member-cards.css', __FILE__),
            array(),
            MMPDB_PLUGIN_VERSION
        );
    }
    wp_enqueue_style('show-members');

    // Transform the XML structure to match what mmpro_display_members expects
    try {
        $transformed_xml = new SimpleXMLElement('<root></root>');

        // Create committee members parent element
        foreach ($xml->dcc as $dcc) {
            $committee_member = $transformed_xml->addChild('committeemembers');

            // Map fields from DCC XML to the expected structure
            // Using proper field names based on the sample XML
            if (isset($dcc->membername)) {
                $committee_member->addChild('membername', (string) $dcc->membername);
                $committee_member->addChild('username', (string) $dcc->membername); // Fallback
            }

            if (isset($dcc->committeename)) {
                $committee_member->addChild('committeename', (string) $dcc->committeename);
            }

            if (isset($dcc->committeeposition)) {
                $committee_member->addChild('committeeposition', (string) $dcc->committeeposition);
            }

            if (isset($dcc->clubname)) {
                $committee_member->addChild('clubname', (string) $dcc->clubname);
            }

            if (isset($dcc->image)) {
                // Combine imgpath and image if both exist
                $image_url = '';
                if (isset($dcc->imgpath) && isset($dcc->image)) {
                    $image_url = rtrim((string) $dcc->imgpath, '/') . '/' . ltrim((string) $dcc->image, '/');
                } else {
                    $image_url = (string) $dcc->image;
                }
                $committee_member->addChild('image', $image_url);
            }

            // No need to store imgpath separately since we've combined it with image
            // if (isset($dcc->imgpath)) {
            //     $committee_member->addChild('imgpath', (string) $dcc->imgpath);
            // }

            // Add additional fields if they exist
            if (isset($dcc->userid)) {
                $committee_member->addChild('userid', (string) $dcc->userid);
            }

            if (isset($dcc->phone)) {
                $committee_member->addChild('phone', (string) $dcc->phone);
            }

            if (isset($dcc->email)) {
                $committee_member->addChild('email', (string) $dcc->email);
            }

            if (isset($dcc->cluburl)) {
                $committee_member->addChild('cluburl', (string) $dcc->cluburl);
            }

            if (isset($dcc->accountid)) {
                $committee_member->addChild('accountid', (string) $dcc->accountid);
            }

            if (isset($dcc->busposition)) {
                $committee_member->addChild('busposition', (string) $dcc->busposition);
            } else if (isset($dcc->position)) {
                $committee_member->addChild('busposition', (string) $dcc->position);
            }

            if (isset($dcc->classification)) {
                $committee_member->addChild('classification', (string) $dcc->classification);
            }
        }

        // Replace the original XML with our transformed version
        $xml = $transformed_xml;

    } catch (Exception $e) {
        if ($fDebug && dacdb_is_admin()) {
            return '<div class="mmpro-error">Error transforming DCC data: ' . $e->getMessage() . '</div>';
        } else {
            error_log('DACdb Plus: Error transforming DCC data in dacdb_dcc: ' . $e->getMessage());
            return '<div class="mmpro-error">Error processing DCC data. Please check the error logs.</div>';
        }
    }

    // Set up display attributes
    $style = isset($atts['style']) && !empty($atts['style']) ? $atts['style'] :
        (isset($options['dcc_display_style']) ? $options['dcc_display_style'] : '1');

    // Determine contact link display
    $show_contact = isset($options['dcc_show_contact']) ? (int) $options['dcc_show_contact'] : 0;

    $display_atts = array(
        'cols' => isset($options['dcc_per_row']) ? $options['dcc_per_row'] : 1,
        'pics' => isset($options['dcc_pics']) ? $options['dcc_pics'] : 1,
        'show_committee_position' => 1, // Always show DCC position
        'show_committee_name' => 1,     // Always show committee name for DCC officers
        'show_district_number' => isset($options['dcc_show_district_number']) ? $options['dcc_show_district_number'] : 0,
        'show_business_position' => isset($options['dcc_show_business_position']) ? $options['dcc_show_business_position'] : 0,
        'show_classification' => isset($options['dcc_show_classification']) ? $options['dcc_show_classification'] : 0,
        'show_contact' => $show_contact,
        'name_as_contact' => false,
        'org_data_entity' => isset($options['dcc_show_club']) ? $options['dcc_show_club'] : 1, // Default to showing club
        'org_data_account' => isset($options['dcc_show_district']) ? $options['dcc_show_district'] : 0
    );

    // Optional prepend content before the cards
    if (isset($options['dcc_header']) && !empty($options['dcc_header'])) {
        $dccs .= '<div class="dcc-header">' . wp_kses_post($options['dcc_header']) . '</div>';
    }

    // Call the display function with the prepared data
    $dccs .= mmpro_display_members($xml, $style, $display_atts);

    // Optional append content after the cards
    if (isset($options['dcc_footer']) && !empty($options['dcc_footer'])) {
        $dccs .= '<div class="dcc-footer">' . wp_kses_post($options['dcc_footer']) . '</div>';
    }

    return $dccs;
}

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 && dacdb_is_admin()) {
        $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') {
                    $getURL = false;
                    $url_path = '';

                    if ($folder && $folder2 == '') {
                        $url_path = $file_path . $options['dacdb_district'] . '/Downloads/' . rawurlencode($options['dacdb_club']) . '/' . rawurlencode($folder) . '/' . rawurlencode($document->name);
                    } elseif ($folder && $folder2) {
                        $url_path = $file_path . $options['dacdb_district'] . '/Downloads/' . rawurlencode($options['dacdb_club']) . '/' . rawurlencode($folder) . '/' . rawurlencode($folder2) . '/' . rawurlencode($document->name);
                    } else {
                        $url_path = $file_path . $options['dacdb_district'] . '/Downloads/' . rawurlencode($options['dacdb_club']) . '/' . rawurlencode($document->name);
                    }

                    // Try to get the URL content with error handling
                    $getURL = @file_get_contents($url_path);
                    if ($getURL === false) {
                        // If file_get_contents fails, try to extract URL from the file name
                        $getURL = str_replace('.URL', '', $document->name);
                    }

                    // Ensure URL has proper protocol
                    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 = '';

    // Get account and club IDs from options
    $account_id = $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    $current_url = add_query_arg($wp->query_string, '', home_url($wp->request));
    
    $folder = isset($_GET["folder"]) ? $_GET["folder"] : '';
    
    // Create completely new variables for size and date display
    $should_show_size = is_toggle_enabled($options, 'newsletters_show_size');
    $should_show_date = is_toggle_enabled($options, 'newsletters_show_date');
    
    // Override with shortcode attributes if explicitly provided
    if (isset($atts['size'])) {
        $should_show_size = ($atts['size'] == '1' || $atts['size'] == 1);
    }
    if (isset($atts['date'])) {
        $should_show_date = ($atts['date'] == '1' || $atts['date'] == 1);
    }
    
    $icon = isset($atts['icon']) ? $atts['icon'] : '0';
    $location = ($options['dacdb_club'] == 0) ? 'newsletters' : 'bulletins';
    $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 && dacdb_is_admin()) {
        $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> ';
                }
            }
            
            // Adding hardcoded debug trace to isolate the issue
            if ($document->type != 'Dir') {
                // Direct option checks for size display - doesn't use intermediate variables
                if (isset($options['newsletters_show_size']) && ($options['newsletters_show_size'] === '1' || $options['newsletters_show_size'] === 1)) {
                    $documents .= '<span class="newsletter__meta newsletter__meta--size">Size: ' . FileSizeConvert($document->size) . '</span>';
                }
                
                // Direct option checks for date display - doesn't use intermediate variables
                if (isset($options['newsletters_show_date']) && ($options['newsletters_show_date'] === '1' || $options['newsletters_show_date'] === 1)) {
                    $documents .= '<span class="newsletter__meta newsletter__meta--date">Last Modified: ' . $document->datelastmodified . '</span>';
                }
            }
            
            $documents .= '<br><br></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;
}

require_once MMPDB_PLUGIN_DIR . 'includes/modal-link.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-areas.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-birthdays.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-calendar.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-club_meetings.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-club_presidents.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-committees.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-events.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-leaders.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-map.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-meeting_info.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-members.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-newMemberFormList.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-riThemeLogo.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-speakers.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-sponsors.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-stories.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-wcm.php';

//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']) && strtolower($_GET['debug']) !== 'false') {
        $fDebug = true;
    }
    return;
}

//!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();
}

// Include the widget class file
require_once MMPDB_PLUGIN_DIR . 'includes/class-dacdb_plus_widget.php';

// Add debug information only when debug mode is active
function dacdb_add_debug_footer() {
    if (isset($_GET['debug']) && strtolower($_GET['debug']) !== 'false') {
        $options = get_option('mmp_plus_options');
        
        echo '<div style="background: #f8f8f8; border: 1px solid #ddd; padding: 15px; margin: 20px; position: fixed; bottom: 0; right: 0; max-width: 400px; max-height: 300px; overflow: auto; z-index: 9999; font-family: monospace; font-size: 12px;">';
        echo '<h4>DACdb Plus Debug - Option Values</h4>';
        
        // Show toggle switch values relevant to member display
        $toggle_switches = [
            'member_bus_name', 'member_bus_url', 'member_bus_pos',
            'member_class', 'members_contact_link', 'member_club_pos',
            'members_since', 'name_display_format'
        ];
        
        echo '<table style="border-collapse: collapse; width: 100%;">';
        echo '<tr><th style="text-align: left; border-bottom: 1px solid #ccc; padding: 3px;">Option</th><th style="text-align: left; border-bottom: 1px solid #ccc; padding: 3px;">Value</th><th style="text-align: left; border-bottom: 1px solid #ccc; padding: 3px;">Enabled</th></tr>';
        
        foreach ($toggle_switches as $option) {
            $value = isset($options[$option]) ? $options[$option] : 'not set';
            $enabled = is_toggle_enabled($options, $option);
            $bg_color = $enabled ? '#d4edda' : '#f8d7da';
            
            echo '<tr style="background-color: ' . $bg_color . ';">';
            echo '<td style="padding: 3px; border-bottom: 1px solid #ddd;">' . $option . '</td>';
            echo '<td style="padding: 3px; border-bottom: 1px solid #ddd;">' . var_export($value, true) . '</td>';
            echo '<td style="padding: 3px; border-bottom: 1px solid #ddd;">' . ($enabled ? 'Yes' : 'No') . '</td>';
            echo '</tr>';
        }
        
        echo '</table>';
        echo '<button onclick="this.parentNode.style.display=\'none\';">Close</button>';
        echo '</div>';
    }
}
add_action('wp_footer', 'dacdb_add_debug_footer');

// Just before the setDataPath function, add this helper function

/**
 * Helper function to check if a toggle switch is enabled
 * Ensures consistent handling of toggle switches by only returning true
 * when the option is explicitly set to '1' as a string
 *
 * @param array $options The plugin options array
 * @param string $key The option key to check
 * @return boolean True if the toggle is enabled, false otherwise
 */
function is_toggle_enabled($options, $key) {
    return isset($options[$key]) && $options[$key] === '1';
}
