<?php
/**
 * Name: Reading Time Calculator
 * Description: Display estimated reading time for posts based on average reading speed and word count to help readers gauge time commitment before starting article
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Article Time Estimates",
 *     "description": "Display '7 min read' on blog posts so readers know time commitment before starting long-form articles."
 *   },
 *   {
 *     "title": "Content Marketing",
 *     "description": "Show reading time on thought leadership pieces to help busy executives decide when to read vs. bookmark for later."
 *   },
 *   {
 *     "title": "User Engagement",
 *     "description": "Help readers choose appropriate length content based on available time, improving user experience and reducing bounces."
 *   }
 * ]
 * Added: 2025-07-08
 * Tags: reading-time, content, ux, engagement, posts
 * WhereToFind: {
 *   "location": "Frontend (Posts with Shortcode)",
 *   "url": "/",
 *   "instructions": "Add [reading_time] shortcode to display estimated reading time",
 *   "newTab": true
 * }
 */

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

class SwitchboardReadingTime {
    
    public function __construct() {
        add_filter('the_content', [$this, 'add_reading_time']);
        add_shortcode('reading_time', [$this, 'reading_time_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_reading-time_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'transients' => []
        ];
    }
    
    public function render_settings($settings = []) {
        $auto_display = isset($settings['auto_display']) ? $settings['auto_display'] : 'yes';
        $position = isset($settings['position']) ? $settings['position'] : 'before';
        $wpm = isset($settings['wpm']) ? intval($settings['wpm']) : 200;
        ?>
        <input type="hidden" name="module" value="reading-time">
        <input type="hidden" name="setting_post_types" value="post">

        <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', 'wpswitchboard'); ?></strong>
                    <label class="sb-module-toggle">
                        <input type="checkbox" name="setting_auto_display" value="yes" <?php checked($auto_display, 'yes'); ?>>
                        <span class="sb-module-toggle-slider"></span>
                    </label>
                </div>
                <p class="sb-module-option-text"><?php esc_html_e('Automatically display reading time on posts', 'wpswitchboard'); ?></p>
            </div>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_position" class="sb-sp-label"><?php esc_html_e('Display Position', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Show reading time before or after post content', 'wpswitchboard'); ?></p>
            </div>
            <select name="setting_position" id="setting_position" class="sb-sp-select">
                <option value="before" <?php selected($position, 'before'); ?>><?php esc_html_e('Before Content', 'wpswitchboard'); ?></option>
                <option value="after" <?php selected($position, 'after'); ?>><?php esc_html_e('After Content', 'wpswitchboard'); ?></option>
            </select>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_wpm" class="sb-sp-label"><?php esc_html_e('Words Per Minute', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Average reading speed. Default: 200 WPM', 'wpswitchboard'); ?></p>
            </div>
            <input type="number" name="setting_wpm" id="setting_wpm" value="<?php echo esc_attr($wpm); ?>" min="100" max="400" class="sb-sp-select" style="width: 150px;">
        </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">
                    <strong><?php esc_html_e('Basic:', 'wpswitchboard'); ?></strong>
                    <input type="text" readonly value='[reading_time]' onclick="copyShortcode(this)" class="sb-module-shortcode-input" style="width: 180px; margin-left: 8px;">
                    <span class="sb-module-shortcode-copied">Copied!</span>
                    <span style="margin-left: 8px; color: #64748b;">→ <?php esc_html_e('"5 mins read" (default)', 'wpswitchboard'); ?></span>
                </li>
                <li class="sb-sp-list-item">
                    <strong><?php esc_html_e('Short:', 'wpswitchboard'); ?></strong>
                    <input type="text" readonly value='[reading_time format="short"]' onclick="copyShortcode(this)" class="sb-module-shortcode-input" style="width: 280px; margin-left: 8px;">
                    <span class="sb-module-shortcode-copied">Copied!</span>
                    <span style="margin-left: 8px; color: #64748b;">→ <?php esc_html_e('"5 mins"', 'wpswitchboard'); ?></span>
                </li>
                <li class="sb-sp-list-item">
                    <strong><?php esc_html_e('Number:', 'wpswitchboard'); ?></strong>
                    <input type="text" readonly value='[reading_time format="number"]' onclick="copyShortcode(this)" class="sb-module-shortcode-input" style="width: 300px; margin-left: 8px;">
                    <span class="sb-module-shortcode-copied">Copied!</span>
                    <span style="margin-left: 8px; color: #64748b;">→ <?php esc_html_e('"5"', 'wpswitchboard'); ?></span>
                </li>
                <li class="sb-sp-list-item">
                    <strong><?php esc_html_e('Custom:', 'wpswitchboard'); ?></strong>
                    <input type="text" readonly value='[reading_time wpm="250"]' onclick="copyShortcode(this)" class="sb-module-shortcode-input" style="width: 250px; margin-left: 8px;">
                    <span class="sb-module-shortcode-copied">Copied!</span>
                    <span style="margin-left: 8px; color: #64748b;">→ <?php esc_html_e('Custom reading speed', 'wpswitchboard'); ?></span>
                </li>
            </ul>
        </div>
        
        <script>
        function copyShortcode(input) {
            input.select();
            input.setSelectionRange(0, 99999);
            
            try {
                navigator.clipboard.writeText(input.value).then(function() {
                    showCopiedMessage(input);
                }).catch(function() {
                    document.execCommand('copy');
                    showCopiedMessage(input);
                });
            } catch (err) {
                document.execCommand('copy');
                showCopiedMessage(input);
            }
        }
        
        function showCopiedMessage(input) {
            var message = input.parentElement.querySelector('.sb-module-shortcode-copied');
            if (message) {
                message.classList.add('show');
                setTimeout(function() {
                    message.classList.remove('show');
                }, 2000);
            }
        }
        </script>
        <?php
    }
    
    private function get_settings() {
        return get_option('switchboard_reading-time_settings', []);
    }
    
    private function calculate_reading_time($content, $wpm = 200) {
        $word_count = str_word_count(wp_strip_all_tags($content));
        return ceil($word_count / $wpm);
    }
    
    public function add_reading_time($content) {
        if (!is_singular()) {
            return $content;
        }
        
        $settings = $this->get_settings();
        $auto_display = isset($settings['auto_display']) ? $settings['auto_display'] : 'yes';
        
        if ($auto_display !== 'yes') {
            return $content;
        }
        
        $post_types = isset($settings['post_types']) ? array_map('trim', explode(',', $settings['post_types'])) : ['post'];
        $position = isset($settings['position']) ? $settings['position'] : 'before';
        $wpm = isset($settings['wpm']) ? intval($settings['wpm']) : 200;
        
        if (!in_array(get_post_type(), $post_types)) {
            return $content;
        }
        
        $reading_time = $this->calculate_reading_time($content, $wpm);
        $label = $reading_time === 1 ? esc_html__('min', 'wpswitchboard') : esc_html__('mins', 'wpswitchboard');
        $read_text = esc_html__('read', 'wpswitchboard');

        $reading_time_html = '<div class="switchboard-reading-time" style="padding: 16px; border-radius: 8px; border-left: 4px solid var(--primary-500); margin: 16px 0; background: var(--primary-50); color: var(--primary-900);">
            <strong>' . $reading_time . ' ' . $label . ' ' . $read_text . '</strong>
        </div>';
        
        if ($position === 'after') {
            return $content . $reading_time_html;
        }
        
        return $reading_time_html . $content;
    }
    
    public function reading_time_shortcode($atts) {
        global $post;
        
        if (!$post) {
            return '';
        }
        
        $atts = shortcode_atts([
            'wpm' => 200,
            'format' => 'full' // 'full' = "5 mins read", 'short' = "5 mins", 'number' = "5"
        ], $atts);
        
        $reading_time = $this->calculate_reading_time($post->post_content, intval($atts['wpm']));
        $label = $reading_time === 1 ? esc_html__('min', 'wpswitchboard') : esc_html__('mins', 'wpswitchboard');

        switch ($atts['format']) {
            case 'short':
                return $reading_time . ' ' . $label;
            case 'number':
                return $reading_time;
            default:
                return $reading_time . ' ' . $label . ' ' . esc_html__('read', 'wpswitchboard');
        }
    }
}

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