<?php
/**
 * Automatic Folders & Special Pages for Folderra
 * 
 * @package Folderra\AutomaticFolders
 */

if (!defined('ABSPATH')) {
    exit;
}

// ============================================
// 1. AUTOMATIC FOLDERS CREATION
// ============================================

add_action('init', 'fold82sm_create_automatic_folders', 5);
function fold82sm_create_automatic_folders() {
    if (!is_admin() || get_option('fold82sm_auto_folders_created')) {
        return;
    }
    
    $auto_folders = [
        'all-pages' => [
            'name' => 'All Pages',
            'template' => 'auto-pages',
            'post_types' => ['page']
        ],
        'all-posts' => [
            'name' => 'All Posts',
            'template' => 'auto-posts',
            'post_types' => ['post']
        ]
    ];
    
    foreach ($auto_folders as $slug => $folder_data) {
        $existing = term_exists($folder_data['name'], 'folderra_sfo_content_folder');
        
        if (!$existing) {
            $result = wp_insert_term(
                $folder_data['name'],
                'folderra_sfo_content_folder',
                ['slug' => $slug]
            );
            
            if (!is_wp_error($result)) {
                update_term_meta($result['term_id'], 'folder_template', $folder_data['template']);
                update_term_meta($result['term_id'], 'folder_display_name', $folder_data['name']);
                update_term_meta($result['term_id'], 'folder_auto_generated', true);
                update_term_meta($result['term_id'], 'folder_is_special', true);
                update_term_meta($result['term_id'], 'allowed_post_types', $folder_data['post_types']);
                update_term_meta($result['term_id'], 'folder_order', -1);
                update_term_meta($result['term_id'], 'folder_created_date', current_time('timestamp'));
            }
        }
    }
    
    update_option('fold82sm_auto_folders_created', true);
}

// ============================================
// 2. SPECIAL FOLDER PAGE REGISTRATION
// ============================================

add_action('admin_menu', 'fold82sm_add_special_folder_page');
function fold82sm_add_special_folder_page() {
    add_submenu_page(
        null,
        'Special Folder',
        'Special Folder',
        'fold82sm_access',
        'folderra-sfo-special-folder',
        'fold82sm_render_special_folder_page'
    );
}

// ============================================
// 3. SPECIAL FOLDER PAGE RENDER FUNCTION
// ============================================

function fold82sm_render_special_folder_page() {
    if (!fold82sm_current_user_can_access()) {
        wp_die(esc_html__('You do not have permission to access this page.', 'folderra-smart-folder-organizer'));
    }
    
    // Enqueue WordPress media
    wp_enqueue_media();
    
    // Determine type
    $folder_type = isset($_GET['folder_type']) ? sanitize_text_field($_GET['folder_type']) : 'pages';
    $is_pages = ($folder_type === 'pages');
    $post_type = $is_pages ? 'page' : 'post';
    
    // Find or create folder
    $slug = $is_pages ? 'all-pages' : 'all-posts';
    $folder_name = $is_pages ? 'All Pages' : 'All Posts';
    $template = $is_pages ? 'auto-pages' : 'auto-posts';
    
    $folder = get_term_by('slug', $slug, 'folderra_sfo_content_folder');
    
    if (!$folder || is_wp_error($folder)) {
        $result = wp_insert_term(
            $folder_name,
            'folderra_sfo_content_folder',
            ['slug' => $slug]
        );
        
        if (!is_wp_error($result)) {
            $folder_id = $result['term_id'];
            update_term_meta($folder_id, 'folder_template', $template);
            update_term_meta($folder_id, 'folder_display_name', $folder_name);
            update_term_meta($folder_id, 'folder_is_special', true);
            update_term_meta($folder_id, 'allowed_post_types', [$post_type]);
            update_term_meta($folder_id, 'folder_order', -1);
            
            $folder = get_term($folder_id, 'folderra_sfo_content_folder');
        }
    }
    
    if (!$folder || is_wp_error($folder)) {
        wp_die(esc_html__('Error creating or accessing special folder.', 'folderra-smart-folder-organizer'));
    }
    
    $folder_id = $folder->term_id;
    
    // Navigation
    fold82sm_navigation('dashboard');
    
    // Query setup with proper pagination
    $paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10; // Default to 10
    
    // Validate per_page
    $valid_per_page = [10, 25, 50, 100];
    if (!in_array($per_page, $valid_per_page)) {
        $per_page = 10;
    }
    
    $args = [
    'post_type'      => $post_type,
    'posts_per_page' => $per_page,
    'paged'          => $paged,

    // Use the saved manual order first, fallback to date for stable ordering
    'orderby'        => [
        'menu_order' => 'ASC',
        'date'       => 'DESC',
    ],
];

    
    // Apply status filter
    if (isset($_GET['post_status']) && $_GET['post_status'] !== 'all') {
        $status_filter = sanitize_text_field($_GET['post_status']);
        
        // Handle "Unassigned" filter
        if ($status_filter === 'unassigned') {
            // Show only posts NOT in any smart folder (excluding special folders)
            $args['post_status'] = ['publish', 'draft', 'pending', 'future', 'private'];
            
            // Get all posts that ARE in smart folders
            $posts_in_folders = get_posts([
                'post_type' => $post_type,
                'posts_per_page' => -1,
                'fields' => 'ids',
                'tax_query' => [
                    [
                        'taxonomy' => 'folderra_sfo_content_folder',
                        'operator' => 'EXISTS'
                    ]
                ]
            ]);
            
            // Filter out posts that are in smart folders
            if (!empty($posts_in_folders)) {
                $args['post__not_in'] = $posts_in_folders;
            }
        } else {
            // Normal status filter
            $args['post_status'] = $status_filter;
        }
    } else {
        $args['post_status'] = ['publish', 'draft', 'pending', 'future', 'private'];
    }
    
    // Date filter
    if (isset($_GET['date_filter']) && $_GET['date_filter'] !== 'all') {
        $date_filter = sanitize_text_field($_GET['date_filter']);
        switch ($date_filter) {
            case 'today':
                $args['date_query'] = [['year' => date('Y'), 'month' => date('m'), 'day' => date('d')]];
                break;
            case 'week':
                $args['date_query'] = [['after' => '1 week ago']];
                break;
            case 'month':
                $args['date_query'] = [['after' => '1 month ago']];
                break;
            case 'modified':
                $args['orderby'] = 'modified';
                $args['order'] = 'DESC';
                break;
        }
    }
    
    // Search filter
    if (isset($_GET['s']) && !empty($_GET['s'])) {
        $args['s'] = sanitize_text_field($_GET['s']);
    }
    
    $query = new WP_Query($args);
    $total_items = $query->found_posts;
    
    ?>
    <div class="wrap">
        <div class="special-folder-container">
            
            <!-- IMPROVED HEADER -->
<div class="special-folder-header">
    <div class="header-title-section">
    <div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
        <h1 style="margin:0;">
            <?php echo $is_pages ? '📄 ' : '📝 '; ?>
            <?php echo esc_html( $folder->name ); ?>
        </h1>

        <?php
        $settings = function_exists( 'fold82sm_get_settings' ) ? fold82sm_get_settings() : array();
        $show_default_link = false;
        $default_url = '';

        if ( $is_pages && ! empty( $settings['redirect_pages_to_all'] ) ) {
            $show_default_link = true;
            $default_url = add_query_arg(
                array(
                    'post_type'        => 'page',
                    'folderra_bypass'  => 1,
                ),
                admin_url( 'edit.php' )
            );
        }

        if ( ! $is_pages && ! empty( $settings['redirect_posts_to_all'] ) ) {
            $show_default_link = true;
            $default_url = add_query_arg(
                array(
                    'folderra_bypass'  => 1,
                ),
                admin_url( 'edit.php' )
            );
        }

        if ( $show_default_link ) :
        ?>
            <a href="<?php echo esc_url( $default_url ); ?>" style="font-size:12px; font-weight:500; text-decoration:none; color:#2271b1; white-space:nowrap;">
                <?php esc_html_e( 'View default screen', 'folderra-smart-folder-organizer' ); ?>
            </a>
        <?php endif; ?>
    </div>

    <p class="header-subtitle">
        <?php echo $is_pages
            ? __('Manage all your pages in one place', 'folderra-smart-folder-organizer')
            : __('Manage all your blog posts in one place', 'folderra-smart-folder-organizer'); ?>
    </p>
</div>            

    <!-- Info bar with Add New button (NO per_page here anymore) -->
    <div class="folder-info-bar">
        <span class="folder-info-item">
            <span class="dashicons dashicons-<?php echo $is_pages ? 'admin-page' : 'edit'; ?>"></span>
            <strong id="current-items-count"><?php echo (int) $total_items; ?></strong>
            <?php echo $is_pages ? 'Pages' : 'Posts'; ?>
        </span>

        <span class="folder-info-item">
            <span class="dashicons dashicons-visibility"></span>
            <strong><?php echo esc_html__('Template:', 'folderra-smart-folder-organizer'); ?></strong>
            <?php echo $is_pages ? 'All Pages' : 'All Posts'; ?>
        </span>

        <?php $new_url = $is_pages ? admin_url('post-new.php?post_type=page') : admin_url('post-new.php'); ?>
        <a href="<?php echo esc_url($new_url); ?>" class="button button-primary add-new-button">
            <span class="dashicons dashicons-plus-alt"></span>
            <?php echo $is_pages ? esc_html__('Add New Page', 'folderra-smart-folder-organizer') : esc_html__('Add New Post', 'folderra-smart-folder-organizer'); ?>
        </a>
    </div>
</div>

<!-- FILTERS ON SINGLE ROW - UPDATED (per_page IS INSIDE THE FORM) -->
<div class="folder-filters-section">
    <form method="get" class="special-folder-filters">
        <input type="hidden" name="page" value="folderra-sfo-special-folder">
        <input type="hidden" name="folder_type" value="<?php echo esc_attr($folder_type); ?>">
        <input type="hidden" name="_wpnonce" value="<?php echo esc_attr($_GET['_wpnonce'] ?? ''); ?>">
        <input type="hidden" name="paged" value="1">
        <div class="filters-inline">

            <!-- Status -->
            <div class="filter-group-inline">
                <label>Status:</label>
                <select name="post_status">
                    <?php
                    $statuses = [
                        'all'        => 'All',
                        'publish'    => 'Published',
                        'draft'      => 'Draft',
                        'pending'    => 'Pending',
                        'unassigned' => 'Unassigned',
                    ];
                    $current_status = isset($_GET['post_status']) ? sanitize_text_field($_GET['post_status']) : 'all';
                    foreach ($statuses as $value => $label) {
                        echo '<option value="' . esc_attr($value) . '" ' . selected($current_status, $value, false) . '>' . esc_html($label) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <!-- Date -->
            <div class="filter-group-inline">
                <label>Date:</label>
                <select name="date_filter">
                    <?php
                    $date_filters = [
                        'all'      => 'All Dates',
                        'today'    => 'Today',
                        'week'     => 'This Week',
                        'month'    => 'This Month',
                        'modified' => 'Recently Modified',
                    ];
                    $current_date_filter = isset($_GET['date_filter']) ? sanitize_text_field($_GET['date_filter']) : 'all';
                    foreach ($date_filters as $value => $label) {
                        echo '<option value="' . esc_attr($value) . '" ' . selected($current_date_filter, $value, false) . '>' . esc_html($label) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <!-- Items (per_page) - MOVED HERE -->
            <div class="filter-group-inline">
                <label>Items:</label>
                <select name="per_page" onchange="this.form.paged.value=1; this.form.submit();">
                    <?php
                    $per_page_options = [10, 25, 50, 100];
                    foreach ($per_page_options as $value) {
                        echo '<option value="' . esc_attr($value) . '" ' . selected($per_page, $value, false) . '>' . esc_html($value) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <!-- Column Visibility -->
            <div class="filter-group-inline">
                <label>Columns:</label>
                <button type="button" id="toggle-columns-btn" class="button" style="padding: 8px 12px; font-size: 13px;">
                    <span class="dashicons dashicons-visibility" style="vertical-align: middle;"></span>
                    Show/Hide
                </button>
            </div>

            <!-- Search -->
            <div class="filter-group-inline search-group">
                <label>Search:</label>
                <input
                    type="text"
                    name="s"
                    value="<?php echo isset($_GET['s']) ? esc_attr($_GET['s']) : ''; ?>"
                    placeholder="<?php echo $is_pages ? esc_attr__('Search pages...', 'folderra-smart-folder-organizer') : esc_attr__('Search posts...', 'folderra-smart-folder-organizer'); ?>"
                >
            </div>

            <!-- Buttons -->
            <div class="filter-buttons-group">
                <button type="submit" class="button button-primary">Apply</button>

                <?php if (isset($_GET['post_status']) || isset($_GET['date_filter']) || isset($_GET['s']) || isset($_GET['per_page'])) : ?>
                    <a href="<?php echo esc_url(remove_query_arg(['post_status', 'date_filter', 's', 'per_page', 'paged'])); ?>"
                       class="button">Reset</a>
                <?php endif; ?>
            </div>

        </div>
    </form>
</div>
            
            <!-- TWO COLUMN LAYOUT -->
            <div class="folder-content-section">
                
                <!-- LEFT SIDEBAR - Smart Folders -->
                <div class="smart-folders-sidebar">
                    <h3>
                        <span class="dashicons dashicons-category"></span>
                        <?php _e('Smart Folders', 'folderra-smart-folder-organizer'); ?>
                    </h3>
                    
                    <?php
                    // Get smart folders compatible with this post type
                    $smart_folders = get_terms([
                        'taxonomy' => 'folderra_sfo_content_folder',
                        'hide_empty' => false,
                        'meta_query' => [
                            'relation' => 'AND',
                            [
                                'key' => 'folder_is_special',
                                'compare' => 'NOT EXISTS'
                            ],
                            [
                                'key' => 'allowed_post_types',
                                'value' => $post_type,
                                'compare' => 'LIKE'
                            ]
                        ]
                    ]);
                    
                    if (!empty($smart_folders) && !is_wp_error($smart_folders)) {
                        echo '<ul class="smart-folders-list">';
                        foreach ($smart_folders as $smart_folder) {
                            // Check if folder can contain this post type
                            $allowed_types = get_term_meta($smart_folder->term_id, 'allowed_post_types', true);
                            $template = get_term_meta($smart_folder->term_id, 'folder_template', true);
                            
                            // Skip dynamic folders (tag-folder, category-folder, media-folder)
                            if (in_array($template, ['tag-folder', 'category-folder', 'media-folder'])) {
                                continue;
                            }
                            
                            // Check compatibility
                            $is_compatible = false;
                            if (is_array($allowed_types)) {
                                $is_compatible = in_array($post_type, $allowed_types);
                            } elseif ($allowed_types === 'mixed' || empty($allowed_types)) {
                                $is_compatible = true;
                            }
                            
                            if (!$is_compatible) {
                                continue;
                            }
                            
                            $details_url = admin_url('admin.php?page=folderra-sfo-folder-details&folder_id=' . $smart_folder->term_id);
                            $nonce = wp_create_nonce('folderra_sfo_folder_details_nonce');
                            $details_url = add_query_arg('_wpnonce', $nonce, $details_url);
                            
                            echo '<li>';
                            echo '<a href="' . esc_url($details_url) . '" class="smart-folder-link" data-folder-id="' . esc_attr($smart_folder->term_id) . '">';
                            echo '<span class="folder-icon">📁</span>';
                            echo esc_html($smart_folder->name);
                            echo ' <span class="folder-count">(' . $smart_folder->count . ')</span>';
                            echo '</a>';
                            echo '</li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p class="no-folders-message">' . __('No smart folders yet.', 'folderra-smart-folder-organizer') . '</p>';
                    }
                    ?>
                    
                    <!-- Create Smart Folder - Automatic and contextual -->
                    <button id="create-smart-folder-btn" class="button button-primary create-folder-btn" 
                            data-post-type="<?php echo esc_attr($post_type); ?>"
                            data-folder-type="<?php echo esc_attr($folder_type); ?>">
                        <span class="dashicons dashicons-plus-alt"></span>
                        <?php _e('Create Smart Folder', 'folderra-smart-folder-organizer'); ?>
                    </button>
                </div>
                
                <!-- MAIN CONTENT -->
                <div class="content-list-main">
                    <?php if ($query->have_posts()) : ?>
                        
                        <!-- Bulk Actions -->
                        <div id="bulk-actions-bar" style="display: none; margin-bottom: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px; border: 1px solid #ddd;">
                            <div style="display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">
                                <strong style="font-size: 14px;">
                                    <span id="bulk-selected-count">0</span> items selected
                                </strong>
                                
                                <select id="bulk-folder-select" style="padding: 8px 12px; border-radius: 6px;">
                                    <option value="">Add to Smart Folder...</option>
                                    <?php
                                    if (!empty($smart_folders) && !is_wp_error($smart_folders)) {
                                        foreach ($smart_folders as $folder) {
                                            // Check compatibility
                                            $allowed_types = get_term_meta($folder->term_id, 'allowed_post_types', true);
                                            $template = get_term_meta($folder->term_id, 'folder_template', true);
                                            
                                            // Skip dynamic folders
                                            if (in_array($template, ['tag-folder', 'category-folder', 'media-folder'])) {
                                                continue;
                                            }
                                            
                                            $is_compatible = false;
                                            if (is_array($allowed_types)) {
                                                $is_compatible = in_array($post_type, $allowed_types);
                                            } elseif ($allowed_types === 'mixed' || empty($allowed_types)) {
                                                $is_compatible = true;
                                            }
                                            
                                            if ($is_compatible) {
                                                echo '<option value="' . esc_attr($folder->term_id) . '">' . esc_html($folder->name) . '</option>';
                                            }
                                        }
                                    }
                                    ?>
                                </select>
                                
                                <button id="bulk-add-to-folder-btn" class="button button-primary" disabled>
                                    <span class="dashicons dashicons-plus-alt" style="vertical-align: middle;"></span>
                                    Add to Folder
                                </button>
                                
                                <button id="bulk-trash-btn" class="button" style="color: #b32d2e;">
                                    <span class="dashicons dashicons-trash" style="vertical-align: middle;"></span>
                                    Move to Trash
                                </button>
                                
                                <button id="bulk-clear-btn" class="button">Clear Selection</button>
                            </div>
                        </div>
                        
                        <table class="wp-list-table widefat fixed striped" id="content-table">
    <thead>
        <tr>
            <!-- Checkbox column -->
            <th class="check-column">
                <input type="checkbox" id="select-all-items">
            </th>
            <th class="drag-column"></th>
            
            <!-- Title - ALWAYS VISIBLE -->
            <th class="title-column-header">Title</th>
            
            <!-- Author - default visible -->
            <th class="author-column-header" style="display: table-cell;">Author</th>
            
            <!-- Date - default visible -->
            <th class="date-column-header" style="display: table-cell;">Date</th>
                                   
            <!-- Smart Folders column - NEW - default HIDDEN -->
            <th class="smartfolders-column-header" style="display: none;">Smart Folders</th>
            
            <!-- Categories - ONLY for posts - default HIDDEN -->
            <?php if (!$is_pages) : ?>
                <th class="categories-column-header" style="display: none;">Categories</th>
            <?php endif; ?>
            
            <!-- Tags - ONLY for posts - default HIDDEN -->
            <?php if (!$is_pages) : ?>
                <th class="tags-column-header" style="display: none;">Tags</th>
            <?php endif; ?>
        </tr>
    </thead>
    <tbody id="the-list" class="ui-sortable">
        <?php while ($query->have_posts()) : $query->the_post(); global $post; ?>
            <tr id="post-<?php echo $post->ID; ?>" class="sortable-row" data-post-id="<?php echo $post->ID; ?>">
                
                <!-- Checkbox -->
                <td class="check-column">
                    <input type="checkbox" class="item-checkbox" value="<?php echo $post->ID; ?>">
                </td>
                
                <!-- Drag Handle -->
                <td class="drag-column">
                    <button type="button" class="drag-handle" title="Drag to reorder">
                        <span class="dashicons dashicons-menu"></span>
                    </button>
                </td>
                
                <!-- Title (wider) -->
                <td class="title-column">
                    <strong>
                        <a href="<?php echo esc_url(get_edit_post_link()); ?>" class="row-title">
                            <?php echo get_the_title(); ?>
                        </a>
                        <?php if (get_post_status() !== 'publish') : ?>
                            <span class="post-state-badge">
                                <?php echo ucfirst(get_post_status()); ?>
                            </span>
                        <?php endif; ?>
                    </strong>
                    
                    <!-- Row actions -->
                    <div class="row-actions">
                        <span class="edit">
                            <a href="<?php echo esc_url(get_edit_post_link()); ?>">Edit</a> |
                        </span>
                        <span class="view">
                            <a href="<?php echo esc_url(get_permalink()); ?>" target="_blank">View</a> |
                        </span>
                        <span class="duplicate">
                            <a href="#" class="duplicate-post" data-post-id="<?php echo $post->ID; ?>" data-post-title="<?php echo esc_attr(get_the_title()); ?>">Duplicate</a> |
                        </span>
                        <span class="trash">
                            <a href="#" class="trash-post" data-post-id="<?php echo $post->ID; ?>" data-post-title="<?php echo esc_attr(get_the_title()); ?>">Trash</a>
                        </span>
                    </div>
                </td>
                
                <!-- Author -->
                <td class="author-column"><?php echo esc_html(get_the_author()); ?></td>
                
                <!-- Date -->
                <td class="date-column"><?php echo esc_html(get_the_date()); ?></td>                              
                
                <!-- Smart Folders column -->
                <td class="smartfolders-column" style="display: none;">
                    <?php
                    // Get smart folders for this post (EXCLUDING special auto folders)
                    $post_folders = wp_get_object_terms($post->ID, 'folderra_sfo_content_folder');
                    
                    if (!empty($post_folders) && !is_wp_error($post_folders)) {
                        echo '<ul class="smartfolders-list">';
                        foreach ($post_folders as $folder) {
                            // Skip special auto-generated folders
                            $is_special = get_term_meta($folder->term_id, 'folder_is_special', true);
                            if ($is_special) {
                                continue;
                            }
                            
                            // Only show folders compatible with this post type
                            $allowed_types = get_term_meta($folder->term_id, 'allowed_post_types', true);
                            $template = get_term_meta($folder->term_id, 'folder_template', true);
                            
                            // Skip dynamic folders
                            if (in_array($template, ['tag-folder', 'category-folder', 'media-folder'])) {
                                continue;
                            }
                            
                            $is_compatible = false;
                            if (is_array($allowed_types)) {
                                $is_compatible = in_array($post->post_type, $allowed_types);
                            } elseif ($allowed_types === 'mixed' || empty($allowed_types)) {
                                $is_compatible = true;
                            }
                            
                            if (!$is_compatible) {
                                continue;
                            }
                            
                            $details_url = admin_url('admin.php?page=folderra-sfo-folder-details&folder_id=' . $folder->term_id);
                            $nonce = wp_create_nonce('folderra_sfo_folder_details_nonce');
                            $details_url = add_query_arg('_wpnonce', $nonce, $details_url);
                            
                            echo '<li>';
                            echo '<a href="' . esc_url($details_url) . '" class="smartfolder-tag" title="View folder: ' . esc_attr($folder->name) . '">';
                            echo esc_html($folder->name);
                            echo '</a>';
                            echo '</li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<span style="color: #999; font-size: 12px;">—</span>';
                    }
                    ?>
                </td>
                
                <!-- Categories - ONLY for posts -->
                <?php if (!$is_pages) : ?>
                    <td class="categories-column" style="display: none;">
                        <?php
                        $categories = get_the_category();
                        if (!empty($categories)) {
                            $cat_names = array_map(function($cat) {
                                return esc_html($cat->name);
                            }, $categories);
                            echo implode(', ', $cat_names);
                        } else {
                            echo '<span style="color: #999;">—</span>';
                        }
                        ?>
                    </td>
                <?php endif; ?>
                
                <!-- Tags - ONLY for posts -->
                <?php if (!$is_pages) : ?>
                    <td class="tags-column" style="display: none;">
                        <?php
                        $tags = get_the_tags();
                        if (!empty($tags)) {
                            $tag_names = array_map(function($tag) {
                                return esc_html($tag->name);
                            }, $tags);
                            echo implode(', ', $tag_names);
                        } else {
                            echo '<span style="color: #999;">—</span>';
                        }
                        ?>
                    </td>
                <?php endif; ?>
            </tr>
        <?php endwhile; ?>
    </tbody>
</table>
                        
                        <!-- CORRECT PAGINATION -->
                        <?php if ($query->max_num_pages > 1) : ?>
                            <div class="tablenav bottom">
                                <div class="tablenav-pages">
                                    <?php
                                    $current_url = remove_query_arg('paged');
                                    $pagination_args = [
                                        'base' => add_query_arg('paged', '%#%', $current_url),
                                        'format' => '',
                                        'current' => max(1, $paged),
                                        'total' => $query->max_num_pages,
                                        'prev_text' => '« ' . __('Previous', 'folderra-smart-folder-organizer'),
                                        'next_text' => __('Next', 'folderra-smart-folder-organizer') . ' »',
                                        'type' => 'plain'
                                    ];
                                    echo paginate_links($pagination_args);
                                    ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                    <?php else : ?>
                        <div class="no-content-message">
                            <div class="no-content-icon">
                                <?php echo $is_pages ? '📄' : '📝'; ?>
                            </div>
                            <h3><?php echo $is_pages ? __('No pages found', 'folderra-smart-folder-organizer') : __('No posts found', 'folderra-smart-folder-organizer'); ?></h3>
                            <p><?php _e('Create your first one to get started!', 'folderra-smart-folder-organizer'); ?></p>
                            <a href="<?php echo esc_url($new_url); ?>" class="button button-primary">
                                <span class="dashicons dashicons-plus-alt"></span>
                                <?php echo $is_pages ? __('Add New Page', 'folderra-smart-folder-organizer') : __('Add New Post', 'folderra-smart-folder-organizer'); ?>
                            </a>
                        </div>
                    <?php endif; ?>
                    
                    <?php wp_reset_postdata(); ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php
}

// ============================================
// 4. AJAX HANDLERS
// ============================================

// Save post order
add_action('wp_ajax_fold82sm_save_post_order', 'fold82sm_save_post_order');
function fold82sm_save_post_order() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if ( ! current_user_can('fold82sm_access') ) {
        wp_send_json_error( array( 'message' => 'Permission denied.' ) );
    }

    $order     = isset($_POST['order']) ? array_map('absint', (array) $_POST['order']) : array();
    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';

    if ( empty($order) ) {
        wp_send_json_error( array( 'message' => 'No order data received.' ) );
    }

    // Read pagination context to avoid menu_order duplicates across pages
    $page     = isset($_POST['page']) ? max(1, absint($_POST['page'])) : 1;
    $per_page = isset($_POST['per_page']) ? max(1, absint($_POST['per_page'])) : 10;
    $offset   = ( $page - 1 ) * $per_page;

    foreach ( $order as $index => $post_id ) {
        wp_update_post( array(
            'ID'         => $post_id,
            'menu_order' => $offset + $index,
        ) );
    }

    wp_send_json_success( array( 'message' => 'Order saved successfully.' ) );
}

// Duplicate post
add_action('wp_ajax_fold82sm_duplicate_post', 'fold82sm_duplicate_post');
function fold82sm_duplicate_post() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => 'Permission denied.']);
    }
    
    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $post = get_post($post_id);
    
    if (!$post) {
        wp_send_json_error(['message' => 'Post not found.']);
    }
    
    $new_post = [
        'post_title'   => $post->post_title . ' (Copy)',
        'post_content' => $post->post_content,
        'post_excerpt' => $post->post_excerpt,
        'post_status'  => 'draft',
        'post_type'    => $post->post_type,
        'post_author'  => get_current_user_id()
    ];
    
    $new_post_id = wp_insert_post($new_post);
    
    if (is_wp_error($new_post_id)) {
        wp_send_json_error(['message' => 'Error creating duplicate.']);
    }
    
    // Copy meta
    $meta_data = get_post_meta($post_id);
    foreach ($meta_data as $key => $values) {
        foreach ($values as $value) {
            add_post_meta($new_post_id, $key, maybe_unserialize($value));
        }
    }
    
    // Copy terms
    $taxonomies = get_object_taxonomies($post->post_type);
    foreach ($taxonomies as $taxonomy) {
        $terms = wp_get_object_terms($post_id, $taxonomy, ['fields' => 'slugs']);
        if (!empty($terms) && !is_wp_error($terms)) {
            wp_set_object_terms($new_post_id, $terms, $taxonomy);
        }
    }
    
    // Copy thumbnail
    $thumbnail_id = get_post_thumbnail_id($post_id);
    if ($thumbnail_id) {
        set_post_thumbnail($new_post_id, $thumbnail_id);
    }
    
    wp_send_json_success([
        'message' => 'Duplicated successfully.',
        'new_post_id' => $new_post_id,
        'edit_url' => get_edit_post_link($new_post_id, '')
    ]);
}

// Bulk add to folder
add_action('wp_ajax_fold82sm_bulk_add_to_folder', 'fold82sm_bulk_add_to_folder');
function fold82sm_bulk_add_to_folder() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => 'Permission denied.']);
    }
    
    $post_ids = isset($_POST['post_ids']) ? array_map('absint', $_POST['post_ids']) : [];
    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;
    
    if (empty($post_ids) || !$folder_id) {
        wp_send_json_error(['message' => 'Invalid data.']);
    }
    
    $success_count = 0;
    foreach ($post_ids as $post_id) {
        $result = wp_set_object_terms($post_id, [$folder_id], 'folderra_sfo_content_folder', true);
        if (!is_wp_error($result)) {
            $success_count++;
        }
    }
    
    wp_send_json_success([
        'message' => $success_count . ' items added to folder.',
        'count' => $success_count
    ]);
}

// Bulk trash
add_action('wp_ajax_fold82sm_bulk_trash', 'fold82sm_bulk_trash');
function fold82sm_bulk_trash() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => 'Permission denied.']);
    }
    
    $post_ids = isset($_POST['post_ids']) ? array_map('absint', $_POST['post_ids']) : [];
    
    if (empty($post_ids)) {
        wp_send_json_error(['message' => 'No items selected.']);
    }
    
    $success_count = 0;
    foreach ($post_ids as $post_id) {
        if (wp_trash_post($post_id)) {
            $success_count++;
        }
    }
    
    wp_send_json_success([
        'message' => $success_count . ' items moved to trash.',
        'count' => $success_count
    ]);
}

// Single trash with confirm
add_action('wp_ajax_fold82sm_trash_post', 'fold82sm_trash_post');
function fold82sm_trash_post() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => 'Permission denied.']);
    }
    
    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    
    if (!$post_id) {
        wp_send_json_error(['message' => 'Invalid post ID.']);
    }
    
    if (wp_trash_post($post_id)) {
        wp_send_json_success(['message' => 'Item moved to trash.']);
    } else {
        wp_send_json_error(['message' => 'Error moving to trash.']);
    }
}

// Create Smart Folder automatic
add_action('wp_ajax_fold82sm_create_smart_folder_auto', 'fold82sm_create_smart_folder_auto');
function fold82sm_create_smart_folder_auto() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => 'Permission denied.']);
    }
    
    $folder_name = isset($_POST['folder_name']) ? sanitize_text_field($_POST['folder_name']) : '';
    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';
    
    if (empty($folder_name)) {
        wp_send_json_error(['message' => 'Folder name required.']);
    }
    
    // Create folder
    $result = wp_insert_term(
        $folder_name,
        'folderra_sfo_content_folder',
        ['slug' => sanitize_title($folder_name)]
    );
    
    if (is_wp_error($result)) {
        wp_send_json_error(['message' => $result->get_error_message()]);
    }
    
    $folder_id = $result['term_id'];
    
    // Set metadata
    update_term_meta($folder_id, 'folder_template', 'standard');
    update_term_meta($folder_id, 'folder_display_name', $folder_name);
    update_term_meta($folder_id, 'allowed_post_types', [$post_type]);
    update_term_meta($folder_id, 'folder_order', 0);
    update_term_meta($folder_id, 'folder_created_date', current_time('timestamp'));
    
    // Create URL for details
    $details_url = admin_url('admin.php?page=folderra-sfo-folder-details&folder_id=' . $folder_id);
    $nonce = wp_create_nonce('folderra_sfo_folder_details_nonce');
    $details_url = add_query_arg('_wpnonce', $nonce, $details_url);
    
    wp_send_json_success([
        'message' => 'Smart folder created successfully.',
        'folder_id' => $folder_id,
        'folder_name' => $folder_name,
        'details_url' => $details_url,
        'count' => 0
    ]);
}