<?php
/**
 * Name: Breadcrumbs
 * Description: Breadcrumb navigation with Schema.org markup for SEO and user navigation. Use [breadcrumbs] shortcode or add to templates.
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Deep Site Navigation",
 *     "description": "Add breadcrumb trail to e-commerce sites with categories 4-5 levels deep so users can navigate back without using browser back button."
 *   },
 *   {
 *     "title": "SEO Enhancement",
 *     "description": "Implement structured breadcrumb markup for better Google search results and rich snippets on documentation or knowledge base sites."
 *   },
 *   {
 *     "title": "User Experience",
 *     "description": "Help visitors understand where they are in site hierarchy on complex sites with multiple content types and category structures."
 *   }
 * ]
 * Added: 2025-09-14
 * Tags: breadcrumbs, navigation, seo, ux, schema, shortcode
 * WhereToFind: {
 *   "location": "Frontend (Pages with Shortcode)",
 *   "url": "/",
 *   "instructions": "Add [breadcrumbs] shortcode to see navigation trail with schema markup",
 *   "newTab": true
 * }
 */

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

class SwitchboardBreadcrumbs {
    
    private $settings;
    
    public function __construct() {
        // Load settings with defaults
        $defaults = [
            'separator' => '›',
            'home_text' => 'Home',
            'auto_display' => 'none',
            'post_types' => 'post,page'
        ];
        
        $this->settings = wp_parse_args(
            get_option('switchboard_breadcrumbs_settings', []),
            $defaults
        );
        
        // Convert post_types string to array if needed
        if (is_string($this->settings['post_types'])) {
            $this->settings['post_types'] = array_map('trim', explode(',', $this->settings['post_types']));
        }
        
        add_shortcode('breadcrumbs', [$this, 'render_breadcrumbs']);
        
        // Auto display hooks
        if (!empty($this->settings['auto_display']) && $this->settings['auto_display'] !== 'none') {
            add_filter('the_content', [$this, 'auto_inject_breadcrumbs']);
        }
        
        // Register with data registry
        $this->register_with_data_registry();
    }
    
    /**
     * Register data locations with the 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__);
        }
    }
    
    /**
     * Register data locations for cleanup
     * 
     * @return array Data locations used by this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_breadcrumbs_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'transients' => []
        ];
    }
    
    /**
     * Render settings panel
     * 
     * @param array $settings Current settings
     * @return void Outputs HTML
     */
    public function render_settings($settings = []) {
        $separator = isset($settings['separator']) ? $settings['separator'] : '›';
        $home_text = isset($settings['home_text']) ? $settings['home_text'] : 'Home';
        $auto_display = isset($settings['auto_display']) ? $settings['auto_display'] : 'none';
        $post_types = isset($settings['post_types']) ? $settings['post_types'] : 'post,page';
        
        // Convert comma-separated string to array
        $selected_post_types = array_map('trim', explode(',', $post_types));
        
        // Get all public post types
        $all_post_types = get_post_types(['public' => true], 'objects');
        $exclude_types = ['attachment', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation'];
        $all_post_types = array_diff_key($all_post_types, array_flip($exclude_types));
        ?>
        <input type="hidden" name="module" value="breadcrumbs">

        <div class="sb-sp-group">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Breadcrumb Navigation', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description"><?php esc_html_e('Add breadcrumb navigation with Schema.org markup for better SEO and user navigation.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label" for="setting_separator"><?php esc_html_e('Separator', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Choose the separator between breadcrumb items', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_separator" id="setting_separator" class="sb-sp-select">
                <option value="›" <?php selected($separator, '›'); ?>><?php esc_html_e('› (Right Arrow)', 'wpswitchboard'); ?></option>
                <option value="/" <?php selected($separator, '/'); ?>><?php esc_html_e('/ (Slash)', 'wpswitchboard'); ?></option>
                <option value=">" <?php selected($separator, '>'); ?>><?php esc_html_e('> (Greater Than)', 'wpswitchboard'); ?></option>
                <option value="→" <?php selected($separator, '→'); ?>><?php esc_html_e('→ (Right Arrow Long)', 'wpswitchboard'); ?></option>
                <option value="»" <?php selected($separator, '»'); ?>><?php esc_html_e('» (Double Right Arrow)', 'wpswitchboard'); ?></option>
                <option value="|" <?php selected($separator, '|'); ?>><?php esc_html_e('| (Pipe)', 'wpswitchboard'); ?></option>
                <option value="·" <?php selected($separator, '·'); ?>><?php esc_html_e('· (Dot)', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label" for="setting_home_text"><?php esc_html_e('Home Text', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Text for the home link (Default: "Home")', 'wpswitchboard'); ?></p>
            </div>
            <input type="text" name="setting_home_text" id="setting_home_text" value="<?php echo esc_attr($home_text); ?>" class="sb-sp-input">
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label" for="setting_auto_display"><?php esc_html_e('Auto Display', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Automatically display breadcrumbs, or use shortcode for manual placement', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_auto_display" id="setting_auto_display" class="sb-sp-select">
                <option value="none" <?php selected($auto_display, 'none'); ?>><?php esc_html_e('Manual (Use Shortcode)', 'wpswitchboard'); ?></option>
                <option value="before" <?php selected($auto_display, 'before'); ?>><?php esc_html_e('Before Content', 'wpswitchboard'); ?></option>
                <option value="after" <?php selected($auto_display, 'after'); ?>><?php esc_html_e('After Content', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php esc_html_e('Display On', 'wpswitchboard'); ?></label>
                    <p class="sb-sp-description"><?php esc_html_e('Select post types where breadcrumbs should appear:', 'wpswitchboard'); ?></p>
                    
                    <input type="hidden" name="setting_post_types" id="setting_post_types" value="<?php echo esc_attr($post_types); ?>">
                    
                    <div class="switchboard-tag-selector">
                        <div class="switchboard-selected-tags" id="breadcrumb-selected-post-types">
                            <?php foreach ($selected_post_types as $pt_slug): 
                                if (isset($all_post_types[$pt_slug])): ?>
                                    <span class="switchboard-tag" data-value="<?php echo esc_attr($pt_slug); ?>">
                                        <?php echo esc_html($all_post_types[$pt_slug]->label); ?>
                                        <span class="remove-tag">×</span>
                                    </span>
                                <?php endif;
                            endforeach; ?>
                        </div>
                        <div class="switchboard-available-tags">
                            <?php foreach ($all_post_types as $pt_slug => $pt_obj): 
                                $is_selected = in_array($pt_slug, $selected_post_types) ? 'selected' : ''; ?>
                                <span class="switchboard-tag-option <?php echo esc_attr($is_selected); ?>" data-value="<?php echo esc_attr($pt_slug); ?>">
                                    <?php echo esc_html($pt_obj->label); ?>
                                </span>
                            <?php endforeach; ?>
                        </div>
                    </div>
        </div>

        <hr class="sb-sp-divider">
        
        <!-- Shortcode Builder -->
        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm"><?php esc_html_e('Shortcode Builder', 'wpswitchboard'); ?></h4>
            <p class="sb-sp-description"><?php esc_html_e('Copy this shortcode to use in your pages, posts, or templates:', 'wpswitchboard'); ?></p>

            <div style="margin: 16px 0;">
                <input type="text" id="breadcrumb-shortcode" class="sb-sp-input sb-sp-w-full" value="[breadcrumbs]" readonly style="font-family: 'Courier New', monospace; font-size: 14px; background: #f9fafb; cursor: text;" onclick="this.select();">
            </div>

            <div class="sb-sp-info-box sb-sp-info-box-tip">
                <h4 class="sb-sp-heading-sm"><?php esc_html_e('Pro Tip', 'wpswitchboard'); ?></h4>
                <p class="sb-sp-description" style="margin: 0 0 12px 0;"><?php esc_html_e('You can override settings in the shortcode:', 'wpswitchboard'); ?></p>
                <div onclick="var range = document.createRange(); range.selectNodeContents(this.querySelector('code')); window.getSelection().removeAllRanges(); window.getSelection().addRange(range);" style="background: #ffffff; border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin-bottom: 12px; cursor: text; transition: border-color 0.2s ease;" onmouseover="this.style.borderColor='var(--primary-500)';" onmouseout="this.style.borderColor='#e5e7eb';">
                    <code style="font-family: 'Courier New', monospace; font-size: 13px; color: #111827; display: block; white-space: pre-wrap; word-break: break-all; user-select: all;">[breadcrumbs separator="/" home_text="Start"]</code>
                </div>
                <p class="sb-sp-description" style="margin: 0 0 8px 0;"><?php esc_html_e('Or add to your theme template:', 'wpswitchboard'); ?></p>
                <div onclick="var range = document.createRange(); range.selectNodeContents(this.querySelector('code')); window.getSelection().removeAllRanges(); window.getSelection().addRange(range);" style="background: #ffffff; border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin: 0; cursor: text; transition: border-color 0.2s ease;" onmouseover="this.style.borderColor='var(--primary-500)';" onmouseout="this.style.borderColor='#e5e7eb';">
                    <code style="font-family: 'Courier New', monospace; font-size: 13px; color: #111827; display: block; white-space: pre-wrap; word-break: break-all; user-select: all;">&lt;?php echo do_shortcode('[breadcrumbs]'); ?&gt;</code>
                </div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            const i18n = {
                copied: <?php echo json_encode(esc_html__('Copied!', 'wpswitchboard')); ?>
            };

            // Update shortcode builder when settings change
            function updateBreadcrumbShortcode() {
                const separator = $('#setting_separator').val();
                const homeText = $('#setting_home_text').val();
                
                let shortcode = '[breadcrumbs';
                
                // Only add attributes if they differ from defaults
                if (separator !== '›') {
                    shortcode += ' separator="' + separator + '"';
                }
                if (homeText !== 'Home') {
                    shortcode += ' home_text="' + homeText + '"';
                }
                
                shortcode += ']';
                $('#breadcrumb-shortcode').val(shortcode);
            }
            
            // Update shortcode on field changes
            $('#setting_separator, #setting_home_text').on('change keyup', updateBreadcrumbShortcode);
            
            // Show/hide post types based on auto display setting
            function togglePostTypesVisibility() {
                if ($('#setting_auto_display').val() === 'none') {
                    $('#breadcrumb_post_types_row').hide();
                } else {
                    $('#breadcrumb_post_types_row').show();
                }
            }
            
            $('#setting_auto_display').on('change', togglePostTypesVisibility);
            togglePostTypesVisibility(); // Initial state
            
            // Handle tag selector for post types
            $('#breadcrumb-selected-post-types').on('click', '.remove-tag', function() {
                const $tag = $(this).parent();
                const value = $tag.data('value');
                
                $tag.remove();
                $('.switchboard-tag-option[data-value="' + value + '"]').removeClass('selected');
                
                updatePostTypesField();
            });
            
            $('.switchboard-available-tags').on('click', '.switchboard-tag-option:not(.selected)', function() {
                const $option = $(this);
                const value = $option.data('value');
                const label = $option.text();
                
                $option.addClass('selected');
                
                const $tag = $('<span class="switchboard-tag" data-value="' + value + '">' + label + ' <span class="remove-tag">×</span></span>');
                $('#breadcrumb-selected-post-types').append($tag);
                
                updatePostTypesField();
            });
            
            function updatePostTypesField() {
                const values = [];
                $('#breadcrumb-selected-post-types .switchboard-tag').each(function() {
                    values.push($(this).data('value'));
                });
                $('#setting_post_types').val(values.join(','));
            }
            
            // Initialize shortcode
            updateBreadcrumbShortcode();
        });
        </script>
        <?php
    }
    
    public function auto_inject_breadcrumbs($content) {
        // Only on singular posts/pages
        if (!is_singular()) {
            return $content;
        }
        
        // Check if current post type is enabled
        $post_type = get_post_type();
        if (!in_array($post_type, $this->settings['post_types'])) {
            return $content;
        }
        
        // Don't show on front page
        if (is_front_page()) {
            return $content;
        }
        
        $breadcrumbs = $this->render_breadcrumbs();
        
        if ($this->settings['auto_display'] === 'before') {
            return $breadcrumbs . $content;
        } elseif ($this->settings['auto_display'] === 'after') {
            return $content . $breadcrumbs;
        }
        
        return $content;
    }
    
    public function render_breadcrumbs($atts = []) {
        // Merge shortcode attributes with saved settings
        $defaults = [
            'separator' => $this->settings['separator'],
            'home_text' => $this->settings['home_text']
        ];
        
        $atts = shortcode_atts($defaults, $atts);
        
        if (is_front_page()) {
            return '';
        }
        
        $breadcrumbs = [];
        
        // Home link
        $breadcrumbs[] = [
            'url' => home_url('/'),
            'title' => $atts['home_text']
        ];
        
        // Build breadcrumb trail
        if (is_category() || is_single()) {
            $category = get_the_category();
            if ($category && is_array($category) && !empty($category)) {
                $cat = $category[0];
                if ($cat->parent != 0) {
                    $breadcrumbs = array_merge($breadcrumbs, $this->get_category_parents($cat->parent));
                }
                $breadcrumbs[] = [
                    'url' => get_category_link($cat->term_id),
                    'title' => $cat->name
                ];
            }
        } elseif (is_page()) {
            global $post;
            if (is_object($post) && isset($post->post_parent) && $post->post_parent) {
                $parent_id = $post->post_parent;
                $parent_breadcrumbs = [];
                
                while ($parent_id) {
                    $page = get_post($parent_id);
                    if (!is_object($page) || !isset($page->ID, $page->post_parent)) {
                        break;
                    }
                    $parent_breadcrumbs[] = [
                        'url' => get_permalink($page->ID),
                        'title' => get_the_title($page->ID)
                    ];
                    $parent_id = $page->post_parent;
                }
                
                $breadcrumbs = array_merge($breadcrumbs, array_reverse($parent_breadcrumbs));
            }
        } elseif (is_tag()) {
            $breadcrumbs[] = [
                'url' => '',
                /* translators: %s: tag name */
                'title' => sprintf(esc_html__('Tag: %s', 'wpswitchboard'), single_tag_title('', false))
            ];
        } elseif (is_author()) {
            $breadcrumbs[] = [
                'url' => '',
                /* translators: %s: author name */
                'title' => sprintf(esc_html__('Author: %s', 'wpswitchboard'), get_the_author())
            ];
        } elseif (is_search()) {
            $breadcrumbs[] = [
                'url' => '',
                /* translators: %s: search query */
                'title' => sprintf(esc_html__('Search Results for: %s', 'wpswitchboard'), get_search_query())
            ];
        } elseif (is_404()) {
            $breadcrumbs[] = [
                'url' => '',
                'title' => esc_html__('404 Not Found', 'wpswitchboard')
            ];
        }
        
        // Current page
        if (is_single() || is_page()) {
            $breadcrumbs[] = [
                'url' => '',
                'title' => get_the_title()
            ];
        }
        
        // Render breadcrumbs
        $output = '<nav class="switchboard-breadcrumbs" aria-label="Breadcrumb">';
        $output .= '<ol itemscope itemtype="https://schema.org/BreadcrumbList" style="list-style: none; padding: 0; margin: 0; display: flex; flex-wrap: wrap; gap: 8px;">';
        
        foreach ($breadcrumbs as $index => $crumb) {
            $position = $index + 1;
            $output .= '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="sb-sp-flex sb-sp-items-center">';
            
            if (!empty($crumb['url'])) {
                $output .= '<a itemprop="item" href="' . esc_url($crumb['url']) . '" class="sb-sp-text-blue-600">';
                $output .= '<span itemprop="name">' . esc_html($crumb['title']) . '</span>';
                $output .= '</a>';
            } else {
                $output .= '<span itemprop="name">' . esc_html($crumb['title']) . '</span>';
            }
            
            $output .= '<meta itemprop="position" content="' . esc_attr($position) . '">';
            
            if ($index < count($breadcrumbs) - 1) {
                $output .= '<span class="sb-sp-m-0">' . esc_html($atts['separator']) . '</span>';
            }
            
            $output .= '</li>';
        }
        
        $output .= '</ol></nav>';
        
        return $output;
    }
    
    private function get_category_parents($parent_id) {
        $breadcrumbs = [];

        while ($parent_id) {
            $cat = get_category($parent_id);
            if (!is_object($cat) || is_wp_error($cat) || !isset($cat->term_id, $cat->name, $cat->parent)) {
                break;
            }
            $breadcrumbs[] = [
                'url' => get_category_link($cat->term_id),
                'title' => $cat->name
            ];
            $parent_id = $cat->parent;
        }
        
        return array_reverse($breadcrumbs);
    }
}

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