<?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');

            // 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 (
                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');
            }

            // 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' => '',
                '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
            );

            $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) {
                $pagedata .= $this->generate_debug_info($xml, $atts);
            }
            try {
                $show = strtolower(str_replace(' ', '', $atts['show']));
                $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)
        {
            switch ($show) {
                case 'areas':
                    return dacdb_areas($atts);
                case 'birthdays':
                    return dacdb_birthdays($atts);
                case 'calendar':
                    return mmpro_calendar($atts);
                case 'cog':
                    return dacdb_cog($atts);
                case 'club_meetings':
                    return dacdb_club_meetings($atts);
                case 'club_presidents':
                    return dacdb_club_presidents($atts);
                case 'clubleaders':
                    return dacdb_clubleaders($atts);
                case 'committee':
                    return dacdb_committee($atts);
                case 'committee_leaders':
                    return dacdb_committee_leaders($atts);
                case 'committees':
                    return dacdb_committees($atts);
                case 'events':
                case 'd_events':
                    if ($show === 'd_events') {
                        $atts['type'] = 'district';
                    }
                    return dacdb_events($atts);
                case 'd_leaders':
                    return dacdb_d_leaders($atts);
                case 'dcc':
                    return dacdb_dcc($atts);
                case 'documents':
                    return dacdb_documents($atts);
                case 'leaders':
                    return dacdb_leaders($atts);
                case 'map':
                    return dacdb_map($atts);
                case 'meeting_info':
                    return dacdb_meeting_info($atts);
                case 'members':
                    return dacdb_members($atts);
                case 'newsletter':
                case 'newsletters':
                    return dacdb_newsletter($atts);
                case 'sponsors':
                    return dacdb_sponsors($atts);
                case 'speakers':
                    return dacdb_speakers($atts);
                case 'stories':
                    return dacdb_stories($atts);
                case 'wcm':
                    return dacdb_wcm($atts);
                case 'joinforms':
                    return dacdb_NewMemberFormList($atts);
                case 'ri-theme':
                    return dacdb_riThemeLogo($atts);
                default:
                    throw new InvalidShortcodeException("Invalid shortcode 'show' value encountered: <em>{$show}</em>");
            }
        }
        private function generate_error_message($message)
        {
            return "=================================================================<BR>" .
                $message . "<BR>" .
                "data_path=" . $data_path . "<BR>" .
                "=================================================================<BR>" .
                "<BR>";
        }
        private function generate_subscription_error()
        {
            global $data_path;
            $error = "=================================================================<BR>" .
                "&nbsp; &nbsp;  Missing subscription record. System=" . $this->options['dacdb_system'] .
                ", AccountID=" . $this->options['dacdb_district'] .
                ", ClubID=" . $this->options['dacdb_club'] . "<BR>" .
                "&nbsp; &nbsp;  Please contact: support@memberminderpro.com<BR>" .
                "data_path=" . $data_path . "<br>" .
                "subscription=" . $xml->status . "<br>" .
                "ip_server=" . $_SERVER['SERVER_ADDR'] . "<br>" .
                "php version=" . phpversion() . "<br>";
            if (\filter_var(\ini_get('allow_url_fopen'), \FILTER_VALIDATE_BOOLEAN)) {
                $error .= "allow_url_fopen is configured properly in php.ini<br>";
            } else {
                $error .= "allow_url_fopen is NOT configured properly in php.ini<br>";
            }
            $error .= "=================================================================<BR><BR>";
            return $error;
        }
        private function generate_debug_info($xml, $atts)
        {
            $districtOrAccount = $this->options['dacdb_system'] == 'dacdb' ? 'District' : 'Account';
            return '
          <div class="debug">
              <div class="info-msg"><i class="fa fa-info-circle"></i> <strong>Debug mode <em>ON</em></strong></div>
              <h5>' . dacdb_debug_shortcode($GLOBALS['post'], $atts) . '</h5>
              <pre>
                  <dl>
                      <dt>Plugin Version</dt><dd>' . MMPDB_PLUGIN_VERSION . '</dd>
                      <dt>' . $districtOrAccount . ' ID</dt><dd>' . $this->options['dacdb_district'] . '</dd>
                      <dt>Club ID</dt><dd>' . $this->options['dacdb_club'] . '</dd>
                      <dt>System</dt><dd>' . (isset($this->options['dacdb_system']) ? $this->options['dacdb_system'] : 'Not set') . '</dd>
                      <dt>CatID</dt><dd>' . (isset($GLOBALS['catid']) && $GLOBALS['catid'] !== '' ? $GLOBALS['catid'] : 'Not set') . '</dd>
                      <dt>data_path</dt><dd>' . (isset($data_path) ? $data_path : 'Not set') . '</dd>
                      <dt>file_path</dt><dd>' . (isset($file_path) ? $file_path : 'Not set') . '</dd>
                      <dt>public_path</dt><dd>' . (isset($GLOBALS['public_path']) && $GLOBALS['public_path'] !== '' ? $GLOBALS['public_path'] : 'Not set') . '</dd>
                      <dt>subscription</dt><dd>' . (isset($xml->status) ? $xml->status : 'Not set') . '</dd>
                      <dt>ip_server</dt><dd>' . (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 'Not set') . '</dd>
                      <dt>php version</dt><dd>' . (null !== phpversion() ? phpversion() : 'Not set') . '</dd>
                  </dl>
              </pre>
          </div>';
        }
    }
}
//!SECTION - Class dacdb_plus