<?php
/**
 * Name: Related Posts Generator
 * Description: Display related posts based on shared tags and categories at end of content to increase engagement and keep visitors reading more articles
 * Category: Content
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Increase Engagement",
 *     "description": "Keep visitors reading by automatically suggesting related content at the end of each post."
 *   },
 *   {
 *     "title": "Reduce Bounce Rate",
 *     "description": "Encourage visitors to explore more of your content instead of leaving after reading one article."
 *   }
 * ]
 * Added: 2025-09-02
 * Tags: related-posts, recommendations, content, engagement, seo
 * WhereToFind: {
 *   "location": "Frontend (Posts with Shortcode)",
 *   "url": "/",
 *   "instructions": "Add [related_posts] shortcode to display related content",
 *   "newTab": true
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardRelatedPosts {
    
    public function __construct() {
        add_filter('the_content', [$this, 'add_related_posts']);
        add_shortcode('related_posts', [$this, 'related_posts_shortcode']);
        
        // Register with data registry
        $this->register_with_data_registry();
    }
    
    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_related-posts_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'transients' => []
        ];
    }
    
    public function render_settings($settings = []) {
        $count = isset($settings['count']) ? intval($settings['count']) : 6;
        $auto_display = isset($settings['auto_display']) ? $settings['auto_display'] : '1';
        $columns = isset($settings['columns']) ? intval($settings['columns']) : 3;
        $show_thumbnail = isset($settings['show_thumbnail']) ? $settings['show_thumbnail'] : '1';
        ?>
        <input type="hidden" name="module" value="related-posts">

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_count" class="sb-sp-label"><?php esc_html_e('Number of Posts to Display', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Recommended: 3, 6, or 9 for best grid layout', 'wpswitchboard'); ?></p>
            </div>
            <input type="number" name="setting_count" id="setting_count" value="<?php echo esc_attr($count); ?>" min="1" max="12" class="sb-sp-select" style="width: 150px;">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_columns" class="sb-sp-label"><?php esc_html_e('Grid Columns', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Number of columns in the grid layout', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_columns" id="setting_columns" class="sb-sp-select">
                <option value="2" <?php selected($columns, 2); ?>><?php esc_html_e('2 Columns', 'wpswitchboard'); ?></option>
                <option value="3" <?php selected($columns, 3); ?>><?php esc_html_e('3 Columns (Recommended)', 'wpswitchboard'); ?></option>
                <option value="4" <?php selected($columns, 4); ?>><?php esc_html_e('4 Columns', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-module-option-item sb-module-toggle-item">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Auto Display After Content', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_auto_display" value="1" <?php checked($auto_display, '1'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Automatically show related posts at the end of single post pages', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-module-option-item sb-module-toggle-item">
            <div class="sb-module-option-content">
                <div class="sb-module-toggle-header">
                    <strong class="sb-module-option-title"><?php esc_html_e('Show Featured Images', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_show_thumbnail" value="1" <?php checked($show_thumbnail, '1'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Display post thumbnails in the grid cards', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-sp-info-box sb-sp-info-box-info">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Shortcode Usage', 'wpswitchboard'); ?></h4>
            <ul class="sb-sp-list">
                <li class="sb-sp-list-item">
                    <?php esc_html_e('Basic:', 'wpswitchboard'); ?>
                    <input type="text" readonly value='[related_posts]' onclick="this.select()" class="sb-sp-code-input" style="width: 200px; font-family: monospace; font-size: 12px; padding: 4px 8px; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 4px; cursor: pointer;">
                </li>
                <li class="sb-sp-list-item">
                    <?php esc_html_e('With options:', 'wpswitchboard'); ?>
                    <input type="text" readonly value='[related_posts count="6" columns="3"]' onclick="this.select()" class="sb-sp-code-input" style="width: 350px; font-family: monospace; font-size: 12px; padding: 4px 8px; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 4px; cursor: pointer;">
                </li>
            </ul>
        </div>
        <?php
    }
    
    public function add_related_posts($content) {
        if (!is_single()) {
            return $content;
        }

        $settings = get_option('switchboard_related-posts_settings', []);
        $auto_display = isset($settings['auto_display']) ? $settings['auto_display'] : '1';

        if ($auto_display !== '1') {
            return $content;
        }

        $related_html = $this->get_related_posts_html();

        // Always display after content
        return $content . $related_html;
    }
    
    public function related_posts_shortcode($atts) {
        $atts = shortcode_atts([
            'count' => 6,
            'columns' => 3
        ], $atts);

        return $this->get_related_posts_html($atts['count'], $atts['columns']);
    }
    
    private function get_related_posts_html($count = null, $columns = null) {
        global $post;

        if (!$post) {
            return '';
        }

        $settings = get_option('switchboard_related-posts_settings', []);
        $count = $count ?: (isset($settings['count']) ? intval($settings['count']) : 6);
        $columns = $columns ?: (isset($settings['columns']) ? intval($settings['columns']) : 3);
        $show_thumbnail = isset($settings['show_thumbnail']) ? $settings['show_thumbnail'] : '1';

        // Get related posts by tags
        $tags = wp_get_post_tags($post->ID, ['fields' => 'ids']);
        $categories = wp_get_post_categories($post->ID);

        $args = [
            'post__not_in' => [$post->ID], // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in -- Small exclusion list (single post)
            'posts_per_page' => $count,
            'post_status' => 'publish',
            'orderby' => 'rand'
        ];

        if (!empty($tags)) {
            $args['tag__in'] = $tags;
        } elseif (!empty($categories)) {
            $args['category__in'] = $categories;
        } else {
            return '';
        }

        $related_query = new WP_Query($args);

        if (!$related_query->have_posts()) {
            return '';
        }

        ob_start();
        ?>
        <div class="switchboard-related-posts" style="margin: 48px 0; padding: 40px 0; border-top: 2px solid #e5e7eb;">
            <h3 style="font-size: 18px; font-weight: 600; color: #111827; margin: 0 0 12px 0;"><?php esc_html_e('Related Posts', 'wpswitchboard'); ?></h3>
            <div class="related-posts-grid" style="display: grid; grid-template-columns: repeat(<?php echo esc_attr($columns); ?>, 1fr); gap: 24px;">
                <?php while ($related_query->have_posts()): $related_query->the_post(); ?>
                <article class="related-post-card" style="background: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e5e7eb; transition: all 0.2s;">
                    <a href="<?php echo esc_url(get_permalink()); ?>" style="text-decoration: none; display: block; color: inherit;">
                        <?php if ($show_thumbnail === '1' && has_post_thumbnail()): ?>
                        <div class="related-post-thumbnail" style="aspect-ratio: 16/9; overflow: hidden; background: #f9fafb;">
                            <?php echo get_the_post_thumbnail(null, 'medium', [
                                'style' => 'width: 100%; height: 100%; object-fit: cover; transition: transform 0.3s;'
                            ]); ?>
                        </div>
                        <?php endif; ?>
                        <div style="padding: 20px;">
                            <h4 style="margin: 0 0 8px 0; font-size: 16px; font-weight: 600; color: #111827;">
                                <?php echo esc_html(get_the_title()); ?>
                            </h4>
                            <time style="font-size: 13px; color: #64748b;">
                                <?php echo esc_html(get_the_date()); ?>
                            </time>
                        </div>
                    </a>
                </article>
                <?php endwhile; ?>
            </div>
        </div>

        <style>
        .related-post-card:hover {
            box-shadow: 0 10px 25px rgba(0,0,0,0.1) !important;
            transform: translateY(-2px);
            border-color: #d1d5db !important;
        }
        .related-post-card:hover .related-post-thumbnail img {
            transform: scale(1.05);
        }

        /* Responsive */
        @media (max-width: 768px) {
            .related-posts-grid {
                grid-template-columns: repeat(2, 1fr) !important;
                gap: 16px !important;
            }
        }
        @media (max-width: 480px) {
            .related-posts-grid {
                grid-template-columns: 1fr !important;
            }
        }
        </style>
        <?php
        wp_reset_postdata();

        return ob_get_clean();
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardRelatedPosts();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
