<?php
//SECTION - Class dacdb_plus
if (!class_exists('dacdb_plus')) {
    /**
     * Class dacdb_plus
     *
     * Description: This class defines a plugin called 'dacdb_plus' with various methods and functions.
     */
    class dacdb_plus
    {
        protected $options;
        function dacdb_plus_register()
        {
            register_widget('DACDB_Plus_Widget');
        }
        function __construct()
        {
            $this->options = get_mmp_options();
            //Register Plugin
            add_action('widgets_init', array($this, 'dacdb_plus_register'));
            //Add Core Functionality Shortcode
            add_shortcode('dacdb_plus', array($this, 'dacdb_plus_function'));
            // Add JavaScript Files
            add_action('wp_enqueue_scripts', array($this, 'enqueue_resources')); // Front-end scripts
            add_action('admin_enqueue_scripts', array($this, 'dacdb_plus_admin_js')); // Admin scripts
            // Handle FontAwesome loading
            add_action('wp_enqueue_scripts', array($this, 'maybe_enqueue_fontawesome'));
        }
        public function enqueue_resources()
        {
            global $post;

            // Register Moment.js
            wp_register_script(
                'moment2',
                'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js',
                array('jquery'),
                '2.29.4',
                true
            );

            // Register Popper.js and Tooltip.js
            wp_register_script(
                'popper',
                'https://unpkg.com/popper.js/dist/umd/popper.min.js',
                array('jquery'),
                null,
                true
            );
            wp_register_script(
                'tooltip-js',
                'https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js',
                array('jquery', 'popper'),
                null,
                true
            );

            // Bootstrap handling - register first, then enqueue
            if (!wp_style_is('dacdb-bootstrap', 'registered')) {
                wp_register_style(
                    'dacdb-bootstrap',
                    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
                    array(),
                    '5.3.0'
                );
                wp_register_script(
                    'dacdb-bootstrap',
                    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js',
                    array('jquery'),
                    '5.3.0',
                    true
                );
            }
            wp_enqueue_style('dacdb-bootstrap');
            wp_enqueue_script('dacdb-bootstrap');

            // Register and enqueue main plugin JavaScript
            wp_register_script(
                'dacdb-plus-js',
                MMPDB_PLUGIN_URL . 'js/dacdb_plus.js',
                array('jquery'),
                MMPDB_PLUGIN_VERSION,
                true
            );
            wp_enqueue_script('dacdb-plus-js');

            // Register pagination scripts if needed
            if (
                is_a($post, 'WP_Post') &&
                has_shortcode($post->post_content, 'dacdb_plus') &&
                strpos($post->post_content, '[dacdb_plus show="members"') !== false
            ) {
                // Register pagination scripts
                wp_register_script(
                    'twbs-pagination',
                    MMPDB_PLUGIN_URL . 'js/pagination.js',
                    array('jquery'),
                    '1.4.1',
                    true
                );
                wp_register_script(
                    'dacdb-member-pagination',
                    MMPDB_PLUGIN_URL . 'js/member-pagination.js',
                    array('jquery', 'twbs-pagination'),
                    MMPDB_PLUGIN_VERSION,
                    true
                );

                // Enqueue pagination scripts
                wp_enqueue_script('twbs-pagination');
                wp_enqueue_script('dacdb-member-pagination');
            }

            // ColorBox handling with proper registration
            if (!wp_script_is('jquery-colorbox', 'registered')) {
                $colorbox_cdn_js = 'https://cdn.jsdelivr.net/gh/jackmoore/colorbox@1.6.4/jquery.colorbox-min.js';
                $colorbox_cdn_css = 'https://cdn.jsdelivr.net/gh/jackmoore/colorbox@1.6.4/example1/colorbox.css';

                if ($this->url_exists($colorbox_cdn_js) && $this->url_exists($colorbox_cdn_css)) {
                    wp_register_script('jquery-colorbox', $colorbox_cdn_js, array('jquery'), '1.6.4', true);
                    wp_register_style('jquery-colorbox-style', $colorbox_cdn_css, array(), '1.6.4');
                } else {
                    wp_register_script('jquery-colorbox', MMPDB_PLUGIN_URL . 'js/vendor/jquery.colorbox-min.js', array('jquery'), '1.6.4', true);
                    wp_register_style('jquery-colorbox-style', MMPDB_PLUGIN_URL . 'css/vendor/colorbox.css', array(), '1.6.4');
                }

                wp_enqueue_script('jquery-colorbox');
                wp_enqueue_style('jquery-colorbox-style');
            }

            // Register css/display/member-cards.css
            if (
                is_a($post, 'WP_Post') &&
                has_shortcode($post->post_content, 'dacdb_plus') &&
                (strpos($post->post_content, '[dacdb_plus show="committees"') !== false)
            ) {
                wp_register_style(
                    'member-cards',
                    MMPDB_PLUGIN_URL . 'css/display/member-cards.css',
                    array('dacdb-bootstrap', 'dacdb-main'),
                    MMPDB_PLUGIN_VERSION
                );
                wp_enqueue_style('member-cards');
            }

            // Register css/display/story-cards.css
            if (
                is_a($post, 'WP_Post') &&
                has_shortcode($post->post_content, 'dacdb_plus') &&
                strpos($post->post_content, '[dacdb_plus show="stories"') !== false
            ) {
                wp_register_style(
                    'story-cards',
                    MMPDB_PLUGIN_URL . 'css/display/story-cards.css',
                    array('dacdb-bootstrap'),
                    MMPDB_PLUGIN_VERSION
                );
                wp_enqueue_style('story-cards');
            }

            // Check if we're on a page with our shortcodes
            if (is_a($post, 'WP_Post')) {
                // Stories-specific resources
                if (
                    has_shortcode($post->post_content, 'dacdb_plus') &&
                    strpos($post->post_content, '[dacdb_plus show="stories"') !== false
                ) {
                    wp_enqueue_style(
                        'dacdb-stories-style',
                        MMPDB_PLUGIN_URL . 'css/show-stories.css',
                        array('dacdb-bootstrap'),
                        MMPDB_PLUGIN_VERSION
                    );
                }

                // Speakers-specific resources
                if (
                    has_shortcode($post->post_content, 'dacdb_plus') &&
                    strpos($post->post_content, '[dacdb_plus show="speakers"') !== false
                ) {
                    wp_enqueue_style(
                        'dacdb-speakers-style',
                        MMPDB_PLUGIN_URL . 'css/show-speakers.css',
                        array('dacdb-bootstrap'),
                        MMPDB_PLUGIN_VERSION
                    );
                }

            }
        }
        // Helper function to check if a URL exists
        private function url_exists($url)
        {
            $headers = @get_headers($url);
            return $headers && strpos($headers[0], '200') !== false;
        }
        public function add_userway_script_to_head()
        {
            if (isset($this->options['userway_data_account']) && !empty($this->options['userway_data_account'])) {
                printf(
                    '<script src="https://cdn.userway.org/widget.js" data-account="%s"></script>',
                    esc_attr($this->options['userway_data_account'])
                );
            }
        }
        public static function activate()
        {
            // Do nothing plugin does not use WordPress classes or functions
        }
        public static function deactivate()
        {
            // Do nothing plugin does not use WordPress classes or functions
        }
        public function dacdb_plus_admin_js()
        {
            wp_enqueue_script('dacdb-admin-js', MMPDB_PLUGIN_URL . 'js/admin.js', array('jquery'), MMPDB_PLUGIN_VERSION, true);
        }

        private function get_fontawesome_version()
        {
            // Check for various FontAwesome style/script handles and get their versions
            $fa_handles = array(
                'font-awesome',
                'fontawesome',
                'fontawesome-all',
                'fontawesome-latest',
                'fa',
                'font-awesome-6'
            );

            foreach ($fa_handles as $handle) {
                if (wp_style_is($handle, 'registered')) {
                    $style = wp_styles()->registered[$handle];
                    if (isset($style->ver)) {
                        return $style->ver;
                    }
                }
            }

            // Check for kit version
            if (wp_script_is('font-awesome-kit', 'registered')) {
                return wp_scripts()->registered['font-awesome-kit']->ver;
            }

            return false;
        }

        private function is_fontawesome_loaded()
        {
            // First check if any version is loaded
            $loaded = (
                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')
            );

            if (!$loaded) {
                return false;
            }

            // If loaded, check version compatibility
            $loaded_version = $this->get_fontawesome_version();
            if ($loaded_version) {
                // Parse major version number
                $major_version = intval($loaded_version);
                // We need at least version 6
                if ($major_version >= 6) {
                    return true;
                }
            }

            return false;
        }

        public function 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') && (
                strpos($post->post_content, '[dacdb_plus show="calendar"') !== false ||
                strpos($post->post_content, '[dacdb_plus show="stories"') !== false ||
                strpos($post->post_content, '[dacdb_plus show="committees"') !== false ||
                strpos($post->post_content, '[dacdb_plus show="committee"') !== false
            );

            // If no shortcodes need Font Awesome, return early
            if (!$needs_fontawesome) {
                return;
            }

            // If Font Awesome 6+ is already loaded, we're good
            if ($this->is_fontawesome_loaded()) {
                return;
            }

            // If we have a kit ID configured, use that
            if (!empty($this->options['fontawesome_kit'])) {
                wp_enqueue_script(
                    'mmpro-font-awesome-kit',
                    'https://kit.fontawesome.com/' . esc_attr($this->options['fontawesome_kit']) . '.js',
                    array(),
                    '6.5.1',
                    array('strategy' => 'defer')
                );
            } else {
                // Load our own namespaced version with a prefix to avoid conflicts
                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'
                );

                // Add CSS to scope FontAwesome to our plugin's elements using simpler approach
                wp_add_inline_style('mmpro-font-awesome', '
                  /* Ensure proper font loading for all icon types */
                  .mmpro-committees__members-link i {
                      font-family: "Font Awesome 6 Pro", "Font Awesome 6 Free", "FontAwesome";
                      display: inline-block;
                      vertical-align: middle;
                  }
                  
                  /* Ensure icon visibility */
                  .mmpro-committees__members-link i.fa {
                      width: auto;
                      height: auto;
                  }
              ');
            }
        }
        //ANCHOR - Process Shortcode
        public function dacdb_plus_function($atts)
        {
            global $public_path, $fDebug, $data_path, $file_path, $options;
            // Handle Shortcode Attributes
            $defaults = array(
                'show' => '',
                'storyid' => '',
                'catid' => '',
                'catids' => '',
                'separator' => '',
                'display' => '',            // removed
                'pagetitle' => '',          // added
                'org' => '',                // depreciated
                'orgyear' => '',
                'description' => '',
                'imgwidth' => '',
                'folder' => '',             // for documents
                'sort' => '',               // where clubs meet
                'cid' => '',
                'row' => '',
                'rows' => '',               // Alternative for row
                'cols' => '',               // Number of columns for committee display
                'style' => '',              // New
                'icon' => 1,
                'size' => 1,
                'date' => 1,
                'club_id' => '',            // Display club calendar on district website
                'mailto' => '',
                'show_headline' => 1,       // added
                'headline' => '',           // added
                'story_output_style' => 0,  // added
                'story_summary' => 0,       // added
                'story_sep' => 0,           // added
                'story_image' => 0,         // added
                'story_open' => 0,          // added
                'story_share' => 1,         // added
                'story_social' => 0,        // added
                'story_limit' => 0,         // added
                'theme' => '',              // RI Theme Logo Color
                'columns' => '',            // Added for club_presidents shortcode
                'per_row' => '',            // Alternative name for columns
                'presidents_per_row' => '', // Legacy attribute for columns
                'club_presidents_per_row' => '', // Legacy attribute for columns
                'rolekeys' => '',           // Added for clubleaders shortcode
                'leaders_per_row' => null     // Added for clubleaders shortcode
            );

            $atts = shortcode_atts($defaults, $atts, 'dacdb_plus');
            $pagedata = "";     // Output for shortcode needs to be returned
            $options = get_mmp_options();
            setDataPath();   // ShortCode DACdb or iMembersDB paths

            if ($data_path == '') {
                return $this->generate_error_message("Missing System selection under Plugin Settings!");
            }

            // Verify subscription
            $xml = simplexml_load_file($data_path . 'wp_subscription2.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club']);
            $int = (int) $xml->status;
            if ($int != 1) {
                return $this->generate_subscription_error();
            }

            // Debug information if enabled
            if ($fDebug && dacdb_is_admin()) {
                $pagedata .= $this->generate_debug_info($xml, $atts);
            }

            try {
                $show = strtolower(str_replace(' ', '', $atts['show']));
                
                // If this is a members shortcode, pre-fetch the member data to set pagination
                if ($show === 'members') {
                    $membertypes = isset($atts['membertypes']) ? $atts['membertypes'] : $options['membertypes'];
                    $member_xml = simplexml_load_file($data_path . 'wp_club_members.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'] . '&MemberTypeIDs=' . $membertypes . '&R=' . rand());
                    
                    if ($member_xml && strlen($member_xml) > 0) {
                        $pag_total = count($member_xml->member);
                        $pag_pages = ceil($pag_total / $options['mem_per_page']);
                        
                        // Store pagination data in global variable
                        $GLOBALS['dacdb_member_pagination_data'] = array(
                            'totalPages' => (int)$pag_pages,
                            'debug' => true,
                            'currentPage' => 1
                        );
                    }
                }
                
                $pagedata .= $this->process_shortcode($show, $atts);
            } catch (InvalidShortcodeException $e) {
                $pagedata .= "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>{$e->getMessage()}</div>";
            }

            return $pagedata;
        }
        private function process_shortcode($show, $atts)
        {
            $output = '';
            
            // If this is a members shortcode, add pagination container and data
            if ($show === 'members') {
                // Get pagination data if available
                $pagination_data = isset($GLOBALS['dacdb_member_pagination_data']) 
                    ? $GLOBALS['dacdb_member_pagination_data']
                    : array(
                        'totalPages' => 1,
                        'debug' => true,
                        'currentPage' => 1
                    );

                // Add pagination container and data
                $output .= '<div id="dacdb-member-pagination-container"></div>';
                $output .= '<script type="text/javascript">';
                $output .= 'window.dacdbMemberPagination = ' . json_encode($pagination_data) . ';';
                $output .= 'console.log("Pagination data:", window.dacdbMemberPagination);';
                $output .= '</script>';
            }

            switch ($show) {
                case 'areas':
                    $output .= dacdb_areas($atts);
                    break;
                case 'birthdays':
                    $output .= dacdb_birthdays($atts);
                    break;
                case 'calendar':
                    $output .= mmpro_calendar($atts);
                    break;
                case 'cog':
                    $output .= dacdb_cog($atts);
                    break;
                case 'club_meetings':
                    $output .= dacdb_club_meetings($atts);
                    break;
                case 'club_presidents':
                    $output .= dacdb_club_presidents($atts);
                    break;
                case 'clubleaders':
                    $output .= dacdb_clubleaders($atts);
                    break;
                case 'committee':
                    $output .= dacdb_committee($atts);
                    break;
                case 'committee_leaders':
                    $output .= dacdb_committee_leaders($atts);
                    break;
                case 'committees':
                    $output .= dacdb_committees($atts);
                    break;
                case 'events':
                case 'd_events':
                    if ($show === 'd_events') {
                        $atts['type'] = 'district';
                    }
                    $output .= dacdb_events($atts);
                    break;
                case 'd_leaders':
                    $output .= dacdb_d_leaders($atts);
                    break;
                case 'dcc':
                    $output .= dacdb_dcc($atts);
                    break;
                case 'documents':
                    $output .= dacdb_documents($atts);
                    break;
                case 'leaders':
                    $output .= dacdb_leaders($atts);
                    break;
                case 'map':
                    $output .= dacdb_map($atts);
                    break;
                case 'meeting_info':
                    $output .= dacdb_meeting_info($atts);
                    break;
                case 'members':
                    $output .= dacdb_members($atts);
                    break;
                case 'newsletter':
                case 'newsletters':
                    $output .= dacdb_newsletter($atts);
                    break;
                case 'sponsors':
                    $output .= dacdb_sponsors($atts);
                    break;
                case 'speakers':
                    $output .= dacdb_speakers($atts);
                    break;
                case 'stories':
                    $output .= dacdb_stories($atts);
                    break;
                case 'wcm':
                    $output .= dacdb_wcm($atts);
                    break;
                case 'joinforms':
                    $output .= dacdb_NewMemberFormList($atts);
                    break;
                case 'ri-theme':
                    $output .= dacdb_riThemeLogo($atts);
                    break;
                default:
                    throw new InvalidShortcodeException("Invalid shortcode 'show' value encountered: <em>{$show}</em>");
            }

            return $output;
        }
        private function generate_error_message($message)
        {
            return sprintf(
                '<div class="notice notice-error is-dismissible">
                    <p><span class="dashicons dashicons-warning"></span> %s</p>
                    <p><code>data_path=%s</code></p>
                </div>',
                esc_html($message),
                esc_html($GLOBALS['data_path'] ?? 'Not set')
            );
        }
        private function generate_subscription_error()
        {
            $error_message = sprintf(
                '<div class="notice notice-error is-dismissible">
                    <p><span class="dashicons dashicons-warning"></span> Missing subscription record:</p>
                    <ul>
                        <li>System: %s</li>
                        <li>Account ID: %s</li>
                        <li>Club ID: %s</li>
                    </ul>
                    <p>Please contact: <a href="mailto:support@memberminderpro.com">support@memberminderpro.com</a></p>
                    <p><strong>Debug Information:</strong></p>
                    <ul>
                        <li>Data Path: %s</li>
                        <li>Server IP: %s</li>
                        <li>PHP Version: %s</li>
                        <li>allow_url_fopen: %s</li>
                    </ul>
                </div>',
                esc_html($this->options['dacdb_system'] ?? 'Not set'),
                esc_html($this->options['dacdb_district'] ?? 'Not set'),
                esc_html($this->options['dacdb_club'] ?? 'Not set'),
                esc_html($GLOBALS['data_path'] ?? 'Not set'),
                esc_html($_SERVER['SERVER_ADDR'] ?? 'Not set'),
                esc_html(phpversion()),
                esc_html(filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN) ? 'Enabled' : 'Disabled')
            );

            return $error_message;
        }
        private function generate_debug_info($xml, $atts)
        {
            $districtOrAccount = $this->options['dacdb_system'] == 'dacdb' ? 'District' : 'Account';
            return sprintf(
                '<div class="notice notice-info is-dismissible">
                    <p><span class="dashicons dashicons-info"></span> <strong>Debug mode <em>ON</em></strong></p>
                    <h5>%s</h5>
                    <dl>
                        <dt>Plugin Version</dt><dd>%s</dd>
                        <dt>%s ID</dt><dd>%s</dd>
                        <dt>Club ID</dt><dd>%s</dd>
                        <dt>System</dt><dd>%s</dd>
                        <dt>CatID</dt><dd>%s</dd>
                        <dt>data_path</dt><dd>%s</dd>
                        <dt>file_path</dt><dd>%s</dd>
                        <dt>public_path</dt><dd>%s</dd>
                        <dt>subscription</dt><dd>%s</dd>
                        <dt>ip_server</dt><dd>%s</dd>
                        <dt>php version</dt><dd>%s</dd>
                    </dl>
                </div>',
                dacdb_debug_shortcode($GLOBALS['post'], $atts),
                MMPDB_PLUGIN_VERSION,
                esc_html($districtOrAccount),
                esc_html($this->options['dacdb_district']),
                esc_html($this->options['dacdb_club']),
                esc_html($this->options['dacdb_system'] ?? 'Not set'),
                esc_html($GLOBALS['catid'] ?? 'Not set'),
                esc_html($GLOBALS['data_path'] ?? 'Not set'),
                esc_html($GLOBALS['file_path'] ?? 'Not set'),
                esc_html($GLOBALS['public_path'] ?? 'Not set'),
                esc_html($xml->status ?? 'Not set'),
                esc_html($_SERVER['SERVER_ADDR'] ?? 'Not set'),
                esc_html(phpversion())
            );
        }
    }
}
//!SECTION - Class dacdb_plus