<?php
/**
 * Asset Enqueuing Functions
 *
 * Centralized location for all CSS and JS enqueuing in the DACdb Plus plugin.
 *
 * @package DACdbPlus
 */

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

// Ensure we have version constants available
if (!defined('MMPDB_PLUGIN_VERSION')) {
    define('MMPDB_PLUGIN_VERSION', '3.3.0'); // Fallback version
}

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

// Make sure the global is initialized early
$dacdbplus_console_log_queue = [];

/**
 * Adds a JS console log message to the footer queue.
 * Only active for logged-in admins when WP_DEBUG is true.
 */
function dacdbplus_queue_console_log($message) {
    if (!is_user_logged_in() || !current_user_can('manage_options') || !defined('WP_DEBUG') || !WP_DEBUG) {
        return;
    }

    // Use a global array to store messages
    global $dacdbplus_console_log_queue;
    if (!isset($dacdbplus_console_log_queue) || !is_array($dacdbplus_console_log_queue)) {
        $dacdbplus_console_log_queue = [];
    }

    // Add message
    $dacdbplus_console_log_queue[] = 'DACDB+: ' . $message;

    // Ensure the footer action is added only once using a flag
    static $footer_action_added = false;
    if (!$footer_action_added) {
        add_action('wp_footer', 'dacdbplus_print_queued_console_logs', 999); // Use wp_footer for frontend
        add_action('admin_footer', 'dacdbplus_print_queued_console_logs', 999); // Use admin_footer for backend
        $footer_action_added = true;
    }
}

/**
 * Prints all queued console log messages in the footer within a single script tag.
 */
function dacdbplus_print_queued_console_logs() {
    global $dacdbplus_console_log_queue;

    if (!empty($dacdbplus_console_log_queue) && is_array($dacdbplus_console_log_queue)) {
        echo "\n<script>\n";
        echo "/* DACdb+ Debug Messages */\n";
        foreach ($dacdbplus_console_log_queue as $message) {
            // Basic sanitization for JS output
            $safe_message = wp_json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            echo "console.log(" . $safe_message . ");\n";
        }
        echo "</script>\n";
         // Clear the queue after printing
         $dacdbplus_console_log_queue = [];
    }
}

/**
 * Emergency function to ensure members assets are loaded when needed
 * 
 * This function directly loads member assets based on URL or page content
 * without relying on complex shortcode detection
 */
function dacdbplus_force_member_assets() {
    // Only run this after init when we have access to globals
    if (!did_action('init')) {
        return;
    }

    $load_assets = false;
    $debug_reason = '';
    
    // Check 1: URL contains "members"
    $current_url = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';
    if (strpos(strtolower($current_url), 'members') !== false) {
        $load_assets = true;
        $debug_reason = 'URL contains "members"';
    }
    
    // Check 2: Current post content contains members shortcode
    global $post;
    if (!$load_assets && is_object($post) && !empty($post->post_content)) {
        // Simple check for common patterns
        $content = strtolower($post->post_content);
        if (
            strpos($content, '[dacdb_plus') !== false && 
            strpos($content, 'members') !== false
        ) {
            $load_assets = true;
            $debug_reason = 'Post content likely contains members shortcode';
        }
    }
    
    // Debug output for admin users
    if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
        error_log('DACdbPlus EMERGENCY: Members asset check: ' . ($load_assets ? 'LOADING' : 'SKIPPING'));
        if ($load_assets) {
            error_log('DACdbPlus EMERGENCY: Reason: ' . $debug_reason);
            error_log('DACdbPlus EMERGENCY: URL: ' . $current_url);
        }
    }
    
    // Load assets if needed
    if ($load_assets) {
        $plugin_url = plugin_dir_url(dirname(__FILE__));
        $css_url = $plugin_url . 'css/';
        $js_url = $plugin_url . 'js/';
        
        // Force enqueue member styles
        wp_enqueue_style(
            'dacdb-show-club-members', 
            $css_url . 'show-club-members.css', 
            array(), 
            MMPDB_PLUGIN_VERSION
        );
        
        // Force enqueue pagination scripts
        wp_enqueue_script('jquery');
        
        wp_enqueue_script(
            'twbs-pagination', 
            $js_url . 'pagination.js', 
            array('jquery'), 
            '1.4.1', 
            true
        );
        
        wp_enqueue_script(
            'dacdb-member-pagination', 
            $js_url . 'member-pagination.js', 
            array('jquery', 'twbs-pagination'), 
            MMPDB_PLUGIN_VERSION, 
            true
        );
        
        // Add footer script for pagination initialization
        add_action('wp_footer', function() {
            ?>
            <script>
            jQuery(document).ready(function($) {
                // console.log("EMERGENCY PAGINATION INIT: Trying to initialize pagination");
                if (typeof $.fn.twbsPagination === 'undefined') {
                    console.error("EMERGENCY PAGINATION INIT: twbsPagination plugin still not available");
                    return;
                }
                
                // console.log("EMERGENCY PAGINATION INIT: twbsPagination plugin found!");
                
                // Wait for pagination data to be available
                var checkPaginationData = function() {
                    if (typeof window.dacdbMemberPagination !== 'undefined') {
                        // console.log("EMERGENCY PAGINATION INIT: Pagination data found, initializing...");
                        
                        // Initialize top pagination
                        if ($("#pagination-dacdb-top").length > 0) {
                            try {
                                $("#pagination-dacdb-top").twbsPagination({
                                    totalPages: window.dacdbMemberPagination.totalPages || 1,
                                    visiblePages: 5,
                                    first: '«',
                                    prev: '‹',
                                    next: '›',
                                    last: '»',
                                    onPageClick: function (event, page) {
                                        // console.log("Page " + page + " clicked");
                                        window.dacdbMemberPagination.currentPage = page;
                                        $(".page-content").hide();
                                        $("#pagsec" + page).show();
                                    }
                                });
                                console.log("EMERGENCY PAGINATION INIT: Top pagination initialized!");
                            } catch (e) {
                                console.error("EMERGENCY PAGINATION INIT: Top pagination error:", e);
                            }
                        }
                        
                        // Initialize bottom pagination
                        if ($("#pagination-dacdb-bottom").length > 0) {
                            try {
                                $("#pagination-dacdb-bottom").twbsPagination({
                                    totalPages: window.dacdbMemberPagination.totalPages || 1,
                                    visiblePages: 5,
                                    first: '«',
                                    prev: '‹',
                                    next: '›',
                                    last: '»',
                                    onPageClick: function (event, page) {
                                        console.log("Page " + page + " clicked");
                                        window.dacdbMemberPagination.currentPage = page;
                                        $(".page-content").hide();
                                        $("#pagsec" + page).show();
                                    }
                                });
                                console.log("EMERGENCY PAGINATION INIT: Bottom pagination initialized!");
                            } catch (e) {
                                console.error("EMERGENCY PAGINATION INIT: Bottom pagination error:", e);
                            }
                        }
                    } else {
                        console.log("EMERGENCY PAGINATION INIT: Waiting for pagination data...");
                        setTimeout(checkPaginationData, 500); // Check again in 500ms
                    }
                };
                
                // Start checking for pagination data
                checkPaginationData();
            });
            </script>
            <?php
        }, 999);
    }
}

// Hook this function to run after init
add_action('wp', 'dacdbplus_force_member_assets', 5);

/**
 * Helper function to get the correct plugin version
 * 
 * Provides a consistent way to access the plugin version
 * regardless of which constant is defined
 *
 * @return string The plugin version
 */
function dacdbplus_get_version() {
    if (defined('MMPDB_PLUGIN_VERSION')) {
        return MMPDB_PLUGIN_VERSION;
    } elseif (defined('DACDBPLUS_VERSION')) {
        return DACDBPLUS_VERSION;
    } else {
        return '3.3.0'; // Fallback version
    }
}

/**
 * DACdb Plus Asset Management
 * 
 * Functions for managing CSS and JavaScript assets
 */

/**
 * Debug utility to log asset status information
 */
function dacdbplus_asset_log($message, $context = array()) {
    if (!is_admin() || !current_user_can('manage_options')) {
        return;
    }

    static $assets_logged = array();
    
    // Avoid duplicate messages with the same context
    $context_key = md5(serialize($context) . $message);
    if (isset($assets_logged[$context_key])) {
        return;
    }
    
    $assets_logged[$context_key] = true;
    
    echo "<div class='dac-asset-debug' style='background: #f8f9fa; border-left: 4px solid #0056b3; padding: 0.5rem; margin: 0.5rem 0; font-family: monospace; font-size: 12px;'>";
    echo "<strong>DACDB+ Asset Debug:</strong> " . esc_html($message);
    
    if (!empty($context)) {
        echo "<pre style='margin: 0.25rem 0 0; padding: 0.25rem; background: #f0f0f0; max-height: 200px; overflow: auto;'>";
        echo esc_html(print_r($context, true));
        echo "</pre>";
    }
    
    echo "</div>";
}

/**
 * Track all registered styles and their sources
 */
function dacdbplus_track_registered_styles() {
    if (!is_admin() || !current_user_can('manage_options')) {
        return;
    }
    
    global $wp_styles;
    
    if (!is_object($wp_styles) || empty($wp_styles->registered)) {
        return;
    }
    
    add_action('wp_footer', function() use ($wp_styles) {
        echo '<div class="dac-asset-debug" style="background: #f8f9fa; border-left: 4px solid #0056b3; padding: 0.5rem; margin: 0.5rem 0; font-family: monospace; font-size: 12px;">';
        echo '<strong>DACDB+ Registered Styles:</strong>';
        echo '<pre style="margin: 0.25rem 0 0; padding: 0.25rem; background: #f0f0f0; max-height: 200px; overflow: auto;">';
        
        foreach ($wp_styles->registered as $handle => $style) {
            if (strpos($handle, 'dacdb') !== false) {
                echo esc_html(sprintf(
                    "%s: %s\n",
                    $handle,
                    $style->src
                ));
            }
        }
        
        echo '</pre>';
        echo '<strong>DACDB+ Queued Styles:</strong>';
        echo '<pre style="margin: 0.25rem 0 0; padding: 0.25rem; background: #f0f0f0; max-height: 200px; overflow: auto;">';
        
        foreach ($wp_styles->queue as $handle) {
            if (strpos($handle, 'dacdb') !== false) {
                $style = $wp_styles->registered[$handle];
                echo esc_html(sprintf(
                    "%s: %s\n",
                    $handle,
                    $style->src
                ));
            }
        }
        
        echo '</pre>';
        echo '</div>';
    }, 999);
}

/**
 * Register all front-end styles used by the plugin
 */
function dacdbplus_register_styles() {
    $plugin_url = plugin_dir_url(dirname(__FILE__));
    $css_url = $plugin_url . 'css/';
    
    dacdbplus_asset_log("Registering styles", [
        'plugin_url' => $plugin_url,
        'css_url' => $css_url
    ]);
    
    // Core plugin stylesheet 
    wp_register_style('dacdb-main', $css_url . 'dacdbplus.css', array(), dacdbplus_get_version());
    
    // Register social media styles with correct dependency
    wp_register_style('dacdb-social-media', $css_url . 'sm.css', array('dacdb-main'), dacdbplus_get_version());
    
    // Font Awesome is conditionally loaded
    wp_register_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css', array(), '6.1.1');
    
    // External Rotary colors from CDN
    wp_register_style('mmp-rotary-colors', 'https://cdn.jsdelivr.net/gh/memberminderpro/rotary-brand-assets@latest/css/rotary-colors.css', array('dacdb-main'), dacdbplus_get_version());
    
    // Modal link styles - always enqueued
    wp_register_style('mmpdbplus-modal', $css_url . 'modal-link.css', array(), dacdbplus_get_version());
    
    // Register conditional styles - these will be enqueued only when needed
    wp_register_style('member-cards', $css_url . 'display/member-cards.css', array(), dacdbplus_get_version());
    wp_register_style('dacdb-show-club-members', $css_url . 'show-club-members.css', array(), dacdbplus_get_version());
    wp_register_style('dacdbplus-colorbox', $css_url . 'partials/_colorbox.css', array(), dacdbplus_get_version());
    wp_register_style('dacdb-stories-style', $css_url . 'show-stories.css', array(), dacdbplus_get_version());
    wp_register_style('show-sponsors', $css_url . 'show-sponsors.css', array(), dacdbplus_get_version());
    wp_register_style('show-newsletters', $css_url . 'show-newsletters.css', array(), dacdbplus_get_version());
    wp_register_style('dacdb-leaders', $css_url . 'show-leaders.css', array(), dacdbplus_get_version());
    wp_register_style('dacdb-birthdays', $css_url . 'show-birthdays.css', array(), dacdbplus_get_version());
    wp_register_style('mmpro-club-presidents-style', $css_url . 'show-club_presidents.css', array(), dacdbplus_get_version());
    wp_register_style('mmpro-committees-style', $css_url . 'show-committees.css', array(), dacdbplus_get_version());
    wp_register_style('story-cards', $css_url . 'display/story-cards.css', array(), dacdbplus_get_version());
    wp_register_style('mmpro-calendar-style', $css_url . 'show-calendar.css', array(), dacdbplus_get_version());
    wp_register_style('dacdb-areas-style', $css_url . 'show-areas.css', array(), dacdbplus_get_version());
    wp_register_style('show-riThemeLogo', $css_url . 'show-riThemeLogo.css', array(), dacdbplus_get_version());
    wp_register_style('dacdb-speakers-style', $css_url . 'show-speakers.css', array(), dacdbplus_get_version());
    
    // Always enqueue main stylesheets
    wp_enqueue_style('dacdb-main');
    wp_enqueue_style('dacdb-social-media');
    wp_enqueue_style('mmp-rotary-colors');
    wp_enqueue_style('mmpdbplus-modal'); // Always enqueue modal styles
    
    // Track all registered styles for debugging
    dacdbplus_track_registered_styles();
}

/**
 * Register all front-end scripts used by the plugin
 */
function dacdbplus_register_scripts() {
    $plugin_url = plugin_dir_url(dirname(__FILE__));
    $js_url = $plugin_url . 'js/';
    $plugin_path = plugin_dir_path(dirname(__FILE__));
    
    dacdbplus_asset_log("Registering scripts", [
        'plugin_url' => $plugin_url,
        'js_url' => $js_url
    ]);
    
    // jQuery Colorbox
    wp_register_script('jquery-colorbox', $js_url . 'jquery.colorbox-min.js', array('jquery'), '1.6.4', true);
    
    // Custom scripts
    wp_register_script('dacdb-scripts', $js_url . 'dacdb.js', array('jquery'), dacdbplus_get_version(), true);
    
    // Enqueue the merged script if it exists
    if (file_exists(plugin_dir_path(dirname(__FILE__)) . 'js/dacdb-merged.js')) {
        wp_register_script('dacdb-merged', $js_url . 'dacdb-merged.js', array('jquery'), dacdbplus_get_version(), true);
    }
    
    // Pagination scripts - critical for member directory functionality
    $pagination_path = $plugin_path . 'js/pagination.js';
    $member_pagination_path = $plugin_path . 'js/member-pagination.js';
    
    // Check if pagination.js exists and register it
    if (file_exists($pagination_path)) {
        wp_register_script(
            'twbs-pagination', 
            $js_url . 'pagination.js', 
            array('jquery'), 
            '1.4.1', 
            true
        );
        
        // Log success for debugging
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Successfully registered twbs-pagination from: ' . $js_url . 'pagination.js');
        }
    } else {
        // Log failure for debugging
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus ERROR: Could not find pagination.js at: ' . $pagination_path);
        }
    }
    
    // Check if member-pagination.js exists and register it with proper dependencies
    if (file_exists($member_pagination_path)) {
        wp_register_script(
            'dacdb-member-pagination', 
            $js_url . 'member-pagination.js', 
            array('jquery', 'twbs-pagination'), 
            dacdbplus_get_version(), 
            true
        );
        
        // Log success for debugging
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Successfully registered dacdb-member-pagination from: ' . $js_url . 'member-pagination.js');
        }
    } else {
        // Log failure for debugging
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus ERROR: Could not find member-pagination.js at: ' . $member_pagination_path);
        }
    }
    
    // Colorbox compatibility script
    wp_register_script('colorbox-compatibility', $js_url . 'colorbox-compatibility.js', array('jquery'), dacdbplus_get_version(), true);
    
    // Utility libraries
    wp_register_script('moment2', 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js', array('jquery'), '2.29.4', true);
    wp_register_script('tooltip-js', 'https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js', array('jquery'), null, true);
    
    // DACdb Plus main script
    wp_register_script('dacdb-plus', $js_url . 'dacdb_plus.js', array('jquery'), dacdbplus_get_version(), true);
    
    // Modal link script - always enqueued
    wp_register_script('mmpdbplus-modal', $js_url . 'modal-link.js', array('jquery'), dacdbplus_get_version(), true);
    wp_enqueue_script('mmpdbplus-modal');
}

/**
 * Helper function to check if a specific shortcode variant is used in the current post.
 * Uses first WordPress has_shortcode, then falls back to string detection if needed.
 */
function dacdbplus_has_shortcode($post_content, $show) {
    dacdbplus_queue_console_log('Checking for shortcode: [dacdb_plus show="' . $show . '"]');

    // First check if the dacdb_plus shortcode exists at all
    if (!has_shortcode($post_content, 'dacdb_plus')) {
        dacdbplus_queue_console_log('No [dacdb_plus] shortcode found at all.');
        return false;
    }

    // 1. Try using WordPress's built-in shortcode parsing first
    dacdbplus_queue_console_log('Attempt 1: Using shortcode_parse_atts');
    $pattern = get_shortcode_regex(['dacdb_plus']);
    $found_via_parse_atts = false;
    if (preg_match_all('/' . $pattern . '/s', $post_content, $matches) && !empty($matches[0])) {
        // Check attributes for each shortcode instance
        foreach ($matches[3] as $attr_string) {
            $attrs = shortcode_parse_atts($attr_string);
            dacdbplus_queue_console_log('Parsed attributes: ' . json_encode($attrs));
            // Check if the 'show' attribute exists and matches our value (case-insensitive)
            if (isset($attrs['show']) && strtolower(trim($attrs['show'])) === strtolower(trim($show))) {
                dacdbplus_queue_console_log('Found match for "' . $show . '" using shortcode_parse_atts.');
                $found_via_parse_atts = true;
                break; // Exit loop once found
            }
        }
    }
    if ($found_via_parse_atts) {
        return true;
    }
    dacdbplus_queue_console_log('No match found using shortcode_parse_atts for "' . $show . '".');

    // 2. Fallback to robust regex matching if standard parsing fails or misses variations
    dacdbplus_queue_console_log('Attempt 2: Using fallback regex');
    $escaped_show = preg_quote($show, '/');
    $regex = '/\\[dacdb_plus\\s+[^\]]*\\bshow\\s*=\\s*([\\"\\\']?)' . $escaped_show . '\\1(?:\\s|\\])/i';
    if (preg_match($regex, $post_content)) {
        dacdbplus_queue_console_log('Found match for "' . $show . '" using fallback regex.');
        return true;
    }

    dacdbplus_queue_console_log('No match found for "' . $show . '" using fallback regex.');
    return false;
}

/**
 * Conditionally load assets based on current page content
 */
function dacdbplus_enqueue_conditional_assets() {
    global $post;
    
    // Define URL variables needed for this function
    $plugin_url = plugin_dir_url(dirname(__FILE__));
    $css_url = $plugin_url . 'css/';
    $js_url = $plugin_url . 'js/';
    
    // Only proceed with conditional loading if we're on a singular post/page with content
    if (!is_singular() || !is_a($post, 'WP_Post')) {
        // dacdbplus_queue_console_log('Not a singular post/page or post object unavailable. Skipping conditional assets.');
        return;
    }
    
    dacdbplus_queue_console_log('Running dacdbplus_enqueue_conditional_assets for post ID: ' . $post->ID);

    // Check for member display shortcodes
    if (
        dacdbplus_has_shortcode($post->post_content, 'committees') ||
        dacdbplus_has_shortcode($post->post_content, 'clubleaders') ||
        dacdbplus_has_shortcode($post->post_content, 'committee_leaders') ||
        dacdbplus_has_shortcode($post->post_content, 'd_leaders') ||
        dacdbplus_has_shortcode($post->post_content, 'dcc') ||
        dacdbplus_has_shortcode($post->post_content, 'leaders') ||
        dacdbplus_has_shortcode($post->post_content, 'committee')
    ) {
        wp_enqueue_style('member-cards');
        dacdbplus_queue_console_log('Enqueued member-cards styles.');
    }
    
    // Check for members shortcode using improved detection
    $is_members_shortcode = dacdbplus_has_shortcode($post->post_content, 'members');
    
    // Force direct content check for members with more variations
    if (!$is_members_shortcode) {
        $content = strtolower($post->post_content);
        
        // Check for common variations with different spacing and quote styles
        $members_variations = [
            'show="members"',
            "show='members'",
            'show=members',
            'show = "members"',
            "show = 'members'",
            'show ="members"',
            "show ='members'"
        ];
        
        foreach ($members_variations as $variation) {
            if (strpos($content, $variation) !== false) {
                $is_members_shortcode = true;
                dacdbplus_queue_console_log('Found members shortcode using direct string match: ' . $variation);
                break;
            }
        }
    }
    
    // Last resort - check for a very basic pattern that might be missed by other methods
    if (!$is_members_shortcode && strpos($content, '[dacdb_plus') !== false && strpos($content, 'members') !== false) {
        dacdbplus_queue_console_log('Found potential members shortcode using basic pattern match');
        dacdbplus_queue_console_log('Content contains [dacdb_plus and members somewhere');
        // Set a flag to investigate further but don't auto-enable
        $potential_members_shortcode = true;
    } else {
        $potential_members_shortcode = false;
    }
    
    if ($is_members_shortcode) {
        // Make sure we have the required stylesheet
        wp_enqueue_style('dacdb-show-club-members', $css_url . 'show-club-members.css', array(), dacdbplus_get_version());
        
        // Always ensure jQuery is loaded first
        wp_enqueue_script('jquery');
        
        // Register and enqueue the pagination scripts
        wp_register_script('twbs-pagination', $js_url . 'pagination.js', array('jquery'), '1.4.1', true);
        wp_enqueue_script('twbs-pagination');
        
        wp_register_script('dacdb-member-pagination', $js_url . 'member-pagination.js', array('jquery', 'twbs-pagination'), dacdbplus_get_version(), true);
        wp_enqueue_script('dacdb-member-pagination');
        
        // Add initialization script to footer
        add_action('wp_footer', function() {
            ?>
            <script>
            jQuery(document).ready(function($) {
                // console.log("Initializing pagination...");
                if (typeof window.dacdbMemberPagination !== 'undefined') {
                    // console.log("Pagination data found, total pages: " + window.dacdbMemberPagination.totalPages);
                    if ($.fn.twbsPagination) {
                        // Initialize top pagination if it exists
                        if ($("#pagination-dacdb-top").length > 0) {
                            $("#pagination-dacdb-top").twbsPagination({
                                totalPages: window.dacdbMemberPagination.totalPages || 1,
                                visiblePages: 5,
                                first: '«',
                                prev: '‹',
                                next: '›',
                                last: '»',
                                onPageClick: function (event, page) {
                                    // console.log("Top pagination - Page " + page + " clicked");
                                    window.dacdbMemberPagination.currentPage = page;
                                    // Hide all pages first
                                    $(".page-content").hide();
                                    // Show the selected page
                                    $("#pagsec" + page).show();
                                }
                            });
                        }
                        
                        // Initialize bottom pagination if it exists
                        if ($("#pagination-dacdb-bottom").length > 0) {
                            $("#pagination-dacdb-bottom").twbsPagination({
                                totalPages: window.dacdbMemberPagination.totalPages || 1,
                                visiblePages: 5,
                                first: '«',
                                prev: '‹',
                                next: '›',
                                last: '»',
                                onPageClick: function (event, page) {
                                    // console.log("Bottom pagination - Page " + page + " clicked");
                                    window.dacdbMemberPagination.currentPage = page;
                                    // Hide all pages first
                                    $(".page-content").hide();
                                    // Show the selected page
                                    $("#pagsec" + page).show();
                                }
                            });
                        }
                    } else {
                        console.error("ERROR: twbsPagination plugin not loaded!");
                    }
                } else {
                    // console.log("Pagination data not found");
                }
            });
            </script>
            <?php
        }, 999); // High priority to ensure it runs after other scripts
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued members shortcode assets with script initialization');
            $loaded_styles = array_keys($GLOBALS['wp_styles']->registered);
            $loaded_scripts = array_keys($GLOBALS['wp_scripts']->registered);
            
            error_log('DACdbPlus: show-club-members.css status: ' . 
                     (in_array('dacdb-show-club-members', $loaded_styles) ? 'Registered' : 'Not Registered'));
            error_log('DACdbPlus: pagination.js status: ' . 
                     (in_array('twbs-pagination', $loaded_scripts) ? 'Registered' : 'Not Registered'));
            error_log('DACdbPlus: member-pagination.js status: ' . 
                     (in_array('dacdb-member-pagination', $loaded_scripts) ? 'Registered' : 'Not Registered'));
        }
    }
    
    // Check for stories shortcode
    if (dacdbplus_has_shortcode($post->post_content, 'stories')) {
        wp_enqueue_style('dacdb-stories-style');
        wp_enqueue_style('story-cards');
        wp_enqueue_script('dacdb-plus');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued stories assets');
        }
    }
    
    // Check for calendar or events shortcode
    if (
        dacdbplus_has_shortcode($post->post_content, 'calendar') ||
        dacdbplus_has_shortcode($post->post_content, 'events')
    ) {
        wp_enqueue_style('dacdbplus-colorbox');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued calendar/events assets');
        }
    }
    
    // Check for sponsors shortcode
    if (dacdbplus_has_shortcode($post->post_content, 'sponsors')) {
        wp_enqueue_style('show-sponsors');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued sponsors assets');
        }
    }
    
    // Check for newsletter/newsletters shortcode
    if (
        dacdbplus_has_shortcode($post->post_content, 'newsletter') ||
        dacdbplus_has_shortcode($post->post_content, 'newsletters')
    ) {
        wp_enqueue_style('show-newsletters');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued newsletter assets');
        }
    }
    
    // Check for leaders shortcode
    if (dacdbplus_has_shortcode($post->post_content, 'leaders')) {
        wp_enqueue_style('dacdb-leaders');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued leaders assets');
        }
    }
    
    // Check for birthdays shortcode
    if (dacdbplus_has_shortcode($post->post_content, 'birthdays')) {
        wp_enqueue_style('dacdb-birthdays');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued birthdays assets');
        }
    }
    
    // Check for speakers shortcode
    if (dacdbplus_has_shortcode($post->post_content, 'speakers')) {
        wp_enqueue_style('dacdb-speakers-style');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued speakers assets');
        }
    }

    // Check for documents, newsletter, or dcc shortcode for Colorbox
    if (
        dacdbplus_has_shortcode($post->post_content, 'documents') ||
        dacdbplus_has_shortcode($post->post_content, 'newsletter') ||
        dacdbplus_has_shortcode($post->post_content, 'dcc')
    ) {
        wp_enqueue_script('jquery-colorbox');
        wp_enqueue_style('jquery-colorbox-style');
        wp_enqueue_script('colorbox-compatibility');
        
        // DEBUG - Log enqueuing (admin only)
        if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
            error_log('DACdbPlus: Enqueued colorbox assets');
        }
    }
    
    // Need to ensure Font Awesome is available for certain shortcodes
    dacdbplus_maybe_enqueue_fontawesome();
}

/**
 * Handles conditional Font Awesome loading
 */
function dacdbplus_maybe_enqueue_fontawesome() {
    global $post;
    
    // Only proceed if we're on a singular post/page with content
    if (!is_singular() || !is_a($post, 'WP_Post')) {
        return;
    }
    
    // Check if any of our shortcodes that need Font Awesome are present
    $needs_fontawesome = has_shortcode($post->post_content, 'dacdb_plus') && (
        dacdbplus_has_shortcode($post->post_content, 'calendar') ||
        dacdbplus_has_shortcode($post->post_content, 'stories') ||
        dacdbplus_has_shortcode($post->post_content, 'committees') ||
        dacdbplus_has_shortcode($post->post_content, 'committee')
    );
    
    // If no shortcodes need Font Awesome, return early
    if (!$needs_fontawesome) {
        return;
    }
    
    // If Font Awesome is already loaded, we're good
    if (
        wp_style_is('font-awesome', 'enqueued') ||
        wp_style_is('fontawesome', 'enqueued') ||
        wp_style_is('fontawesome-all', 'enqueued') ||
        wp_style_is('fontawesome-latest', 'enqueued') ||
        wp_style_is('fa', 'enqueued') ||
        wp_style_is('font-awesome-6', 'enqueued') ||
        wp_script_is('font-awesome-kit', 'enqueued')
    ) {
        return;
    }
    
    // Load our own version
    wp_enqueue_style(
        'mmpro-font-awesome',
        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css',
        array(),
        '6.5.1'
    );
    
    // DEBUG - Log Font Awesome enqueuing (admin only)
    if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
        error_log('DACdbPlus: Enqueued Font Awesome');
    }
}

/**
 * Enqueue admin-specific assets
 */
function dacdbplus_admin_assets($hook) {
    $plugin_url = plugin_dir_url(dirname(__FILE__));
    $css_url = $plugin_url . 'css/';
    $js_url = $plugin_url . 'js/';
    
    // Admin-specific CSS
    wp_enqueue_style('dacdb-admin-css', $css_url . 'admin.css', array(), dacdbplus_get_version());
    
    // Admin-specific JavaScript
    wp_enqueue_script('dacdb-admin-js', $js_url . 'admin.js', array('jquery'), dacdbplus_get_version(), true);
}

/**
 * Initialize all enqueuing hooks
 */
function dacdbplus_init_enqueues() {
    // Front-end assets
    add_action('wp_enqueue_scripts', 'dacdbplus_register_styles');
    add_action('wp_enqueue_scripts', 'dacdbplus_register_scripts');
    add_action('wp_enqueue_scripts', 'dacdbplus_enqueue_conditional_assets', 20); // Higher priority to run after registration
    
    // Admin assets
    add_action('admin_enqueue_scripts', 'dacdbplus_admin_assets');
    
    // Add an action that will run after WordPress is fully loaded to log initialization
    add_action('wp_loaded', 'dacdbplus_log_initialization');
}

/**
 * Log initialization info after WordPress is fully loaded
 */
function dacdbplus_log_initialization() {
    // DEBUG - Log initialization (admin only)
    if (is_user_logged_in() && current_user_can('manage_options') && defined('WP_DEBUG') && WP_DEBUG) {
        error_log('DACdbPlus: Enqueuing hooks initialized');
    }
}

// Initialize all enqueuing
dacdbplus_init_enqueues(); 