<?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 __construct()
        {
            $this->options = get_mmp_options();

            // Restore widget registration
            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', array($this, 'maybe_enqueue_fontawesome'));
        }

        public function enqueue_resources()
        {
            global $post;
            
            // First check and enqueue jQuery (WordPress core)
            wp_enqueue_script('jquery');

            // 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 FullCalendar with proper dependencies
            wp_register_script(
                'fullcalendar',
                plugins_url('js/index.global.js', dirname(__FILE__)),
                array('jquery', 'moment2'),
                MMPDB_PLUGIN_VERSION,
                true
            );

            // Plugin-specific scripts with proper dependencies
            wp_enqueue_script('dacdb-calendar', 
                MMPDB_PLUGIN_URL . 'js/show-calendar.js', 
                array('jquery', 'jquery-colorbox', 'popper', 'tooltip-js', 'fullcalendar'), 
                MMPDB_PLUGIN_VERSION, 
                true
            );

            // Plugin-specific styles with proper dependencies
            wp_enqueue_style('show-stories', MMPDB_PLUGIN_URL . 'css/show-stories.css', array('dacdb-bootstrap'), MMPDB_PLUGIN_VERSION);

            // Add speakers styles if shortcode is present
            if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'dacdb_plus')) {
                // Check if any shortcode instance has show="speakers"
                if (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 . 'r' . rand(1, 1000000) // Add a random number to the version to force a cache refresh
                    );
                }
            }

            // FontAwesome handling - ensure both solid and brands styles are loaded
            if (
                is_a($post, 'WP_Post') &&
                (has_shortcode($post->post_content, 'dacdb_plus') ||
                    has_shortcode($post->post_content, 'dacdb_stories'))
            ) {
                if (!wp_style_is('fontawesome-all', 'enqueued')) {
                    // Register and enqueue Font Awesome CSS files in correct order
                    wp_register_style(
                        'fontawesome-all',
                        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css',
                        array(),
                        '6.4.2'
                    );
                    wp_register_style(
                        'fontawesome-solid',
                        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/solid.min.css',
                        array('fontawesome-all'),
                        '6.4.2'
                    );
                    wp_register_style(
                        'fontawesome-brands',
                        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/brands.min.css',
                        array('fontawesome-all'),
                        '6.4.2'
                    );
                    
                    wp_enqueue_style('fontawesome-all');
                    wp_enqueue_style('fontawesome-solid');
                    wp_enqueue_style('fontawesome-brands');
                }
            }

            // Add UserWay script if configured
            if (isset($this->options['userway_data_account']) && !empty($this->options['userway_data_account'])) {
                add_action('wp_head', array($this, 'add_userway_script_to_head'));
            }

            // Add back core scripts
            wp_enqueue_script('dacdb-plus-js', MMPDB_PLUGIN_URL . 'js/dacdb_plus.js', array('jquery'), MMPDB_PLUGIN_VERSION, true);
            wp_enqueue_script('pagination', MMPDB_PLUGIN_URL . 'js/pagination.js', array('jquery'), MMPDB_PLUGIN_VERSION, true);
        }

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

        // Method to conditionally enqueue FontAwesome based on shortcode presence
        public function maybe_enqueue_fontawesome()
        {
            global $post;
            if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'dacdb_plus')) {
                add_action('wp_enqueue_scripts', array($this, 'enqueue_fontawesome'));
            }
        }

        public function enqueue_fontawesome()
        {
            if (!wp_style_is('font-awesome', 'enqueued') && !wp_style_is('dacdb-fontawesome', 'enqueued')) {
                // Use Font Awesome Kit if configured
                if (!empty($this->options['fontawesome_kit'])) {
                    wp_enqueue_script(
                        'fontawesome-kit',
                        'https://kit.fontawesome.com/' . $this->options['fontawesome_kit'] . '.js',
                        array(),
                        null,
                        true
                    );
                } else {
                    // Otherwise use CDN
                    wp_enqueue_style(
                        'fontawesome',
                        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css',
                        array(),
                        '6.4.2'
                    );
                }
            }
        }

        //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)
        {
            try {
                switch ($show) {
                    case 'areas':
                        return dacdb_areas($atts);
                    case 'birthdays':
                        return dacdb_birthdays($atts);
                    case 'calendar':
                        return dacdb_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>");
                }
            } catch (Exception $e) {
                return "<div class=\"error-msg\"><i class=\"fa fa-times-circle\"></i>{$e->getMessage()}</div>";
            }
        }

        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>';
        }

        // Add back the widget registration function
        public function dacdb_plus_register() {
            register_widget('DACDB_Plus_Widget');
        }

        public function dacdb_plus_js() {
            // Keep for backward compatibility
            wp_enqueue_script('dacdb-plus-js', plugins_url('js/dacdb_plus.js', __FILE__), array('jquery'), MMPDB_PLUGIN_VERSION, true);
        }
    }
}
//!SECTION - Class dacdb_plus