<?php
/**
 * Name: Compact Tables
 * Description: Create ultra-compact post and page list tables with reduced padding, compact date format, and minimal spacing to show more content per screen
 * Category: Admin
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Managing 500+ Posts",
 *     "description": "Reduce row height in posts table to see 30+ articles per screen instead of 10, making batch operations much faster."
 *   },
 *   {
 *     "title": "Product Catalog Management",
 *     "description": "Fit more WooCommerce products on screen when doing inventory updates across hundreds of items."
 *   },
 *   {
 *     "title": "Small Laptop Screens",
 *     "description": "Maximize visible rows for editors working on 13-inch laptops or smaller screens where vertical space is limited."
 *   }
 * ]
 * Added: 2025-08-05
 * Tags: list-tables, compact, minimal, admin, spacing, date
 * WhereToFind: {
 *   "location": "Posts/Pages List Tables",
 *   "url": "edit.php",
 *   "instructions": "Tables will have reduced padding and compact date format",
 *   "newTab": false
 * }
 */

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

class SwitchboardCompactTables {
    
    public function __construct() {
        $settings = get_option('switchboard_compact-tables_settings', []);
        $post_types = isset($settings['post_types']) && is_string($settings['post_types'])
            ? array_map('trim', explode(',', $settings['post_types']))
            : ['post', 'page'];

        add_action('admin_enqueue_scripts', [$this, 'enqueue_styles']);

        // Add compact date column for selected post types
        foreach ($post_types as $post_type) {
            if (empty($post_type)) continue;

            add_filter("manage_{$post_type}_posts_columns", [$this, 'add_compact_date_column']);
            add_action("manage_{$post_type}_posts_custom_column", [$this, 'show_compact_date_column'], 10, 2);
            add_filter("manage_edit-{$post_type}_sortable_columns", [$this, 'sortable_columns']);
        }
        
        // 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_compact-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 = []) {
        $padding = isset($settings['padding']) ? intval($settings['padding']) : 3;
        $font_size = isset($settings['font_size']) ? intval($settings['font_size']) : 12;
        $row_height = isset($settings['row_height']) ? intval($settings['row_height']) : 28;
        $compact_date = isset($settings['compact_date']) ? $settings['compact_date'] : '1';

        $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="compact-tables">

        <div class="sb-sp-group">
            <label class="sb-sp-label"><?php echo esc_html__('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-compact">
                    <?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 echo esc_html__('Select which post types should have ultra-compact list tables.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group">
            <label class="sb-module-checkbox-item">
                <input type="checkbox" name="setting_compact_date" value="1" <?php checked($compact_date, '1'); ?>>
                <span><?php echo esc_html__('Compact Date Format', 'wpswitchboard'); ?></span>
            </label>
            <p class="sb-sp-description" style="margin-top: 8px;"><?php echo esc_html__('Show date and time on single line (Y/m/d g:i a)', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_row_height" class="sb-sp-label"><?php echo esc_html__('Row Height', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php echo esc_html__('Total height of each table row. Lower values fit more rows on screen.', 'wpswitchboard'); ?></p>
            </div>
            <div class="sb-sp-field-horizontal-right">
                <input type="range" name="setting_row_height" id="setting_row_height" value="<?php echo esc_attr($row_height); ?>" min="24" max="40" step="2" class="sb-sp-range">
                <div class="sb-sp-range-value">
                    <span class="sb-sp-text-semibold"><span id="row-height-value"><?php echo esc_html($row_height); ?></span>px</span>
                </div>
            </div>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_padding" class="sb-sp-label"><?php echo esc_html__('Cell Padding', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php echo esc_html__('Space between cell content and borders. Lower values pack content tighter.', 'wpswitchboard'); ?></p>
            </div>
            <div class="sb-sp-field-horizontal-right">
                <input type="range" name="setting_padding" id="setting_padding" value="<?php echo esc_attr($padding); ?>" min="1" max="10" step="1" class="sb-sp-range">
                <div class="sb-sp-range-value">
                    <span class="sb-sp-text-semibold"><span id="padding-value"><?php echo esc_html($padding); ?></span>px</span>
                </div>
            </div>
        </div>

        <div class="sb-sp-group sb-sp-field-horizontal">
            <div class="sb-sp-field-horizontal-left">
                <label for="setting_font_size" class="sb-sp-label"><?php echo esc_html__('Font Size', 'wpswitchboard'); ?></label>
                <p class="sb-sp-description"><?php echo esc_html__('Text size across all table columns.', 'wpswitchboard'); ?></p>
            </div>
            <div class="sb-sp-field-horizontal-right">
                <input type="range" name="setting_font_size" id="setting_font_size" value="<?php echo esc_attr($font_size); ?>" min="10" max="14" step="1" class="sb-sp-range">
                <div class="sb-sp-range-value">
                    <span class="sb-sp-text-semibold"><span id="font-size-value"><?php echo esc_html($font_size); ?></span>px</span>
                </div>
            </div>
        </div>

        <script>
        jQuery(document).ready(function($) {
            $("#setting_padding").on("input", function() {
                $("#padding-value").text($(this).val());
            });
            $("#setting_font_size").on("input", function() {
                $("#font-size-value").text($(this).val());
            });
            $("#setting_row_height").on("input", function() {
                $("#row-height-value").text($(this).val());
            });
        });
        </script>
        <?php
    }
    
    public function enqueue_styles($hook) {
        // Only load on edit.php pages (post list tables)
        if ($hook !== 'edit.php') {
            return;
        }
        
        $settings = get_option('switchboard_compact-tables_settings', []);
        $post_types = isset($settings['post_types']) && is_string($settings['post_types'])
            ? array_map('trim', explode(',', $settings['post_types']))
            : ['post', 'page'];
        $current_screen = get_current_screen();

        // Check if current post type is in the enabled list
        if (!$current_screen || !is_object($current_screen) || !isset($current_screen->post_type) || !in_array($current_screen->post_type, $post_types, true)) {
            return;
        }
        
        $padding = isset($settings['padding']) ? intval($settings['padding']) : 3;
        $font_size = isset($settings['font_size']) ? intval($settings['font_size']) : 12;
        $row_height = isset($settings['row_height']) ? intval($settings['row_height']) : 28;
        
        $css = "
        /* Compact Tables - Ultra-Compact Styling */
        .wp-list-table {
            font-size: {$font_size}px;
            line-height: 1.3;
        }
        
        .wp-list-table th,
        .wp-list-table td {
            padding: {$padding}px 6px !important;
            vertical-align: middle;
        }

        .wp-list-table tr {
            height: {$row_height}px !important;
        }

        .wp-list-table tbody tr {
            max-height: {$row_height}px !important;
        }
        
        .wp-list-table .row-actions {
            padding: 0 !important;
            margin: 0 !important;
            line-height: 1.3;
        }
        
        .wp-list-table .row-actions span {
            margin: 0 3px 0 0 !important;
        }
        
        .wp-list-table .column-title .row-title {
            font-size: " . ($font_size + 1) . "px;
            font-weight: 600;
            margin-bottom: 2px;
        }
        
        .wp-list-table .column-title strong {
            display: inline-block;
            margin-bottom: 2px;
        }
        
        .wp-list-table img {
            max-width: 35px;
            max-height: 35px;
        }

        /* Admin Columns Manager integration - thumbnail column */
        .wp-list-table .column-thumbnail img,
        .wp-list-table .switchboard-column-thumbnail {
            max-width: " . ($row_height - 4) . "px !important;
            max-height: " . ($row_height - 4) . "px !important;
            width: auto !important;
            height: auto !important;
            object-fit: cover;
            vertical-align: middle;
        }

        /* Admin Columns Manager - ALL columns get uniform font size */
        .wp-list-table td,
        .wp-list-table th {
            font-size: {$font_size}px !important;
        }

        /* Make row-title (post/page titles) slightly larger for readability */
        .wp-list-table .row-title,
        .wp-list-table td.column-title a {
            font-size: " . ($font_size + 1) . "px !important;
        }

        /* Compact date column - same font size, just nowrap */
        .wp-list-table .column-compact_date,
        .wp-list-table .column-date,
        .wp-list-table .column-modified {
            white-space: nowrap;
        }

        .wp-list-table .column-compact_date abbr,
        .wp-list-table .column-date abbr {
            display: inline;
            border: none;
        }

        /* Admin Columns Manager quick-add columns - same font size, just nowrap */
        .wp-list-table .column-post_id,
        .wp-list-table .column-word_count,
        .wp-list-table .column-slug {
            white-space: nowrap;
        }

        /* Empty column placeholder */
        .wp-list-table .switchboard-column-empty {
            color: #999;
        }
        
        /* Compact navigation */
        .tablenav {
            padding: 6px 0 !important;
            min-height: 32px;
        }
        
        .tablenav .actions {
            padding: 0 6px 0 0 !important;
        }
        
        .tablenav select {
            height: 26px !important;
            font-size: 11px !important;
            padding: 2px 20px 2px 6px !important;
        }
        
        .tablenav .button {
            height: 26px !important;
            line-height: 24px !important;
            padding: 0 8px !important;
            font-size: 11px !important;
        }
        
        .tablenav-pages {
            margin: 0 !important;
        }
        
        .tablenav-pages .pagination-links {
            font-size: 11px;
        }
        
        .tablenav-pages .button {
            height: 24px !important;
            width: 24px !important;
            padding: 0 !important;
            font-size: 13px !important;
        }
        
        .tablenav-pages .current-page {
            height: 24px !important;
            line-height: 24px !important;
            font-size: 11px !important;
            padding: 0 4px !important;
        }
        
        .subsubsub {
            margin: 6px 0 !important;
            font-size: 11px;
        }
        
        .wp-list-table .check-column {
            width: 2em !important;
            padding: {$padding}px 0 {$padding}px 6px !important;
        }
        
        /* Tighter search box */
        .search-box {
            margin: 0 !important;
        }
        
        .search-box input[type='search'] {
            height: 26px !important;
            font-size: 11px !important;
            padding: 2px 8px !important;
        }
        
        .search-box input[type='submit'] {
            height: 26px !important;
            line-height: 24px !important;
            padding: 0 8px !important;
            font-size: 11px !important;
        }
        
        /* Compact post states */
        .post-state {
            font-size: " . ($font_size - 1) . "px;
        }
        ";
        
        wp_add_inline_style('common', $css);
    }
    
    public function add_compact_date_column($columns) {
        $settings = get_option('switchboard_compact-tables_settings', []);
        $compact_date = isset($settings['compact_date']) ? $settings['compact_date'] : '1';
        
        if ($compact_date !== '1') {
            return $columns;
        }
        
        $new_columns = [];
        
        foreach ($columns as $key => $value) {
            // Replace default date column with compact version
            if ($key === 'date') {
                $new_columns['compact_date'] = esc_html__('Published', 'wpswitchboard');
                continue; // Skip the default date column
            }
            
            $new_columns[$key] = $value;
        }
        
        return $new_columns;
    }
    
    public function show_compact_date_column($column, $post_id) {
        if ($column !== 'compact_date') {
            return;
        }

        $post = get_post($post_id);
        if (!$post) {
            return;
        }
        $status = $post->post_status;
        
        if ($status === 'publish') {
            $date = get_the_date('Y/m/d', $post_id);
            $time = get_the_time('g:i a', $post_id);
            
            echo '<span class="sb-sp-whitespace-nowrap">';
            echo esc_html($date) . ' <strong>' . esc_html($time) . '</strong>';
            echo '</span>';
        } else {
            $status_obj = get_post_status_object($status);
            $status_label = $status_obj ? $status_obj->label : ucfirst($status);
            echo '<strong>' . esc_html($status_label) . '</strong>';
            
            if ($status === 'future') {
                $date = get_the_date('Y/m/d', $post_id);
                $time = get_the_time('g:i a', $post_id);
                echo '<br><span class="sb-sp-whitespace-nowrap">' . esc_html($date) . ' ' . esc_html($time) . '</span>';
            }
        }
    }
    
    public function sortable_columns($columns) {
        $columns['compact_date'] = 'date';
        return $columns;
    }
}

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