<?php
/**
 * Name: Enhance List Tables
 * Description: Add featured image, excerpt, word count, ID, and custom columns to post and page admin tables for better content overview and management
 * Category: Admin
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Faster Bulk Editing",
 *     "description": "Add hover actions and enhanced row highlighting to speed up bulk operations when managing hundreds of posts or products."
 *   },
 *   {
 *     "title": "Improved Visual Hierarchy",
 *     "description": "Better distinguish between rows with alternating colors and borders when scrolling through long lists of pages or media files."
 *   },
 *   {
 *     "title": "Dense Information Display",
 *     "description": "Enhanced styling to pack more readable information in post/page lists without sacrificing clarity or usability."
 *   }
 * ]
 * Added: 2025-07-20
 * Tags: list-tables, columns, admin, featured-image, excerpt, enhanced
 * WhereToFind: {
 *   "location": "Posts/Pages List Tables",
 *   "url": "edit.php",
 *   "instructions": "Additional columns (ID, word count, excerpt, featured image) will appear",
 *   "newTab": false
 * }
 */

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

class SwitchboardEnhanceListTables {
    
    public function __construct() {
        $settings = get_option('switchboard_enhance-list-tables_settings', []);
        $post_types = isset($settings['post_types']) && is_string($settings['post_types'])
            ? explode(',', $settings['post_types'])
            : ['post', 'page'];

        // Add columns for selected post types
        foreach ($post_types as $post_type) {
            $post_type = trim($post_type);
            if (empty($post_type)) continue;

            add_filter("manage_{$post_type}_posts_columns", [$this, 'add_columns']);
            add_action("manage_{$post_type}_posts_custom_column", [$this, 'show_columns'], 10, 2);
            add_filter("manage_edit-{$post_type}_sortable_columns", [$this, 'sortable_columns']);
        }

        // Handle sorting
        add_action('pre_get_posts', [$this, 'handle_sorting']);
        
        // 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_enhance-list-tables_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'term_meta' => [],
            'transients' => []
        ];
    }
    
    /**
     * Render settings panel
     * 
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        $show_thumbnail = isset($settings['show_thumbnail']) ? $settings['show_thumbnail'] : '1';
        $show_id = isset($settings['show_id']) ? $settings['show_id'] : '0';
        $show_excerpt = isset($settings['show_excerpt']) ? $settings['show_excerpt'] : '1';
        $show_word_count = isset($settings['show_word_count']) ? $settings['show_word_count'] : '0';
        $show_modified = isset($settings['show_modified']) ? $settings['show_modified'] : '1';
        $show_author_email = isset($settings['show_author_email']) ? $settings['show_author_email'] : '0';
        $show_template = isset($settings['show_template']) ? $settings['show_template'] : '0';
        $excerpt_length = isset($settings['excerpt_length']) ? intval($settings['excerpt_length']) : 15;
        
        $selected_post_types = isset($settings['post_types']) ? explode(',', $settings['post_types']) : ['post', 'page'];
        $selected_post_types = array_map('trim', $selected_post_types);
        $all_post_types = get_post_types(['public' => true], 'objects');
        unset($all_post_types['attachment']); // Remove media/attachment from picker
        ?>
        <input type="hidden" name="module" value="enhance-list-tables">

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php esc_html_e('Post Types', 'wpswitchboard'); ?></label>
        <input type="hidden" name="setting_post_types" id="setting_post_types" value="<?php echo esc_attr(implode(',', $selected_post_types)); ?>">
        <div class="switchboard-tag-selector" data-input-id="setting_post_types">
            <div class="switchboard-selected-tags" id="selected-post-types-enhance">
                <?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>
        <p class="sb-sp-description"><?php esc_html_e('Select which post types to enhance with additional columns.', 'wpswitchboard'); ?></p>
        </div>

        <hr class="sb-sp-divider">

        <div class="sb-sp-group">
            <label class="sb-sp-label sb-sp-mb-2"><?php esc_html_e('Additional Columns', 'wpswitchboard'); ?></label>
            <div class="sb-sp-grid-2">
            <label class="sb-module-checkbox-item" style="margin:0px;">
                <input type="checkbox" name="setting_show_id" value="1" <?php checked($show_id, '1'); ?>>
                <span><?php esc_html_e('Post ID', 'wpswitchboard'); ?></span>
            </label>
            <label class="sb-module-checkbox-item" style="margin:0px;">
                <input type="checkbox" name="setting_show_thumbnail" value="1" <?php checked($show_thumbnail, '1'); ?>>
                <span><?php esc_html_e('Featured Image', 'wpswitchboard'); ?></span>
            </label>
            <label class="sb-module-checkbox-item" style="margin:0px;">
                <input type="checkbox" name="setting_show_excerpt" value="1" <?php checked($show_excerpt, '1'); ?>>
                <span><?php esc_html_e('Excerpt', 'wpswitchboard'); ?></span>
            </label>
            <label class="sb-module-checkbox-item" style="margin:0px;">
                <input type="checkbox" name="setting_show_word_count" value="1" <?php checked($show_word_count, '1'); ?>>
                <span><?php esc_html_e('Word Count', 'wpswitchboard'); ?></span>
            </label>
            <label class="sb-module-checkbox-item" style="margin:0px;">
                <input type="checkbox" name="setting_show_modified" value="1" <?php checked($show_modified, '1'); ?>>
                <span><?php esc_html_e('Last Modified', 'wpswitchboard'); ?></span>
            </label>
            <label class="sb-module-checkbox-item" style="margin:0px;">
                <input type="checkbox" name="setting_show_author_email" value="1" <?php checked($show_author_email, '1'); ?>>
                <span><?php esc_html_e('Author Email', 'wpswitchboard'); ?></span>
            </label>
            <label class="sb-module-checkbox-item" style="margin:0px;">
                <input type="checkbox" name="setting_show_template" value="1" <?php checked($show_template, '1'); ?>>
                <span><?php esc_html_e('Page Template', 'wpswitchboard'); ?></span>
            </label>
            </div>
        </div>

        <hr class="sb-sp-divider">

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label class="sb-sp-label" for="setting_excerpt_length"><?php esc_html_e('Excerpt Length (words)', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php esc_html_e('Number of words to show in the excerpt column.', 'wpswitchboard'); ?></p>
            </div>
            <input type="number" name="setting_excerpt_length" id="setting_excerpt_length" value="<?php echo esc_attr($excerpt_length); ?>" min="5" max="100" class="sb-sp-input">
        </div>
        <?php
    }
    

    public function add_columns($columns) {
        $settings = get_option('switchboard_enhance-list-tables_settings', []);
        $show_thumbnail = isset($settings['show_thumbnail']) ? $settings['show_thumbnail'] : '1';
        $show_id = isset($settings['show_id']) ? $settings['show_id'] : '0';
        $show_excerpt = isset($settings['show_excerpt']) ? $settings['show_excerpt'] : '1';
        $show_word_count = isset($settings['show_word_count']) ? $settings['show_word_count'] : '0';
        $show_modified = isset($settings['show_modified']) ? $settings['show_modified'] : '1';
        $show_author_email = isset($settings['show_author_email']) ? $settings['show_author_email'] : '0';
        $show_template = isset($settings['show_template']) ? $settings['show_template'] : '0';
        
        $new_columns = [];


        // Add ID column at the beginning if enabled
        if ($show_id === '1') {
            $new_columns['post_id'] = esc_html__('ID', 'wpswitchboard');
        }

        foreach ($columns as $key => $value) {
            // Add thumbnail before title
            if ($key === 'title' && $show_thumbnail === '1') {
                $new_columns['featured_image'] = esc_html__('Image', 'wpswitchboard');
            }

            $new_columns[$key] = $value;
        }

        // Add additional columns at the end
        if ($show_excerpt === '1') {
            $new_columns['excerpt'] = esc_html__('Excerpt', 'wpswitchboard');
        }
        if ($show_word_count === '1') {
            $new_columns['word_count'] = esc_html__('Words', 'wpswitchboard');
        }
        if ($show_modified === '1') {
            $new_columns['last_modified'] = esc_html__('Modified', 'wpswitchboard');
        }
        if ($show_author_email === '1') {
            $new_columns['author_email'] = esc_html__('Author Email', 'wpswitchboard');
        }
        if ($show_template === '1') {
            $new_columns['page_template'] = esc_html__('Template', 'wpswitchboard');
        }
        
        return $new_columns;
    }
    
    public function show_columns($column, $post_id) {
        switch ($column) {
            case 'post_id':
                echo '<strong>' . esc_html($post_id) . '</strong>';
                break;
                
            case 'featured_image':
                if (has_post_thumbnail($post_id)) {
                    echo get_the_post_thumbnail($post_id, [50, 50]);
                } else {
                    echo '<span class="sb-sp-text-gray-400">—</span>';
                }
                break;
                
            case 'excerpt':
                $settings = get_option('switchboard_enhance-list-tables_settings', []);
                $excerpt_length = isset($settings['excerpt_length']) ? intval($settings['excerpt_length']) : 15;
                $excerpt = get_the_excerpt($post_id);
                if ($excerpt && is_string($excerpt)) {
                    echo esc_html(wp_trim_words($excerpt, $excerpt_length));
                } else {
                    echo '<span class="sb-sp-text-gray-400">—</span>';
                }
                break;
                
            case 'word_count':
                $content = get_post_field('post_content', $post_id);
                if ($content && is_string($content)) {
                    $word_count = str_word_count(wp_strip_all_tags($content));
                    echo '<strong>' . esc_html(number_format($word_count)) . '</strong>';
                } else {
                    echo '<strong>0</strong>';
                }
                break;
                
            case 'last_modified':
                $modified = get_post_modified_time('Y-m-d H:i', false, $post_id);
                $modified_timestamp = get_post_modified_time('U', false, $post_id);
                $time_diff = human_time_diff($modified_timestamp, current_time('timestamp'));
                /* translators: %s: time difference */
                echo '<span title="' . esc_attr($modified) . '">' . sprintf(esc_html__('%s ago', 'wpswitchboard'), esc_html($time_diff)) . '</span>';
                break;

            case 'author_email':
                $author_id = get_post_field('post_author', $post_id);
                $author_email = get_the_author_meta('user_email', $author_id);
                echo '<a href="mailto:' . esc_attr($author_email) . '">' . esc_html($author_email) . '</a>';
                break;

            case 'page_template':
                $template = get_page_template_slug($post_id);
                if ($template) {
                    $template_name = basename($template, '.php');
                    echo '<code>' . esc_html($template_name) . '</code>';
                } else {
                    echo '<span class="sb-sp-text-gray-400">' . esc_html__('Default', 'wpswitchboard') . '</span>';
                }
                break;
        }
    }
    
    public function sortable_columns($columns) {
        $columns['post_id'] = 'ID';
        $columns['word_count'] = 'word_count';
        $columns['last_modified'] = 'modified';
        return $columns;
    }
    
    public function handle_sorting($query) {
        if (!is_admin() || !$query->is_main_query()) {
            return;
        }
        
        $orderby = $query->get('orderby');
        
        if ($orderby === 'word_count') {
            $query->set('meta_key', '_word_count');
            $query->set('orderby', 'meta_value_num');
        }
    }
}

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