<?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.16
 * 
 * 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.1
 */

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_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;
}

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-committee.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-committees.php';
require_once MMPDB_PLUGIN_DIR . 'includes/show-documents.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-newsletters.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;

    // Get the system from options
    $system = isset($options['dacdb_system']) ? $options['dacdb_system'] : '';

    // Set paths based on system
    if ($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';
    } else {
        // Default to 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 (defined('WP_DEBUG') && WP_DEBUG === true) {
        error_log('DACdb Plus: System set to ' . $system);
        error_log('DACdb Plus: Data path set to ' . $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';
}
