<?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');
            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'));
            
            // Admin scripts
            add_action('admin_enqueue_scripts', array($this, 'dacdb_plus_admin_js'));
            
            // Asset enqueuing is handled by includes/enqueue.php
        }
        
        // 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;
        }

        //ANCHOR - Process Shortcode
        public function dacdb_plus_function($atts)
        {
            global $public_path, $fDebug, $data_path, $file_path, $options;
            
            if (defined('WP_DEBUG') && WP_DEBUG === true) {
                error_log('DACdb Plus: Main shortcode function called with: ' . print_r($atts, true));
            }
            
            // 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
                'wk' => 0,                  // Added for events shortcode
                'show_members' => '',       // Added for committee shortcode
                'members' => '',            // Alternative for show_members
                'name' => '',               // Added for committee shortcode
                'accountid' => '',          // Added for committee shortcode
                'district' => '',           // Alternative for accountid
                'grandlodge' => '',         // Alternative for accountid
                'entityname' => '',         // Added for committee shortcode
                'lodgename' => '',          // Alternative for entityname
                'clubname' => '',           // Alternative for entityname
                'chaptername' => '',        // Alternative for entityname
                'pics' => '',               // Added for committee shortcode
                'contact' => '',            // Added for committee shortcode
                'committeeposition' => '',  // Added for committee shortcode
                'busposition' => '',        // Added for committee shortcode
                'classification' => '',     // Added for committee shortcode
                'leaders' => '',            // Added for committee shortcode
                'show_leaders' => '',       // Alternative for leaders
                'imgheight' => '',          // Added for committee shortcode
                'sector' => ''              // Added for calendar sector filtering
            );

            $original_atts = $atts; // Save original attributes
            $atts = shortcode_atts($defaults, $atts, 'dacdb_plus');
            
            // Use a unique identifier for each shortcode instance to avoid conflicts
            $shortcode_id = uniqid('dacdb_plus_', true);
            $GLOBALS['dacdb_plus_original_atts_' . $shortcode_id] = $original_atts;
            $GLOBALS['dacdb_plus_current_shortcode_id'] = $shortcode_id;
            $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 using the robust utility function
            $subscription_url = $data_path . 'wp_subscription2.cfm?AccountID=' . $options['dacdb_district'] . '&ClubID=' . $options['dacdb_club'];
            $xml = dacdb_load_xml($subscription_url, 'subscription');
            
            if ($xml === false) {
                return $this->generate_subscription_error();
            }
            
            $int = (int) $xml->status;
            if ($int != 1) {
                if (defined('WP_DEBUG') && WP_DEBUG === true) {
                    error_log('DACdb Plus: Subscription status is not 1. Status: ' . $int);
                }
                return $this->generate_subscription_error();
            }

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

            try {
                // Normalize the show attribute for better flexibility
                $show = strtolower(trim(str_replace(' ', '', $atts['show'])));
                
                // Check if show attribute is empty
                if (empty($show)) {
                    return '<div class="error-msg"><i class="fa fa-times-circle"></i>The "show" attribute is required (e.g., [dacdb_plus show="members"]).</div>';
                }
                
                // Valid show values (must match the cases in process_shortcode)
                $valid_shows = [
                    'areas', 'birthdays', 'calendar', 'cog', 'club_meetings', 'club_presidents',
                    'clubleaders', 'committee', 'committee_leaders', 'committees', 'events',
                    'd_events', 'd_leaders', 'dcc', 'documents', 'leaders', 'map', 'meeting_info',
                    'members', 'newsletter', 'newsletters', 'sponsors', 'speakers', 'stories',
                    'wcm', 'joinforms', 'ri-theme'
                ];
                
                // Validate show attribute value
                if (!in_array($show, $valid_shows)) {
                    return '<div class="error-msg"><i class="fa fa-times-circle"></i>Invalid "show" attribute value: <em>' . esc_html($show) . '</em>. Valid values include: members, events, calendar, stories, etc.</div>';
                }
                
                // 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>";
            }

            // Clean up global variables to prevent memory leaks
            if (isset($GLOBALS['dacdb_plus_current_shortcode_id'])) {
                $shortcode_id = $GLOBALS['dacdb_plus_current_shortcode_id'];
                unset($GLOBALS['dacdb_plus_original_atts_' . $shortcode_id]);
                unset($GLOBALS['dacdb_plus_current_shortcode_id']);
            }

            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':
                    if (defined('WP_DEBUG') && WP_DEBUG === true) {
                        error_log('DACdb Plus: Calendar shortcode called with attributes: ' . print_r($atts, true));
                        error_log('DACdb Plus: About to call mmpro_calendar function');
                        error_log('DACdb Plus: Function exists: ' . (function_exists('mmpro_calendar') ? 'YES' : 'NO'));
                        error_log('DACdb Plus: Sector attribute check - isset: ' . (isset($atts['sector']) ? 'YES' : 'NO'));
                        error_log('DACdb Plus: Sector attribute check - empty: ' . (empty($atts['sector']) ? 'YES' : 'NO'));
                        if (isset($atts['sector'])) {
                            error_log('DACdb Plus: Sector value being passed: "' . $atts['sector'] . '"');
                        }
                    }
                    $output .= mmpro_calendar($atts);
                    if (defined('WP_DEBUG') && WP_DEBUG === true) {
                        error_log('DACdb Plus: mmpro_calendar function completed');
                    }
                    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()
        {
            $subscription_url = ($GLOBALS['data_path'] ?? '') . 'wp_subscription2.cfm?AccountID=' . ($this->options['dacdb_district'] ?? '') . '&ClubID=' . ($this->options['dacdb_club'] ?? '');
            
            $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>Subscription URL: <a href="%s" target="_blank">%s</a></li>
                        <li>Server IP: %s</li>
                        <li>PHP Version: %s</li>
                        <li>allow_url_fopen: %s</li>
                        <li>OpenSSL: %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_url($subscription_url),
                esc_html($subscription_url),
                esc_html($_SERVER['SERVER_ADDR'] ?? 'Not set'),
                esc_html(phpversion()),
                esc_html(filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN) ? 'Enabled' : 'Disabled'),
                esc_html(extension_loaded('openssl') ? 'Enabled (v' . OPENSSL_VERSION_TEXT . ')' : '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