<?php

function dacdb_members($atts)
{
    global $fDebug, $data_path, $options;
    $options = get_mmp_options();
    
    // Initialize $members to avoid undefined variable warning
    $members = '';
    
    // Debug information (only if debug mode is enabled)
    if ($fDebug && current_user_can('manage_options')) {
        $members .= '<div class="debug-info" style="background: #f0f0f0; padding: 10px; margin: 10px 0; border: 1px solid #ccc;">';
        $members .= "Debug Info:<br>";
        $members .= "AccountID: " . $options['dacdb_district'] . "<br>";
        $members .= "ClubID: " . $options['dacdb_club'] . "<br>";
        $members .= '</div>';
    }
    
    // Initialize options and check for required settings
    $options = get_option('mmp_plus_options');
    if (!isset($options['mem_per_page'])) {
        $options['mem_per_page'] = 10; // Default value
    }
    if (!isset($options['pagnationposition'])) {
        $options['pagnationposition'] = 'Center'; // Default value
    }
    if (!isset($options['pagnationposition_tb'])) {
        $options['pagnationposition_tb'] = 'Bottom'; // Default value
    }
    if (!isset($options['member_club_pos'])) {
        $options['member_club_pos'] = 1; // Default value
    }
    if (!isset($options['members_since'])) {
        $options['members_since'] = 0; // Default value
    }
    if (!isset($options['members_since_format'])) {
        $options['members_since_format'] = 1; // Default value
    }
    if (!isset($options['member_show_club_name'])) {
        $options['member_show_club_name'] = 0; // Default value
    }
    if (!isset($options['member_bus_name'])) {
        $options['member_bus_name'] = 0; // Default value
    }
    if (!isset($options['member_bus_url'])) {
        $options['member_bus_url'] = 0; // Default value
    }
    if (!isset($options['member_bus_pos'])) {
        $options['member_bus_pos'] = 0; // Default value
    }
    if (!isset($options['member_class'])) {
        $options['member_class'] = 0; // Default value
    }
    if (!isset($options['name_display_format'])) {
        $options['name_display_format'] = 0; // Default value
    }
    if (!isset($options['member_pics'])) {
        $options['member_pics'] = 0; // Default value
    }
    if (!isset($options['members_contact_link'])) {
        $options['members_contact_link'] = 1; // Default value
    }

    // Check if member_pics is enabled but thumbnail_width is not set
    if (isset($options['member_pics']) && $options['member_pics'] === '1') {
        if (!isset($options['thumbnail_width']) || empty($options['thumbnail_width']) || $options['thumbnail_width'] <= 0) {
            $options['thumbnail_width'] = 160; // Set default width to 160px when showing member pictures
        }
    }

    $members = '';
    $counter = 0;
    $grid_counter = 0;
    $pagcounter = isset($options['mem_per_page']) ? $options['mem_per_page'] : 10;
    $pagcountersec = 1;

    // Initialize default values for attributes
    $default_atts = array(
        'members_per_row' => isset($options['members_per_row']) ? $options['members_per_row'] : 3,
        'members_contact_link' => isset($options['members_contact_link']) ? $options['members_contact_link'] : '1',
        'thumbnail_width' => isset($options['thumbnail_width']) ? $options['thumbnail_width'] : 150
    );
    
    // Merge default attributes with user provided attributes
    $atts = shortcode_atts($default_atts, $atts, 'dacdb_members');
    
    // Convert string '0' to actual integer 0 for proper comparison later
    if (isset($atts['members_contact_link']) && $atts['members_contact_link'] === '0') {
        $atts['members_contact_link'] = 0;
    }

    // Track if members shortcode has been used
    static $members_shortcode_used = false;
    if ($members_shortcode_used) {
        if (current_user_can('manage_options')) {
            return '<div class="notice notice-warning"><p>The member directory can only be used once on a single page. Please remove additional instances of <code>[dacdb_plus show="members"]</code>.</p></div>';
        }
        return ''; // Return empty for non-admin users
    }
    $members_shortcode_used = true;

    $members = '';

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

    // Get the raw value first
    $raw_members_per_row = isset($_GET['cols']) && $_GET['cols'] > 0 ? $_GET['cols'] :
        (isset($_GET['members_per_row']) && $_GET['members_per_row'] > 0 ? $_GET['members_per_row'] :
            (isset($_GET['rows']) && $_GET['rows'] > 0 ? $_GET['rows'] :
                (isset($atts['cols']) && $atts['cols'] > 0 ? $atts['cols'] :
                    (isset($atts['members_per_row']) && $atts['members_per_row'] > 0 ? $atts['members_per_row'] :
                        (isset($atts['rows']) && $atts['rows'] > 0 ? $atts['rows'] :
                            (isset($options['members_per_row']) && $options['members_per_row'] > 0 ? $options['members_per_row'] : 3))))));

    // Cast to integer
    $members_per_row = (int) $raw_members_per_row;

    $api_filename = 'wp_club_members.cfm';

    if ($fDebug && current_user_can('manage_options')) {
        $members .= "=================================================================<BR>";
        $members .= "function dacdb_members called<br>";
        $members .= "AccountID=" . $options['dacdb_district'] . "<br>";
        $members .= "ClubID=" . $options['dacdb_club'] . "<br>";
        $members .= "Thumbnail Width=" . $thumbnail_width . "<br>";
        $members .= "Thumbnail Width override=" . (isset($atts['imgwidth']) ? $atts['imgwidth'] : '') . "<br>";
        $members .= "Membertypes=" . $membertypes . "<br>";
        $name_display_format = isset($options['name_display_format']) && $options['name_display_format'] === '1' ? 'first_last' : 'last_first';
        $members .= "includeSatellite=" . $include_satellite . "<br>";
        $members .= "Name Display Format=" . $name_display_format . "<br>";
        $members .= "Membertypes override=" . (isset($atts['membertypes']) ? $atts['membertypes'] : '') . "<br>";
        $members .= "Members Per Row=" . $members_per_row . "<br>";
        
        // Debug for Contact Link parameters - more detailed with type info
        $members .= "Contact Link Option Value=" . (isset($options['members_contact_link']) ? $options['members_contact_link'] : 'not set') . " (type: " . (isset($options['members_contact_link']) ? gettype($options['members_contact_link']) : 'N/A') . ")<br>";
        $members .= "Contact Link Shortcode Value=" . (isset($atts['members_contact_link']) ? $atts['members_contact_link'] : 'not set') . " (type: " . (isset($atts['members_contact_link']) ? gettype($atts['members_contact_link']) : 'N/A') . ")<br>";
        
        // Debug business URL settings
        $members .= "Business URL Option Value=" . (isset($options['member_bus_url']) ? $options['member_bus_url'] : 'not set') . " (type: " . (isset($options['member_bus_url']) ? gettype($options['member_bus_url']) : 'N/A') . ")<br>";  
        $members .= "Business Name Option Value=" . (isset($options['member_bus_name']) ? $options['member_bus_name'] : 'not set') . " (type: " . (isset($options['member_bus_name']) ? gettype($options['member_bus_name']) : 'N/A') . ")<br>";
        $members .= "Business Position Option Value=" . (isset($options['member_bus_pos']) ? $options['member_bus_pos'] : 'not set') . " (type: " . (isset($options['member_bus_pos']) ? gettype($options['member_bus_pos']) : 'N/A') . ")<br>";
        
        // Improved show_contact_link calculation for debug with robust logic
        $show_contact_link = (isset($atts['members_contact_link']) && $atts['members_contact_link'] === '1') || 
                             (!isset($atts['members_contact_link']) && is_toggle_enabled($options, 'members_contact_link'));
        
        $members .= "Contact Link Calculated Value=" . ($show_contact_link ? 'true' : 'false') . "<br>";
        $members .= "ON status check (option === '1'): " . ((isset($options['members_contact_link']) && $options['members_contact_link'] === '1') ? 'true' : 'false') . "<br>";
        $members .= "ON status check (option == '1'): " . ((isset($options['members_contact_link']) && $options['members_contact_link'] == '1') ? 'true' : 'false') . "<br>";
        $members .= "ON status check (attr === '1'): " . ((isset($atts['members_contact_link']) && $atts['members_contact_link'] === '1') ? 'true' : 'false') . "<br>"; 
        
        $members .= "URL=" . $data_path . $api_filename . '?AccountID=' . $account_id . '&ClubID=' . $club_id . '&MemberTypeIDs=' . $membertypes . ($include_satellite === 'Y' ? '&IncludeSatellite=' . $include_satellite : '') . '<br>';
        $members .= "=================================================================<BR>";
    }

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

    // Calculate pagination values
    $counter = 1;
    $lastCounter = count($xml->member);
    $pag_total = count($xml->member);
    $pag_pages = ceil($pag_total / $options['mem_per_page']);

    // Add debug output
    if ($fDebug && current_user_can('manage_options')) {
        $members .= '<div class="debug-info" style="background: #f0f0f0; padding: 10px; margin: 10px 0; border: 1px solid #ccc;">';
        $members .= "Pagination Debug Info:<br>";
        $members .= "Total Members: " . $pag_total . "<br>";
        $members .= "Members Per Page: " . $options['mem_per_page'] . "<br>";
        $members .= "Total Pages: " . $pag_pages . "<br>";
        $members .= "Pagination Alignment: " . $options['pagnationposition'] . "<br>";
        $members .= "Pagination Position: " . $options['pagnationposition_tb'] . "<br>";
        $members .= '</div>';
    }

    // Store pagination data in a global variable for the enqueue_resources method to use
    $GLOBALS['dacdb_member_pagination_data'] = array(
        'totalPages' => (int) $pag_pages,
        'debug' => true,
        'currentPage' => 1
    );
    
    // Add debug script to check if the stylesheets are actually loaded
    if (current_user_can('manage_options')) {
        $members .= '<script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            // console.log("Checking loaded stylesheets:");
            var styles = document.styleSheets;
            for (var i = 0; i < styles.length; i++) {
                try {
                    var href = styles[i].href || "Inline style";
                    // console.log(" - " + href);
                    if (href.indexOf("show-club-members.css") > -1) {
                        // console.log("   ✓ Found show-club-members.css!");
                    }
                } catch (e) {
                    // console.log(" - [Error accessing stylesheet]");
                }
            }
            
            // Check if pagination scripts are loaded
            if (typeof jQuery !== "undefined") {
                // console.log("jQuery is loaded: " + jQuery.fn.jquery);
                if (typeof jQuery.fn.twbsPagination === "function") {
                    // console.log("✓ twbsPagination plugin is loaded!");
                } else {
                    console.error("✗ twbsPagination plugin is NOT loaded!");
                }
            } else {
                console.error("✗ jQuery is NOT loaded!");
            }
        });
        </script>';
    }

    $pagcounter = $options['mem_per_page'];
    $pagcountersec = 1;

    // check member count start pagnation
    if ($pag_pages > 0) {
        // Add pagination at top if configured
        if ($options['pagnationposition_tb'] == 'Top' || $options['pagnationposition_tb'] == 'Both') {
            $members .= '<div class="pagination-container pagination-container-top clearfix">';
            if ($options['pagnationposition'] == 'Right') {
                $members .= '<div class="pagination-right"><nav aria-label="Member directory pagination (top)"><ul id="pagination-dacdb-top" class="pagination"></ul></nav></div>';
            } else if ($options['pagnationposition'] == 'Center') {
                $members .= '<div class="pagination-center"><nav aria-label="Member directory pagination (top)"><ul id="pagination-dacdb-top" class="pagination"></ul></nav></div>';
            } else {
                $members .= '<div class="pagination-left"><nav aria-label="Member directory pagination (top)"><ul id="pagination-dacdb-top" class="pagination"></ul></nav></div>';
            }
            $members .= '</div>';
        }
    }

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

        $setDivWidth = 150;
        $setImgWidth = 140;

        if ($members_per_row == 1) {
            $members .= '<div class="member-directory__item member-directory__item--col-1' . ($member->clubid != $options['dacdb_club'] ? ' member-directory__item--satellite' : '') . '">';
        } else if ($members_per_row == 2) {
            $members .= '<div class="member-directory__item member-directory__item--col-2' . ($member->clubid != $options['dacdb_club'] ? ' member-directory__item--satellite' : '') . '">';
        } else if ($members_per_row == 3) {
            $members .= '<div class="member-directory__item member-directory__item--col-3' . ($member->clubid != $options['dacdb_club'] ? ' member-directory__item--satellite' : '') . '">';
        } else if ($members_per_row == 4) {
            $members .= '<div class="member-directory__item member-directory__item--col-4' . ($member->clubid != $options['dacdb_club'] ? ' member-directory__item--satellite' : '') . '">';
            $setImgWidth = 110;
        }

        // Add proper existence check for member_pics
        $member_pics = isset($options['member_pics']) ? $options['member_pics'] : '0';

        if ($member_pics == '1') {
            if ($member->image == '') {
                $members .= '<table class="member-directory__table"><tr><td class="member-directory__image-cell" style="width:' . $options['thumbnail_width'] . 'px"><div><img src="' . MMPDB_PLUGIN_URL . 'img/avatar.svg" class="member-directory__image"></div></td>';
            } else {
                $members .= '<table class="member-directory__table"><tr><td class="member-directory__image-cell" style="width:' . $options['thumbnail_width'] . 'px"><div><img src="' . $member->image . '" class="member-directory__image"></div></td>';
            }
        } else {
            $members .= '<table class="member-directory__table"><tr>';
        }

        $members .= '<td class="member-directory__spacer">&nbsp;</td><td class="member-directory__content"><div class="member-directory__name">' . ($options['name_display_format'] === '1' ? (!empty($member->membername) ? $member->membername : $member->username) : $member->username) . '</div>';

        if (isset($options['member_club_pos']) && $options['member_club_pos'] === '1') {
            if ($member->clubposition != '' && $member->clubposition != 'Member') {
                $members .= '<span class="member-directory__position">' . $member->clubposition . '</span>';
            }
        }

        if ((isset($options['members_since']) && $options['members_since'] === '1') || 
            (isset($options['member_show_club_name']) && $options['member_show_club_name'] > 0)) {
            $members .= '<p class="member-card__membership-info">';

            if (isset($options['member_show_club_name']) && $options['member_show_club_name'] === '1') {
                // Only show club name if member is from a different club
                if ($member->clubid != $options['dacdb_club']) {
                    $members .= '<span class="member-card__club-name">Club: ' . esc_html($member->clubname) . '</span><br><!-- Club Affiliation -->';
                }
            } elseif (isset($options['member_show_club_name']) && $options['member_show_club_name'] === '2') {
                // Always show club name
                $members .= '<span class="member-card__club-name">Club: ' . esc_html($member->clubname) . '</span><br><!-- Club Affiliation -->';
            }
            // If member_show_club_name is 0, don't show club name at all

            if (isset($options['members_since']) && $options['members_since'] === '1') {
                $startdate = strtotime($member->startdate);
                if (isset($options['members_since_format']) && $options['members_since_format'] === '1') {
                    $newformat = date('n/j/Y', $startdate);
                } elseif (isset($options['members_since_format']) && $options['members_since_format'] === '2') {
                    $newformat = date('F Y', $startdate);
                } else {
                    $newformat = date('Y', $startdate);
                }
                $members .= 'Member Since: ' . $newformat . '<br><!-- Member Since -->';
            }


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

        // Start business info section if any business data exists
        if (
            // Business name is ON (but only if it's exactly '1')
            (is_toggle_enabled($options, 'member_bus_name') && 
             (!empty($member->busname) || !empty($member->busweb))) ||
            
            // Business URL is ON (but only if it's exactly '1') and Business name is OFF (any falsy value or just not '1')
            ((!is_toggle_enabled($options, 'member_bus_name')) && 
             is_toggle_enabled($options, 'member_bus_url') && 
             !empty($member->busweb)) ||
            
            // Business position is ON (but only if it's exactly '1')
            (is_toggle_enabled($options, 'member_bus_pos') && 
             !empty($member->busposition))
        ) {
            $members .= '<p class="member-card__business-info">';

            // Handle business name and URL
            if (is_toggle_enabled($options, 'member_bus_name')) {
                // Only show URL if member_bus_url is explicitly '1'
                if (!empty($member->busname) && !empty($member->busweb) && is_toggle_enabled($options, 'member_bus_url')) {
                    $newURL = strpos($member->busweb, "https://") === false ? 'https://' . $member->busweb : $member->busweb;
                    $members .= '<a href="' . esc_url($newURL) . '" target="_blank">' . esc_html($member->busname) . '</a><br><!-- Business Name With URL -->';
                } elseif (!empty($member->busname)) {
                    $members .= esc_html($member->busname) . '<br><!-- Business Name No URL-->';
                }
            }

            // Handle URL only if business name is disabled and URL is enabled
            // Force URL to be explicitly '1', any other value (0, false, null, etc) will be treated as OFF
            if ((!is_toggle_enabled($options, 'member_bus_name')) && 
                is_toggle_enabled($options, 'member_bus_url') && 
                !empty($member->busweb)) {
                $newURL = strpos($member->busweb, "https://") === false ? 'https://' . $member->busweb : $member->busweb;
                $members .= '<a href="' . esc_url($newURL) . '" target="_blank">' . esc_html($member->busweb) . '</a><br><!-- Business URL No Business Name -->';
            }

            // Handle business position
            if (is_toggle_enabled($options, 'member_bus_pos') && !empty($member->busposition)) {
                $members .= '<span class="member-card__busposition" style="font-size:0.9em;font-style:italic;">' . esc_html($member->busposition) . '</span><br><!-- Business Position -->';
            }

            // Handle classification
            if (is_toggle_enabled($options, 'member_class') && !empty($member->classification)) {
                $members .= '<span class="member-card__business-classification">' . esc_html($member->classification) . '</span><br><!-- Business Classification -->';
            }

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

        // Get members_contact_link from shortcode attributes if it exists, otherwise use global option value
        // More robust check - only treat explicit "1" as ON, everything else as OFF
        $show_contact_link = (isset($atts['members_contact_link']) && $atts['members_contact_link'] === '1') || 
                             (!isset($atts['members_contact_link']) && is_toggle_enabled($options, 'members_contact_link'));

        if ($show_contact_link) {
            $members .= '<a href="' . $data_path . 'R_Emailer.cfm?UserID=' . $member->userid . '" name="cmc-inline-link-' . $counter . '" class="modal-link member-directory__contact-btn member-grid__contact-btn">Contact</a><br><!-- Contact Link -->';
        }

        $members .= '</td></tr></table></div><!-- end div.member -->'; // Close the div.member
        $counter = $counter + 1;
        $pagcounter = $pagcounter + 1;

        // Close dac-row only when we hit members_per_row
        if ($grid_counter == $members_per_row) {
            $members .= '</div><!-- end div.dac-row -->';
            $grid_counter = 0;
        }

        // Close page-content when we hit mem_per_page
        if ($pagcounter % $options['mem_per_page'] == 0) {
            $members .= '</div><!-- end div.page-content -->';
        }
    }
    $members .= '<!-- ' . $lastCounter . '-' . $counter . '-' . $grid_counter . ' -->';

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

    // Close page-content
    $members .= '</div><!-- end div.page-content -->';

    // Close page-wrapper
    $members .= '</div><!-- end div#page-wrapper -->';

    // Add pagination at bottom if configured
    if ($pag_pages > 0) {
        if ($options['pagnationposition_tb'] == 'Bottom' || $options['pagnationposition_tb'] == 'Both') {
            $members .= '<div class="pagination-container pagination-container-bottom clearfix">';
            if ($options['pagnationposition'] == 'Right') {
                $members .= '<div class="pagination-right"><nav aria-label="Member directory pagination (bottom)"><ul id="pagination-dacdb-bottom" class="pagination"></ul></nav></div>';
            } else if ($options['pagnationposition'] == 'Center') {
                $members .= '<div class="pagination-center"><nav aria-label="Member directory pagination (bottom)"><ul id="pagination-dacdb-bottom" class="pagination"></ul></nav></div>';
            } else {
                $members .= '<div class="pagination-left"><nav aria-label="Member directory pagination (bottom)"><ul id="pagination-dacdb-bottom" class="pagination"></ul></nav></div>';
            }
            $members .= '</div>';
        }
    }
    
    return $members;
}
