<?php
/**
 * Member display functionality for Member Minder Pro plugin
 * 
 * This file contains the member display functions used across various shortcodes.
 * It provides different styles of displaying member information while maintaining
 * backward compatibility with existing implementations.
 */

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

/**
 * Display member data in various styles
 * 
 * This function serves as a bridge between legacy and modern display styles.
 * It maintains backward compatibility through the style parameter while
 * introducing modern BEM-based markup for newer implementations.
 *
 * @param SimpleXMLElement $xml    The XML data containing member information
 * @param int $style               The style to display the members:
 *                                 0 = Test Mode
 *                                 1 = Legacy Leaders Display (Aligned Columns)
 *                                 3 = Legacy Two Column Layout
 *                                 4 = Legacy Card Display
 *                                 5 = Modern Card Display (BEM-based)
 * @param array $atts              Display attributes:
 *                                 - cols: Number of columns (1-4)
 *                                 - pics: Whether to show photos (0/1)
 *                                 - show_*: Various display toggles
 *
 * @global bool $fDebug            Debug mode flag
 * @global string $data_path       Data operations path
 * @global string $file_path       File operations path
 * @global array $options          Plugin options
 *
 * @return string                  HTML markup for member display
 */
function dacdb_DisplayMembers($xml, $style, $atts) {
    // Maintain backward compatibility while introducing new naming
    return mmpro_display_members($xml, $style, $atts);
}

/**
 * Helper function to get member name, preferring membername over username
 * 
 * @param object $member The member object containing name information
 * @return string The member's name
 */
function mmpro_get_member_name($member) {
    // First try membername as it's the properly formatted name
    if (!empty($member->membername)) {
        return $member->membername;
    }
    // Fallback to username if membername is not available
    if (!empty($member->username)) {
        return $member->username;
    }
    // If neither is available, return empty string
    return '';
}

/**
 * Modern implementation of member display functionality
 */
function mmpro_display_members($xml, $style, $atts) {
    global $fDebug, $data_path, $file_path, $options;

    // Register and enqueue required styles
    if (!wp_style_is('show-members', 'registered')) {
        wp_register_style(
            'show-members',
            MMPDB_PLUGIN_URL . 'css/display/member-cards.css',
            array(),
            MMPDB_PLUGIN_VERSION
        );
    }
    wp_enqueue_style('show-members');

    // Set default style to 1 (legacy aligned columns) if empty or not provided
    if (empty($style) || !in_array($style, ['0', '1', '3', '4', '5', 0, 1, 3, 4, 5])) {
        $style = '1';
        if (defined('WP_DEBUG') && WP_DEBUG === true) {
            error_log('MMPro Display Members - Using default legacy style 1 (aligned columns)');
        }
    }

    // Debug logging
    if (defined('WP_DEBUG') && WP_DEBUG === true) {
        error_log('MMPro Display Members - Style: ' . var_export($style, true));
        error_log('MMPro Display Members - XML Structure: ' . var_export($xml, true));
    }

    // Initialize variables
    $members = "";
    
    // Set defaults
    $atts = wp_parse_args($atts, array(
        'cols' => 1,
        'pics' => 1,
        'show_committee_position' => 1,
        'show_committee_name' => 0,
        'show_district_number' => 0,
        'show_business_position' => 0,
        'show_classification' => 0,
        'show_contact' => 1,
        'name_as_contact' => false,
        'org_data' => 0,
        'org_data_entity' => 0,
        'org_data_account' => 0
    ));

    // Debug information
    if ($fDebug) {
        $members .= sprintf(
            '<div class="mmpro-debug">
                <h5>function mmpro_display_members</h5>
                <pre>Style: %s\nColumns: %s\nPictures: %s</pre>
            </div>',
            esc_html($style),
            esc_html($atts['cols']),
            esc_html($atts['pics'])
        );
    }

    // Process based on style
    switch ($style) {
        case '0':
        case 0:   // Test Mode
            $members .= '<div class="test-mode">';
            foreach ($xml->club as $member) {
                $members .= esc_html($member->clubname) . "<br/>";
                $members .= count($member->officers->officer) . "<br>";
                foreach ($member->officers->officer as $officer) {
                    $members .= esc_html($officer->username) . "<br/>";
                }
            }
            $members .= '</div>';
            break;

        case '1':
        case 1:    // Legacy Leaders Display (Aligned Columns)
            $setDivWidth = 160;
            $setImgWidth = 150;

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

            $members .= '<div class="dac-row">';
            foreach ($xml->committeemembers as $member) {
                $members .= $div;
                $members .= '<table border="0" cellpadding="0" cellspacing="0">';
                $members .= '<tr>';
                
                if ($atts['pics']) {
                    $members .= '<td style="border:0 !important;vertical-align: top; padding:0; width:' . $setDivWidth . 'px;">';
                    if (empty($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->imgpath . $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;">';
                
                // Member name with optional contact link
                if ($atts['show_contact']) {
                    $members .= '<a href="' . esc_url($data_path . 'R_Emailer.cfm?UserID=' . $member->userid) . '" class="iframe3 cboxElement"><strong>' . esc_html(mmpro_get_member_name($member)) . '</strong></a>';
                } else {
                    $members .= '<strong>' . esc_html(mmpro_get_member_name($member)) . '</strong>';
                }
                $members .= '<br>';

                // Committee name if enabled and available
                if ($atts['show_committee_name'] && !empty($member->committeename)) {
                    $members .= '<span class="committee-name">' . esc_html($member->committeename) . '</span><br>';
                }

                // Optional information
                if ($atts['show_committee_position'] && !empty($member->committeeposition)) {
                    $members .= esc_html($member->committeeposition) . '<br>';
                }

                // Organization data based on setting
                if (isset($atts['org_data_entity']) || isset($atts['org_data_account'])) {
                    // Show Club/Entity/Lodge name if enabled
                    if ($atts['org_data_entity'] && !empty($member->clubname)) {
                        $club_url = function_exists('formatDomainToUrl') ? formatDomainToUrl($member->cluburl) : '';
                        if (!empty($club_url)) {
                            $members .= '<a href="' . esc_url($club_url) . '" target="_blank">' . esc_html($member->clubname) . '</a><br>';
                        } else {
                            $members .= esc_html($member->clubname) . '<br>';
                        }
                    }
                    
                    // Show Account/District/Grand Lodge name if enabled
                    if ($atts['org_data_account'] && !empty($member->accountid)) {
                        $members .= 'District ' . esc_html($member->accountid) . '<br>';
                    }
                }

                // Business position if enabled
                if ($atts['show_business_position'] && !empty($member->busposition)) {
                    $members .= esc_html($member->busposition) . '<br>';
                }

                // Classification if enabled
                if ($atts['show_classification'] && !empty($member->classification)) {
                    $members .= esc_html($member->classification) . '<br>';
                }

                // Separate contact link if needed
                if ($atts['show_contact'] && !$atts['name_as_contact']) {
                    $members .= '<a href="' . esc_url($data_path . 'R_Emailer.cfm?UserID=' . $member->userid) . '" class="iframe3 cboxElement">Contact</a>';
                }

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

        case '3':
        case 3:    // Legacy Two Column Layout
            $setDivWidth = 100;
            $setImgWidth = 95;
            $members .= '<div class="dac-row">';
            $members .= '<div class="members dac-col-xs-12">'; // Force full width
            $members .= '<table border="5" cellpadding="3" cellspacing="0" style="width: 100%;">';
            
            foreach ($xml->committeemembers as $member) {
                $members .= '<tr>';
                $members .= '<td valign="top" align="left" width="40%">';
                $members .= '<table border="1" cellpadding="3" cellspacing="0">';
                $members .= '<tr>';

                if ($atts['pics']) {
                    $members .= '<td style="border:0 !important;vertical-align: top; padding:0; width:' . $setDivWidth . 'px;">';
                    if (empty($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->imgpath . $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>' . esc_html(mmpro_get_member_name($member)) . '</strong><br>';
                
                // Committee name if enabled and available
                if ($atts['show_committee_name'] && !empty($member->committeename)) {
                    $members .= '<span class="committee-name">' . esc_html($member->committeename) . '</span><br>';
                }
                
                if ($atts['show_committee_position'] && !empty($member->committeeposition)) {
                    $members .= esc_html($member->committeeposition) . '<br>';
                }

                if ($atts['show_contact']) {
                    $members .= '<a href="' . esc_url($data_path . 'R_Emailer.cfm?UserID=' . $member->userid) . '" class="iframe3 cboxElement">Contact</a>';
                }

                $members .= '</td></tr></table>';
                
                $members .= '</td><td valign="top" width="60%">';
                
                // Organization data based on setting
                if (isset($atts['org_data_entity']) || isset($atts['org_data_account'])) {
                    // Show Club/Entity/Lodge name if enabled
                    if ($atts['org_data_entity'] && !empty($member->clubname)) {
                        $club_url = function_exists('formatDomainToUrl') ? formatDomainToUrl($member->cluburl) : '';
                        if (!empty($club_url)) {
                            $members .= '<a href="' . esc_url($club_url) . '" target="new"><strong>' . esc_html($member->clubname) . '</strong></a><br>';
                        } else {
                            $members .= '<strong>' . esc_html($member->clubname) . '</strong><br>';
                        }
                    }
                    
                    // Show Account/District/Grand Lodge name if enabled
                    if ($atts['org_data_account'] && !empty($member->accountid)) {
                        $members .= 'District ' . esc_html($member->accountid) . '<br>';
                    }
                }

                if ($atts['show_business_position'] && !empty($member->busposition)) {
                    $members .= esc_html($member->busposition) . '<br>';
                }

                if ($atts['show_classification'] && !empty($member->classification)) {
                    $members .= esc_html($member->classification) . '<br>';
                }

                $members .= '</td></tr>';
                $members .= '<tr><td colspan="2"><hr style="margin:10px 0 5px 0;"></td></tr>';
            }
            
            $members .= '</table>';
            $members .= '</div>'; // Close dac-col-xs-12
            $members .= '</div>'; // Close dac-row
            break;

        case '4':
        case 4:    // Legacy Card Layout
            $members .= '<div class="clubleader-container">';
            
            foreach ($xml->committeemembers as $member) {
                $members .= '<div class="clubleader-card">';
                $members .= '<div class="clubleader-card-inner">';

                // Member image
                if ($atts['pics']) {
                    $members .= '<div class="clubleader-image" style="aspect-ratio: 4/5; width: 100%;">';
                    if (!empty($member->image)) {
                        $members .= '<img src="' . esc_url($member->imgpath . $member->image) . '" alt="' . esc_attr(mmpro_get_member_name($member)) . '" style="width: 100%; height: 100%; object-fit: cover;">';
                    } else {
                        $members .= '<div class="clubleader-no-image" style="width: 100%; height: 100%;"><i class="fas fa-user"></i></div>';
                    }
                    $members .= '</div>';
                }

                // Member information
                $members .= '<div class="clubleader-info">';
                $members .= '<h4>' . esc_html(mmpro_get_member_name($member)) . '</h4>';

                // Committee name if enabled and available
                if ($atts['show_committee_name'] && !empty($member->committeename)) {
                    $members .= '<p class="clubleader-committee">' . esc_html($member->committeename) . '</p>';
                }

                if ($atts['show_committee_position'] && !empty($member->committeeposition)) {
                    $members .= '<p class="clubleader-position">' . esc_html($member->committeeposition) . '</p>';
                }

                // Start list only if we have items to show
                $list_items = array();

                // Organization data based on setting
                if (isset($atts['org_data_entity']) || isset($atts['org_data_account'])) {
                    // Show Club/Entity/Lodge name if enabled
                    if ($atts['org_data_entity'] && !empty($member->clubname)) {
                        $club_url = function_exists('formatDomainToUrl') ? formatDomainToUrl($member->cluburl) : '';
                        if (!empty($club_url)) {
                            $list_items[] = '<li><a href="' . esc_url($club_url) . '" target="_blank">' . esc_html($member->clubname) . '</a></li>';
                        } else {
                            $list_items[] = '<li>' . esc_html($member->clubname) . '</li>';
                        }
                    }
                    
                    // Show Account/District/Grand Lodge name if enabled
                    if ($atts['org_data_account'] && !empty($member->accountid)) {
                        $list_items[] = '<li>District ' . esc_html($member->accountid) . '</li>';
                    }
                }

                if ($atts['show_business_position'] && !empty($member->busposition)) {
                    $list_items[] = '<li>' . esc_html($member->busposition) . '</li>';
                }

                if ($atts['show_classification'] && !empty($member->classification)) {
                    $list_items[] = '<li>' . esc_html($member->classification) . '</li>';
                }

                if ($atts['show_contact'] && !empty($member->userid)) {
                    $list_items[] = '<li><a href="' . esc_url($data_path . 'R_Emailer.cfm?UserID=' . $member->userid) . '" class="modal-link">Contact</a></li>';
                }

                // Only output the list if we have items
                if (!empty($list_items)) {
                    $members .= '<ul>' . implode('', $list_items) . '</ul>';
                }

                $members .= '</div>'; // Close clubleader-info
                $members .= '</div>'; // Close clubleader-card-inner
                $members .= '</div>'; // Close clubleader-card
            }
            
            $members .= '</div>'; // Close clubleader-container
            break;

        case '5':
        case 5:    // Modern Card Display (BEM-based)
            if (!$xml || !isset($xml->committeemembers)) {
                return '<div class="mmpro-error">No committee members found</div>';
            }

            $members .= '<div class="mmpro-members">';
            $members .= '<div class="mmpro-members__grid">';
            
            foreach ($xml->committeemembers as $member) {
                $members .= '<div class="mmpro-members__item">';
                $members .= '<div class="mmpro-members__card">';
                
                // Photo section
                if ($atts['pics']) {
                    $members .= '<div class="mmpro-members__photo" style="aspect-ratio: 4/5; width: 100%;">';
                    $img_src = $member->image ? $member->imgpath . $member->image : MMPDB_PLUGIN_URL . 'img/avatar.svg';
                    $members .= '<img src="' . esc_url($img_src) . '" alt="' . esc_attr(mmpro_get_member_name($member)) . '" class="mmpro-members__image" style="width: 100%; height: 100%; object-fit: cover;">';
                    $members .= '</div>';
                }
                
                // Details section
                $members .= '<div class="mmpro-members__details">';
                
                // Name with optional contact link
                if ($atts['show_contact'] && !empty($member->userid)) {
                    $members .= '<a href="' . esc_url($data_path . 'R_Emailer.cfm?UserID=' . $member->userid) . '" class="mmpro-members__name modal-link">' . esc_html(mmpro_get_member_name($member)) . '</a>';
                } else {
                    $members .= '<span class="mmpro-members__name">' . esc_html(mmpro_get_member_name($member)) . '</span>';
                }
                
                // Committee name if enabled and available
                if ($atts['show_committee_name'] && !empty($member->committeename)) {
                    $members .= '<div class="mmpro-members__committee">' . esc_html($member->committeename) . '</div>';
                }
                
                // Position
                if ($atts['show_committee_position'] && !empty($member->committeeposition)) {
                    $members .= '<div class="mmpro-members__position">' . esc_html($member->committeeposition) . '</div>';
                }
                
                // Organization data based on setting
                if (isset($atts['org_data_entity']) || isset($atts['org_data_account'])) {
                    // Show Club/Entity/Lodge name if enabled
                    if ($atts['org_data_entity'] && !empty($member->clubname)) {
                        $club_url = function_exists('formatDomainToUrl') ? formatDomainToUrl($member->cluburl) : '';
                        if (!empty($club_url)) {
                            $members .= '<a href="' . esc_url($club_url) . '" class="mmpro-members__org" target="_blank">' . esc_html($member->clubname) . '</a>';
                        } else {
                            $members .= '<div class="mmpro-members__org">' . esc_html($member->clubname) . '</div>';
                        }
                    }
                    
                    // Show Account/District/Grand Lodge name if enabled
                    if ($atts['org_data_account'] && !empty($member->accountid)) {
                        $members .= '<div class="mmpro-members__org">District ' . esc_html($member->accountid) . '</div>';
                    }
                }
                
                // Optional information
                if ($atts['show_business_position'] && !empty($member->busposition)) {
                    $members .= '<div class="mmpro-members__business-position">' . esc_html($member->busposition) . '</div>';
                }
                
                if ($atts['show_classification'] && !empty($member->classification)) {
                    $members .= '<div class="mmpro-members__classification">' . esc_html($member->classification) . '</div>';
                }
                
                // Separate contact link if needed
                if ($atts['show_contact'] && !$atts['name_as_contact'] && !empty($member->userid)) {
                    $members .= '<a href="' . esc_url($data_path . 'R_Emailer.cfm?UserID=' . $member->userid) . '" class="mmpro-members__contact modal-link">Contact</a>';
                }
                
                $members .= '</div>'; // Close details
                $members .= '</div>'; // Close card
                $members .= '</div>'; // Close item
            }
            
            $members .= '</div>'; // Close grid
            $members .= '</div>'; // Close members
            break;

        default:
            $members .= sprintf(
                '<div class="mmpro-error"><i class="fa fa-times-circle"></i>Invalid style selected: <pre>%s</pre></div>',
                esc_html($style)
            );
            break;
    }

    return $members;
}
