<?php//If this file is called directly,abort. if (!defined('WPINC')){die}function cptc_register_custom_post_type(){$labels=array('name'=> _x('Help Posts','Help Portal Posts','text_domain'),'singular_name'=> _x('Help Post','Help Portal Post','text_domain'),'menu_name'=> __('Help Portal Posts','text_domain'),'name_admin_bar'=> __('Help Portal Posts','text_domain'),'archives'=> __('Help Post Archives','text_domain'),'attributes'=> __('Help Post Attributes','text_domain'),'parent_item_colon'=> __('Parent Help Post:','text_domain'),'all_items'=> __('All Help Posts','text_domain'),'add_new_item'=> __('Add New Help Post','text_domain'),'add_new'=> __('Add New','text_domain'),'new_item'=> __('New Help Post','text_domain'),'edit_item'=> __('Edit Help Post','text_domain'),'update_item'=> __('Update Help Post','text_domain'),'view_item'=> __('View Help Post','text_domain'),'view_items'=> __('View Help Posts','text_domain'),'search_items'=> __('Search Help Post','text_domain'),'not_found'=> __('Not found','text_domain'),'not_found_in_trash'=> __('Not found in Trash','text_domain'),'featured_image'=> __('Featured Image','text_domain'),'set_featured_image'=> __('Set featured image','text_domain'),'remove_featured_image'=> __('Remove featured image','text_domain'),'use_featured_image'=> __('Use as featured image','text_domain'),'insert_into_item'=> __('Insert into Help Post','text_domain'),'uploaded_to_this_item'=> __('Uploaded to this Help Post','text_domain'),'items_list'=> __('Help Posts list','text_domain'),'items_list_navigation'=> __('Help Posts list navigation','text_domain'),'filter_items_list'=> __('Filter Help Posts list','text_domain'),);$args=array('label'=> __('Help Post','text_domain'),'description'=> __('Help Post type with same structure as posts','text_domain'),'labels'=> $labels,'supports'=> array('title','editor','excerpt','author','thumbnail','comments','revisions','custom-fields','trackbacks'),'taxonomies'=> array('category','post_tag'),'hierarchical'=> false,'public'=> true,'show_ui'=> true,'show_in_menu'=> true,'menu_position'=> 5,'menu_icon'=> 'dashicons-admin-post','show_in_admin_bar'=> true,'show_in_nav_menus'=> true,'can_export'=> true,'has_archive'=> true,'exclude_from_search'=> false,'publicly_queryable'=> true,'capability_type'=> 'post','show_in_rest'=> true,//Enable Gutenberg editor);register_post_type('custom_post',$args)}add_action('init','cptc_register_custom_post_type');function cptc_wpml_compatibility(){//Make sure WPML is active if (function_exists('icl_object_id')){//Register the custom post type for translation if (function_exists('icl_register_string')){//For older versions of WPML global $sitepress;if ($sitepress){$sitepress->set_setting('custom_posts_sync_option',array('custom_post'=> 1),true)}}else if (function_exists('wpml_register_single_string')){//For newer versions of WPML do_action('wpml_register_single_string','custom_post','custom_post','Custom Post')}}}add_action('plugins_loaded','cptc_wpml_compatibility',20);function cptc_activate(){//First register the post type cptc_register_custom_post_type();//Then flush rewrite rules flush_rewrite_rules()}register_activation_hook(__FILE__,'cptc_activate');function cptc_deactivate(){//Flush rewrite rules flush_rewrite_rules()}register_deactivation_hook(__FILE__,'cptc_deactivate');class CPTC_Related_Custom_Posts_Widget extends WP_Widget{public function __construct(){parent::__construct('cptc_related_posts',//Base ID __('Related Custom Posts','text_domain'),//Name array('description'=> __('Shows related custom posts in the sidebar','text_domain'))//Args)}public function widget($args,$instance){global $post,$sitepress;//Only show on regular post pages if (!is_singular('post')){return}echo $args['before_widget'];$title=!empty($instance['title']) ? apply_filters('widget_title',$instance['title']) :__('Related Custom Posts','text_domain');echo $args['before_title'] . $title . $args['after_title'];//Get current post's tags and categories for relevancy
        $current_post_tags = wp_get_post_tags($post->ID, array('fields' => 'ids'));
        $current_post_cats = wp_get_post_categories($post->ID, array('fields' => 'ids'));
        
        // Get current language
        $current_language = function_exists('wpml_get_current_language') ? apply_filters('wpml_current_language', NULL) : '';
        
        // Query arguments
        $query_args = array(
            'post_type'      => 'custom_post',
            'posts_per_page' => 5,
            'post_status'    => 'publish',
            'orderby'        => 'relevance', // Order by relevance if possible
        );
        
        // Add WPML language filter if WPML is active
        if ($current_language && function_exists('icl_object_id')) {
            $query_args['suppress_filters'] = false; // Allow WPML to filter by language
        }
        
        // If the post has tags, use them for relevancy
        if (!empty($current_post_tags)) {
            $query_args['tag__in'] = $current_post_tags;
        }
        
        // If the post has categories, use them for relevancy
        if (!empty($current_post_cats)) {
            $query_args['category__in'] = $current_post_cats;
        }
        
        // Add title search for additional relevancy if post has a title
        if (!empty($post->post_title)) {
            // Get main keywords from post title (remove common words)
            $title_parts = explode(' ', strtolower($post->post_title));
            $common_words = array('the', 'and', 'or', 'a', 'an', 'in', 'on', 'at', 'to', 'for', 'with', 'by', 'about', 'as', 'of');
            $keywords = array_diff($title_parts, $common_words);
            
            if (!empty($keywords)) {
                // Use the first 2-3 significant keywords for search
                $significant_keywords = array_slice($keywords, 0, 3);
                $search_term = implode(' ', $significant_keywords);
                $query_args['s'] = $search_term;
            }
        }
        
        // Run the query
        $related_custom_posts = new WP_Query($query_args);
        
        if ($related_custom_posts->have_posts()) {
            echo '<ul class="related-custom-posts">';
            
            while ($related_custom_posts->have_posts()) {
                $related_custom_posts->the_post();
                
                echo '<li>';
                echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
                
                // Optionally show excerpt or thumbnail
                if (!empty($instance['show_thumbnail']) && has_post_thumbnail()) {
                    echo '<div class="related-thumbnail">';
                    echo '<a href="' . get_permalink() . '">';
                    the_post_thumbnail('thumbnail');
                    echo '</a>';
                    echo '</div>';
                }
                
                if (!empty($instance['show_excerpt'])) {
                    echo '<div class="related-excerpt">' . wp_trim_words(get_the_excerpt(), 15) . '</div>';
                }
                
                echo '</li>';
            }
            
            echo '</ul>';
            
            // Restore original post data
            wp_reset_postdata();
        } else {
            // If no related posts found through tags/cats, just show recent custom posts
            $recent_args = array(
                'post_type'      => 'custom_post',
                'posts_per_page' => 5,
                'post_status'    => 'publish',
            );
            
            // Add WPML language filter if WPML is active
            if ($current_language && function_exists('icl_object_id')) {
                $recent_args['suppress_filters'] = false; // Allow WPML to filter by language
            }
            
            $recent_custom_posts = new WP_Query($recent_args);
            
            if ($recent_custom_posts->have_posts()) {
                echo '<ul class="related-custom-posts">';
                echo '<p class="fallback-notice">' . __('No closely related custom posts found. Here are some recent ones:', 'text_domain') . '</p>';
                
                while ($recent_custom_posts->have_posts()) {
                    $recent_custom_posts->the_post();
                    
                    echo '<li>';
                    echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
                    
                    // Optionally show excerpt or thumbnail
                    if (!empty($instance['show_thumbnail']) && has_post_thumbnail()) {
                        echo '<div class="related-thumbnail">';
                        echo '<a href="' . get_permalink() . '">';
                        the_post_thumbnail('thumbnail');
                        echo '</a>';
                        echo '</div>';
                    }
                    
                    if (!empty($instance['show_excerpt'])) {
                        echo '<div class="related-excerpt">' . wp_trim_words(get_the_excerpt(), 15) . '</div>';
                    }
                    
                    echo '</li>';
                }
                
                echo '</ul>';
                
                // Restore original post data
                wp_reset_postdata();
            } else {
                echo '<p>' . __('No custom posts found.', 'text_domain') . '</p>';
            }
        }
        
        echo $args['after_widget'];
    }

    /**
     * Back-end widget form.
     *
     * @param array $instance Previously saved values from database.
     */
    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Related Custom Posts', 'text_domain');
        $show_thumbnail = !empty($instance['show_thumbnail']) ? (bool) $instance['show_thumbnail'] : false;
        $show_excerpt = !empty($instance['show_excerpt']) ? (bool) $instance['show_excerpt'] : false;
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_attr_e('Title:', 'text_domain'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <input class="checkbox" type="checkbox" <?php checked($show_thumbnail); ?> id="<?php echo $this->get_field_id('show_thumbnail'); ?>" name="<?php echo $this->get_field_name('show_thumbnail'); ?>" />
            <label for="<?php echo $this->get_field_id('show_thumbnail'); ?>"><?php _e('Display post thumbnail?', 'text_domain'); ?></label>
        </p>
        <p>
            <input class="checkbox" type="checkbox" <?php checked($show_excerpt); ?> id="<?php echo $this->get_field_id('show_excerpt'); ?>" name="<?php echo $this->get_field_name('show_excerpt'); ?>" />
            <label for="<?php echo $this->get_field_id('show_excerpt'); ?>"><?php _e('Display post excerpt?', 'text_domain'); ?></label>
        </p>
        <?php
    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update($instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        $instance['show_thumbnail'] = (!empty($new_instance['show_thumbnail'])) ? 1 : 0;
        $instance['show_excerpt'] = (!empty($new_instance['show_excerpt'])) ? 1 : 0;

        return $instance;
    }
}

/**
 * Register the widget
 */
function cptc_register_related_widget() {
    register_widget('CPTC_Related_Custom_Posts_Widget');
}
add_action('widgets_init', 'cptc_register_related_widget');

/**
 * Add text domain for translations
 */
function cptc_load_textdomain() {
    load_plugin_textdomain('text_domain', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
add_action('plugins_loaded', 'cptc_load_textdomain');

/**
 * Add widget-specific styles
 */
function cptc_widget_styles() {
    // Only enqueue on single post pages
    if (is_singular('post')) {
        wp_enqueue_style(
            'cptc-widget-style',
            plugin_dir_url(//contabo.com/blog/wp-content/plugins/helpposts/__FILE__) . 'widget-style.css',
            array(),
            '1.0.0'
        );
    }
}
add_action('wp_enqueue_scripts', 'cptc_widget_styles');?>