<?php
/**
 * Plugin Name: Folderra – Smart Folder Organizer for WordPress Pages & Posts
 * Plugin URI: https://wpsmartfolder.com
 * Description: Organize your WordPress pages and posts with smart folders, drag & drop, and advanced structure management.
 * Version: 1.4.0
 * Author: DaveLabs
 * Text Domain: folderra-smart-folder-organizer
 * Domain Path: /languages
 * Requires at least: 6.0
 * Tested up to: 6.9.1
 * Requires PHP: 7.4
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

// Main version constant
define('FOLD82SM_VERSION', '1.4.0');

// Backward compatibility for PRO plugin integration
if (!defined('FOLD82SM_VERSION')) {
    define('FOLD82SM_VERSION', FOLD82SM_VERSION);
}

// ===== INTERNATIONALIZATION =====
// Note: WordPress.org automatically loads translations - no need for manual load_plugin_textdomain()

// ===== NOTICES MANAGEMENT =====

// Define a centralized list of plugin page slugs
if (!defined('FOLD82SM_PAGE_SLUGS')) {
    define('FOLD82SM_PAGE_SLUGS', wp_json_encode(array(
        'folderra-sfo-dashboard',    // Main dashboard
        'folderra-sfo-new-folder',   // "New Folder" page
        'folderra-sfo-folders',      // Folder list
        'folderra-sfo-folder-details', // Hidden details screen
        'fold82sm-settings',         // Settings page
        'folderra-sfo-special-folder', // Special folder page
        'folderra-sfo-media-organizer', // Media Organizer page (hidden page)
    )));
}

/**
 * Detect if the current screen is from our plugin.
 * Replaces fold82sm_is_plugin_page() with enhanced detection
 */
function fold82sm_is_plugin_screen() {
    // EARLY RETURN.
    if (!did_action('init') || !is_admin()) {
        return false;
    }

    $our_slugs = json_decode(FOLD82SM_PAGE_SLUGS, true);

    // Verify by ?page=.
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
    
    if ($page && in_array($page, $our_slugs, true)) {
        return true;
    }

    // Verify by get_current_screen().
    if (function_exists('get_current_screen')) {
        $screen = get_current_screen();

        if ($screen && isset($screen->id)) {
            // Accept any screen ID that contains one of our slugs.
            foreach ($our_slugs as $slug) {
                if (false !== strpos($screen->id, $slug)) {
                    return true;
                }
            }
        }
    }

    return false;
}

/**
 * Add a custom body class on Folderra pages (used to style/hide notices via CSS)
 */
add_filter('admin_body_class', 'fold82sm_admin_body_class');
function fold82sm_admin_body_class($classes) {
    if (fold82sm_is_plugin_screen()) {
        $classes .= ' folderra-admin-page';
    }
    return $classes;
}

/**
 * Get the number of folders that are actually visible in the Folders screen.
 * This respects all the same filters applied by fold82sm_get_filtered_folders()
 * (e.g. nested folders, special folders, and PRO-only folders when PRO is inactive/unlicensed).
 *
 * @return int
 */
function fold82sm_get_visible_folders_count() {
    if ( ! function_exists( 'fold82sm_get_filtered_folders' ) ) {
        return 0;
    }

    $result = fold82sm_get_filtered_folders( array(
        'page'        => 1,
        'per_page'    => 0,     // 0 = no pagination slicing in our implementation
        'folder_type' => 'all',
        'search'      => '',
    ) );

    if ( ! is_array( $result ) || empty( $result['pagination']['total_items'] ) ) {
        return 0;
    }

    return (int) $result['pagination']['total_items'];
}

/**
 * Custom plugin notices with folder count check for welcome notice
 */
function fold82sm_custom_notices() {
    if (!fold82sm_is_plugin_screen()) {
        return; // Exit if not on our plugin pages
    }
    
    // Welcome notice - only show if user has 0 folders
    if (get_option('fold82sm_show_welcome')) {
        // Check if any folders already exist
        $folders_count = fold82sm_get_visible_folders_count();
        
        // If error or 0 folders, show welcome
        if ($folders_count === 0) {
            echo '<div class="notice notice-info is-dismissible fold82sm-notice"><p>' . 
                 esc_html__('Welcome to Folderra! You can now create your first folder.', 'folderra-smart-folder-organizer') . 
                 '</p></div>';
        }
        
        // Always delete the option after checking
        delete_option('fold82sm_show_welcome');
    }

    // Database update notice (example - uses transient)
    if (get_transient('fold82sm_db_updated')) {
        echo '<div class="notice notice-success fold82sm-notice"><p>' . 
             esc_html__('Database optimized for better performance.', 'folderra-smart-folder-organizer') . 
             '</p></div>';
        delete_transient('fold82sm_db_updated');
    }
}

/**
 * Enhanced notice cleanup - removes intrusive plugin notices while keeping WordPress core
 */
add_action('in_admin_header', 'fold82sm_clean_notices', 999);
function fold82sm_clean_notices() {
    if (!fold82sm_is_plugin_screen()) {
        return;
    }

    global $wp_filter;
    
    $notice_hooks = array('admin_notices', 'all_admin_notices');
    
    foreach ($notice_hooks as $hook) {
        if (isset($wp_filter[$hook])) {
            foreach ($wp_filter[$hook]->callbacks as $priority => $callbacks) {
                foreach ($callbacks as $callback_key => $callback) {
                    // Keep WordPress core update notices (start with 'update_')
                    if (is_array($callback['function']) && 
                        isset($callback['function'][1]) && 
                        strpos($callback['function'][1], 'update_') === 0) {
                        continue;
                    }
                    
                    remove_action($hook, $callback['function'], $priority);
                }
            }
        }
    }
    
    // Re-attach only our plugin's notices
    add_action('admin_notices', 'fold82sm_custom_notices');
}

/**
 * Footer (left): replaces "Thank you for creating with WordPress."
 * on plugin pages only.
 */
add_filter('admin_footer_text', function($text) {
    if (!fold82sm_is_plugin_screen()) {
        return $text;
    }

    $link_html = '<a href="https://wpsmartfolder.com" target="_blank" rel="noopener noreferrer">Folderra Smart Folder</a>';

    $allowed_tags = array(
        'a' => array(
            'href'   => array(),
            'target' => array(),
            'rel'    => array(),
        ),
    );

    return sprintf(        
        wp_kses(
            /* translators: %s: plugin name with link. */
            __('Thanks for organizing with %s — focus on creating, not searching.', 'folderra-smart-folder-organizer'),
            $allowed_tags
        ),
        $link_html
    );
}, 20);

/**
 * Footer (right): shows plugin version + WP version
 * only on our pages (elsewhere the WordPress version remains).
 */
add_filter('update_footer', function($text) {
    if (!fold82sm_is_plugin_screen()) {
        return $text;
    }

    $plugin_ver = defined('FOLD82SM_VERSION') ? FOLD82SM_VERSION : '1.0.2';

    return sprintf(
        /* translators: 1: plugin version, 2: WordPress version. */
        esc_html__('Folderra Smart Folder v%1$s • WordPress %2$s', 'folderra-smart-folder-organizer'),
        esc_html($plugin_ver),
        esc_html(get_bloginfo('version'))
    );
}, 999);


// ===== CORE FUNCTIONS =====

/**
 * Register Folderra "Smart Folder" taxonomy (private) for posts and pages.
 * Goal: prevent WordPress from adding its default taxonomy meta box (Classic Editor),
 * because Folderra provides its own custom meta box UI.
 */
add_action( 'init', 'fold82sm_register_taxonomy' );
function fold82sm_register_taxonomy() {

	$labels = array(
		'name'              => _x( 'Smart Folders', 'taxonomy general name', 'folderra-smart-folder-organizer' ),
		'singular_name'     => _x( 'Smart Folder', 'taxonomy singular name', 'folderra-smart-folder-organizer' ),
		'search_items'      => __( 'Search Smart Folders', 'folderra-smart-folder-organizer' ),
		'all_items'         => __( 'All Smart Folders', 'folderra-smart-folder-organizer' ),
		'parent_item'       => __( 'Parent Smart Folder', 'folderra-smart-folder-organizer' ),
		'parent_item_colon' => __( 'Parent Smart Folder:', 'folderra-smart-folder-organizer' ),
		'edit_item'         => __( 'Edit Smart Folder', 'folderra-smart-folder-organizer' ),
		'update_item'       => __( 'Update Smart Folder', 'folderra-smart-folder-organizer' ),
		'add_new_item'      => __( 'Add New Smart Folder', 'folderra-smart-folder-organizer' ),
		'new_item_name'     => __( 'New Smart Folder Name', 'folderra-smart-folder-organizer' ),
		'menu_name'         => __( 'Smart Folders', 'folderra-smart-folder-organizer' ),
	);

	$args = array(
		'hierarchical'       => true,
		'labels'             => $labels,

		// Keep taxonomy available in admin (Folderra uses it), but not exposed publicly.
		'show_ui'            => true,
		'show_admin_column'  => false,
		'show_in_menu'       => false,
		'show_in_quick_edit' => false,

		'public'             => false,
		'publicly_queryable' => false,
		'query_var'          => false,
		'rewrite'            => false,

		// Gutenberg support (Folderra still hides the default panel via JS later).
		'show_in_rest'       => true,

		// Prevent WP from creating the default taxonomy meta box (Classic Editor).
		// This does NOT affect Categories/Tags meta boxes.
		'meta_box_cb'        => false,
	);

	// Register for posts and pages.
	register_taxonomy( 'folderra_sfo_content_folder', array( 'page', 'post' ), $args );
}

/**
 * Extra safety: if another plugin/theme re-adds the default meta box,
 * remove it anyway across all contexts.
 *
 * Note: This only targets Folderra taxonomy metabox ID:
 * folderra_sfo_content_folderdiv (Classic Editor).
 */
add_action( 'add_meta_boxes', 'fold82sm_remove_default_taxonomy_metabox', 1000 );
function fold82sm_remove_default_taxonomy_metabox() {

	if ( function_exists( 'fold82sm_current_user_can_access' ) && ! fold82sm_current_user_can_access() ) {
		return;
	}

	$post_types = array( 'post', 'page' );
	$contexts   = array( 'side', 'normal', 'advanced' );

	foreach ( $post_types as $pt ) {
		foreach ( $contexts as $ctx ) {
			remove_meta_box( 'folderra_sfo_content_folderdiv', $pt, $ctx );
		}
	}
}


// Initialize folder ordering and display names
add_action('init', 'fold82sm_initialize_data');
function fold82sm_initialize_data() {
    // Only run in admin
    if (!is_admin()) {
        return;
    }
    
    $folders = get_terms([
        'taxonomy' => 'folderra_sfo_content_folder', 
        'hide_empty' => false,
        'fields' => 'ids',
        'number' => 0
    ]);
    
    if (is_wp_error($folders) || empty($folders)) {
        return;
    }
    
    foreach ($folders as $folder_id) {
        $updates = [];
        
        // Set creation date if not exists (use current time for new folders)
        $created_date = get_term_meta($folder_id, 'folder_created_date', true);
        if ($created_date === '') {
            update_term_meta($folder_id, 'folder_created_date', current_time('timestamp'));
            $updates[] = 'created_date';
        }
        
        // Initialize display name if not set
        $current_display_name = get_term_meta($folder_id, 'folder_display_name', true);
        if ($current_display_name === '') {
            $term = get_term($folder_id);
            if ($term && !is_wp_error($term)) {
                update_term_meta($folder_id, 'folder_display_name', $term->name);
                $updates[] = 'display_name';
            }
        }
        
        // Initialize template if not set
        $current_template = get_term_meta($folder_id, 'folder_template', true);
        if ($current_template === '') {
            update_term_meta($folder_id, 'folder_template', 'mixed');
            $updates[] = 'template';
        }
        
        // Clear cache if updated
        if (!empty($updates)) {
            clean_term_cache($folder_id, 'folderra_sfo_content_folder');
        }
    }
}


// ===== CAPABILITY MANAGEMENT =====

/**
 * Get Folderra settings with defaults.
 *
 * @return array
 */
function fold82sm_get_settings() {
    $defaults = array(
        'allowed_roles'          => array( 'administrator', 'editor' ),
        'redirect_pages_to_all'  => 1,
        'redirect_posts_to_all'  => 1,
    );

    $settings = get_option( 'fold82sm_settings', array() );

    if ( ! is_array( $settings ) ) {
        $settings = array();
    }

    return wp_parse_args( $settings, $defaults );
}

/**
 * Check if current user can access Folderra Smart Folder
 * This is the main capability check function
 */
function fold82sm_current_user_can_access() {
    // Get current user
    $user = wp_get_current_user();
    
    // Get settings
    $settings = fold82sm_get_settings();
    
    // Always allow administrators (super admin in multisite)
    if (in_array('administrator', (array) $user->roles)) {
        return true;
    }
    
    // Check if user has any allowed role
    foreach ((array) $user->roles as $user_role) {
        if (in_array($user_role, $settings['allowed_roles'])) {
            return true;
        }
    }
    
    return false;
}

/**
 * Setup capabilities for Folderra Smart Folder based on saved settings
 * This runs on init to ensure capabilities are always up to date
 */
add_action('init', 'fold82sm_setup_capabilities');
function fold82sm_setup_capabilities() {
    // Get saved settings
    $settings = fold82sm_get_settings();
    
    // Always include administrator
    if (!in_array('administrator', $settings['allowed_roles'])) {
        $settings['allowed_roles'][] = 'administrator';
        $settings['allowed_roles'] = array_unique($settings['allowed_roles']);
        update_option('fold82sm_settings', $settings);
    }
    
    // Get all WordPress roles
    global $wp_roles;
    
    // Add capability to allowed roles
    foreach ($settings['allowed_roles'] as $role_slug) {
        $role = get_role($role_slug);
        if ($role) {
            $role->add_cap('fold82sm_access', true);
        }
    }
    
    // Remove capability from disallowed roles
    $all_roles = array_keys($wp_roles->roles);
    foreach ($all_roles as $role_slug) {
        if (!in_array($role_slug, $settings['allowed_roles'])) {
            $role = get_role($role_slug);
            if ($role && $role->has_cap('fold82sm_access')) {
                $role->remove_cap('fold82sm_access');
            }
        }
    }
}

// ===== ADMIN MENU =====

// Add main "Folderra Smart Folder" menu within 'admin_menu' hook
add_action('admin_menu', 'fold82sm_add_menu');
function fold82sm_add_menu() {
    // Main menu
    add_menu_page(
        'Folderra Smart Folder Dashboard',  // Page title
        'Folderra',                   // Menu text
        'fold82sm_access',            // Custom capability
        'folderra-sfo-dashboard',     // Menu slug
        'fold82sm_main_page',         // Callback function
        'dashicons-category',
        6
    );

    // FIRST SUBMENU (Dashboard)
    add_submenu_page(
        'folderra-sfo-dashboard',     // Parent slug
        'Folderra Smart Folder Dashboard',  // Page title
        'Dashboard',                  // Menu title
        'fold82sm_access',            // Custom capability
        'folderra-sfo-dashboard',     // Same slug as main menu
        'fold82sm_main_page'          // Same callback function
    );

    // Add "Folders" submenu
    add_submenu_page(
        'folderra-sfo-dashboard',
        'Folders',
        'Folders',
        'fold82sm_access',            // Custom capability
        'folderra-sfo-folders',
        'fold82sm_manage_page'
    );

    // Add "New Folder" submenu
    add_submenu_page(
        'folderra-sfo-dashboard', 
        'New Folder', 
        'New Folder', 
        'fold82sm_access',            // Custom capability
        'folderra-sfo-new-folder', 
        'fold82sm_new_folder_page'
    );
      
    // Add "Settings" submenu
    add_submenu_page(
        'folderra-sfo-dashboard',
        'Settings',
        'Settings',
        'fold82sm_access',            // Custom capability
        'fold82sm-settings',
        'fold82sm_settings_page'
    );

    // Add page to view single folder content
    add_submenu_page(
        null,
        'Folder Details',
        'Folder Details',
        'fold82sm_access',            // Custom capability
        'folderra-sfo-folder-details',
        'fold82sm_details_page'
    );

    // Hidden admin page for Media Organizer (no sidebar menu item)
add_submenu_page(
    null,
    __( 'Media Organizer', 'folderra-smart-folder-organizer' ),
    __( 'Media Organizer', 'folderra-smart-folder-organizer' ),
    'fold82sm_access',
    'folderra-sfo-media-organizer',
    'fold82sm_media_organizer_page'
);
}   

// ===== ADMIN PAGES =====

// Function to show plugin navigation menu
function fold82sm_navigation($current_page = '') {
    ?>
    <div class="fold82sm-navigation" style="margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 5px; position: relative;">
        <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
            <div style="flex: 1;">
                <h2 style="margin: 0 0 15px 0; color: #0073aa; display: flex; align-items: center; gap: 10px; font-size: 18px; font-weight: 600;">
                    <img src="<?php echo esc_url(plugins_url('assets/icon.png', __FILE__)); ?>" style="width: 24px; height: 24px; border-radius: 3px;" alt="Folderra Smart Folder">
                    Folderra Smart Folder
                </h2>
                <nav style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-dashboard')); ?>" 
                       style="padding: 8px 15px; background: <?php echo $current_page === 'dashboard' ? '#0073aa' : '#ffffff'; ?>; 
                              color: <?php echo $current_page === 'dashboard' ? '#ffffff' : '#0073aa'; ?>; 
                              text-decoration: none; border: 1px solid #0073aa; border-radius: 3px;">
                       📊 Dashboard
                    </a>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-folders')); ?>" 
                       style="padding: 8px 15px; background: <?php echo $current_page === 'folders' ? '#0073aa' : '#ffffff'; ?>; 
                              color: <?php echo $current_page === 'folders' ? '#ffffff' : '#0073aa'; ?>; 
                              text-decoration: none; border: 1px solid #0073aa; border-radius: 3px;">
                       📁 Manage Folders
                    </a>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-new-folder')); ?>" 
                       style="padding: 8px 15px; background: <?php echo $current_page === 'new-folder' ? '#0073aa' : '#ffffff'; ?>; 
                              color: <?php echo $current_page === 'new-folder' ? '#ffffff' : '#0073aa'; ?>; 
                              text-decoration: none; border: 1px solid #0073aa; border-radius: 3px;">
                       ➕ New Folder
                    </a>
                </nav>
            </div>
            
            <!-- Settings icon on the right -->
            <div style="margin-left: auto;">
                <a href="<?php echo esc_url(admin_url('admin.php?page=fold82sm-settings')); ?>" 
                   title="<?php esc_attr_e('Settings', 'folderra-smart-folder-organizer'); ?>"
                   style="display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #ffffff; border: 1px solid #ddd; border-radius: 50%; text-decoration: none; transition: all 0.2s ease;"
                   onmouseover="this.style.background='#f0f7ff'; this.style.borderColor='#0073aa';"
                   onmouseout="this.style.background='#ffffff'; this.style.borderColor='#ddd';">
                    <span class="dashicons dashicons-admin-generic" style="font-size: 20px; color: #0073aa; line-height: 1;"></span>
                </a>
                <div style="text-align: center; margin-top: 5px;">
                    <span style="font-size: 11px; color: #666;"><?php esc_html_e('Settings', 'folderra-smart-folder-organizer'); ?></span>
                </div>
            </div>
        </div>
    </div>
    <?php
}

// Main plugin page
function fold82sm_main_page() {
    if (!fold82sm_current_user_can_access()) {
    wp_die( esc_html__( 'You do not have permission to access Folderra Smart Folder.', 'folderra-smart-folder-organizer' ) );
}
    fold82sm_navigation('dashboard');
    echo '<div class="wrap">';
    echo '<h1>' . esc_html__('Dashboard', 'folderra-smart-folder-organizer') . '</h1>';
    echo '<p>' . esc_html__('Manage your content by organizing it in custom folders.', 'folderra-smart-folder-organizer') . '</p>';
    
    // Count folders and content
    $folders_count = fold82sm_get_visible_folders_count();
    
    // Count ALL relationships between pages and folders
    $all_relationships = fold82sm_get_relationships_count();
    $pages_count = $all_relationships ? intval($all_relationships) : 0;
    
    // Updated grid with new boxes
    echo '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 20px 0;">';

    // BOX LEFT: Control Panel
echo '<div style="background:#fff; padding:20px; border-radius:8px; border-left:4px solid #0073aa; box-shadow:0 4px 12px rgba(0,115,170,0.1);">';
echo '<div style="margin-bottom:15px;">';
echo '<div style="display:flex; align-items:center; gap:10px; margin-bottom:5px;">';
echo '<span class="dashicons dashicons-chart-bar" style="font-size:22px; color:#0073aa;"></span>';
echo '<h4 style="margin:0; color:#23282d; font-size:16px; font-weight:700;">'
    . esc_html__( 'Control Panel', 'folderra-smart-folder-organizer' ) .
'</h4>';
echo '</div>';
echo '<p style="margin:0; font-size:13px; color:#666;">'
    . esc_html__( 'Overview of your current organization', 'folderra-smart-folder-organizer' ) .
'</p>';
echo '</div>';

// Statistics
echo '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">';

// Folders column
echo '<div style="text-align: center; padding: 12px; background: #f8f9fa; border-radius: 6px;">';
echo '<div style="font-size: 16px; font-weight: bold; margin-bottom: 4px; color: #0073aa;">' . esc_html($folders_count) . '</div>';
echo '<div style="font-size: 12px; color: #666; margin-bottom: 8px;">' . esc_html__('Smart folders', 'folderra-smart-folder-organizer') . '</div>';
echo '</div>';

// Content column
echo '<div style="text-align: center; padding: 12px; background: #f8f9fa; border-radius: 6px;">';
echo '<div style="font-size: 16px; font-weight: bold; margin-bottom: 4px; color: #0073aa;">' . esc_html($pages_count) . '</div>';
echo '<div style="font-size: 12px; color: #666; margin-bottom: 8px;">' . esc_html__('Organized content items', 'folderra-smart-folder-organizer') . '</div>';
echo '</div>';

echo '</div>';

// Special Folders Section
echo '<div style="margin-bottom: 15px;">';
echo '<h5 style="margin: 0 0 12px 0; color: #2c3338; font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 8px;">';
echo '<span class="dashicons dashicons-admin-page" style="color: #0073aa; font-size: 18px;"></span>';
echo esc_html__('Special Folders', 'folderra-smart-folder-organizer');
echo '</h5>';
echo '</div>';

/// Prepare URLs
$pages_nonce = wp_create_nonce('folderra_special_folder_nonce');
$pages_url = add_query_arg([
    'page' => 'folderra-sfo-special-folder',
    'folder_type' => 'pages',
    '_wpnonce' => $pages_nonce
], admin_url('admin.php'));

$posts_nonce = wp_create_nonce('folderra_special_folder_nonce');
$posts_url = add_query_arg([
    'page' => 'folderra-sfo-special-folder',
    'folder_type' => 'posts',
    '_wpnonce' => $posts_nonce
], admin_url('admin.php'));

// Buttons allpages and allposts
echo '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 20px;">';

// ALL PAGES Button
echo '<a href="' . esc_url($pages_url) . '" class="button button-primary" style="
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 20px;
    background: linear-gradient(135deg, #0073aa 0%, #005a87 100%);
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    transition: all 0.2s ease;
    font-weight: 600;
    font-size: 14px;
" onmouseover="this.style.boxShadow=\'0 4px 12px rgba(0,115,170,0.3)\';" 
   onmouseout="this.style.boxShadow=\'none\';">';
echo '<span class="dashicons dashicons-admin-page" style="font-size: 16px;"></span>';
echo '<span>' . esc_html__('All Pages', 'folderra-smart-folder-organizer') . '</span>';
echo '</a>';

// ALL POSTS Button
echo '<a href="' . esc_url($posts_url) . '" class="button button-primary" style="
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 20px;
    background: linear-gradient(135deg, #46b450 0%, #3fa048 100%);
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    transition: all 0.2s ease;
    font-weight: 600;
    font-size: 14px;
" onmouseover="this.style.boxShadow=\'0 4px 12px rgba(70,180,80,0.3)\';" 
   onmouseout="this.style.boxShadow=\'none\';">';
echo '<span class="dashicons dashicons-edit" style="font-size: 16px;"></span>';
echo '<span>' . esc_html__('All Posts', 'folderra-smart-folder-organizer') . '</span>';
echo '</a>';

// Media Organizer Button (full width)
echo '<a href="' . esc_url( admin_url( 'admin.php?page=folderra-sfo-media-organizer' ) ) . '" class="button button-primary" style="
    grid-column: 1 / -1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 20px;
    background: linear-gradient(135deg, #d63638 0%, #b32d2e 100%);
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    transition: all 0.2s ease;
    font-weight: 600;
    font-size: 14px;
" onmouseover="this.style.boxShadow=\'0 4px 12px rgba(214,54,56,0.35)\';"
   onmouseout="this.style.boxShadow=\'none\';">';
echo '<span class="dashicons dashicons-images-alt2" style="font-size: 16px;"></span>';
echo '<span>' . esc_html__( 'Media Organizer (Cleanup)', 'folderra-smart-folder-organizer' ) . '</span>';
echo '</a>';

echo '</div>'; // End grid

echo '</div>'; // End box Your Folderra Activity

    // RIGHT BOX: Folderra PRO upsell
    echo '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 8px; color: white;">';
    echo '<h4 style="margin: 0 0 12px 0; color: white;">🚀 ' . esc_html__('Folderra PRO', 'folderra-smart-folder-organizer') . '</h4>';
    echo '<p style="margin: 0 0 15px 0; color: rgba(255,255,255,0.9); font-size: 13px; line-height: 1.4;">' . esc_html__('Take your content organization to the next level with advanced features designed for marketers and teams.', 'folderra-smart-folder-organizer') . '</p>';
    
    echo '<ul style="margin: 0 0 20px 0; padding-left: 16px; color: white; font-size: 13px; line-height: 1.4;">';
    echo '<li>🧪 ' . esc_html__('A/B testing suite for content optimization', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li>🎯 ' . esc_html__('Special folders built for lead generation', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li>🖼️ ' . esc_html__('Media Library Folders', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li>🏷️ ' . esc_html__('Automatic Tag & Category Folders', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li>📊 ' . esc_html__('Advanced analytics & performance insights', 'folderra-smart-folder-organizer') . '</li>';
    echo '</ul>';

    echo '<a href="https://wpsmartfolder.com/pro" target="_blank" rel="noopener noreferrer" class="button" style="background: #ffd700; color: #333; border: none; font-weight: bold; font-size: 13px; padding: 10px 20px; width: 100%; text-align: center; text-decoration: none; display: block; border-radius: 4px;">';
    echo '✨ ' . esc_html__('Discover Folderra PRO', 'folderra-smart-folder-organizer');
    echo '</a>';
    
    echo '<p style="margin: 8px 0 0 0; color: rgba(255,255,255,0.8); font-size: 11px; text-align: center;">' . esc_html__('Professional features for serious content management', 'folderra-smart-folder-organizer') . '</p>';
    echo '</div>';

    echo '</div>'; // Stop grid    
    
// ===== RECENTLY MODIFIED (FREE) =====
echo '<div style="display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:20px; margin-top:20px;">';
fold82sm_render_recently_modified_box(
    'page',
    esc_html__( 'Recently modified Pages', 'folderra-smart-folder-organizer' ),
    'admin-page',
    6,
    'blue'
);

fold82sm_render_recently_modified_box(
    'post',
    esc_html__( 'Recently modified Posts', 'folderra-smart-folder-organizer' ),
    'edit',
    6,
    'green'
);

echo '</div>';

    // ===== MINI ANALYTICS (FREE) - TOP CONTENT =====
echo '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px;">';

// Top Pages filters
echo '<div style="background: #fff; padding: 20px; border-radius: 5px; border-left: 4px solid #0073aa; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
echo '<h3 style="margin: 0 0 10px 0;">📄 ' . esc_html__( 'Top Pages', 'folderra-smart-folder-organizer' ) . '</h3>';
echo '<p style="margin: 0 0 15px 0; color: #666;">' . esc_html__( 'Your most viewed pages.', 'folderra-smart-folder-organizer' ) . '</p>';

// PAGES FILTERS
echo '<div class="fold82sm-mini-analytics-filters-pages" style="margin:0 0 15px 0;">';
echo '<div style="display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-bottom:10px;">';
echo '<span style="font-weight:600; color:#23282d; font-size:13px;">' . esc_html__('Period:', 'folderra-smart-folder-organizer') . '</span>';
echo '<button type="button" class="button button-small is-active" data-period="today">' . esc_html__('Today', 'folderra-smart-folder-organizer') . '</button>';
echo '<button type="button" class="button button-small" data-period="week">' . esc_html__('Weekly', 'folderra-smart-folder-organizer') . '</button>';
echo '<button type="button" class="button button-small" data-period="month">' . esc_html__('Monthly', 'folderra-smart-folder-organizer') . '</button>';
echo '<button type="button" class="button button-small" data-period="year">' . esc_html__('Yearly', 'folderra-smart-folder-organizer') . '</button>';
echo '</div>';
echo '</div>';

echo '<div id="fold82sm-mini-analytics-pages" style="min-height: 60px; color:#666; font-size:13px;">' . esc_html__('Loading...', 'folderra-smart-folder-organizer') . '</div>';
echo '</div>';

// Top Posts filters
echo '<div style="background: #fff; padding: 20px; border-radius: 5px; border-left: 4px solid #46b450; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
echo '<h3 style="margin: 0 0 10px 0;">📝 ' . esc_html__( 'Top Posts', 'folderra-smart-folder-organizer' ) . '</h3>';
echo '<p style="margin: 0 0 15px 0; color: #666;">' . esc_html__( 'Your most viewed posts.', 'folderra-smart-folder-organizer' ) . '</p>';

// POSTS FILTERS
echo '<div class="fold82sm-mini-analytics-filters-posts" style="margin:0 0 15px 0;">';
echo '<div style="display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-bottom:10px;">';
echo '<span style="font-weight:600; color:#23282d; font-size:13px;">' . esc_html__('Period:', 'folderra-smart-folder-organizer') . '</span>';
echo '<button type="button" class="button button-small is-active" data-period="today">' . esc_html__('Today', 'folderra-smart-folder-organizer') . '</button>';
echo '<button type="button" class="button button-small" data-period="week">' . esc_html__('Weekly', 'folderra-smart-folder-organizer') . '</button>';
echo '<button type="button" class="button button-small" data-period="month">' . esc_html__('Monthly', 'folderra-smart-folder-organizer') . '</button>';
echo '<button type="button" class="button button-small" data-period="year">' . esc_html__('Yearly', 'folderra-smart-folder-organizer') . '</button>';
echo '</div>';
echo '</div>';

echo '<div id="fold82sm-mini-analytics-posts" style="min-height: 60px; color:#666; font-size:13px;">' . esc_html__('Loading...', 'folderra-smart-folder-organizer') . '</div>';
echo '</div>';

echo '</div>';

// MAIN GRID FUNCTIONALITY
    echo '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 20px;">';
    
    // Box Existing Folders
    echo '<div style="background: #fff; padding: 20px; border-radius: 5px; border-left: 4px solid #0073aa; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
    echo '<h3 style="margin: 0 0 10px 0;">📁 ' . esc_html__('Existing Folders', 'folderra-smart-folder-organizer') . '</h3>';
    echo '<p style="margin: 0 0 15px 0; color: #666;">' . esc_html__('View and manage all your created folders.', 'folderra-smart-folder-organizer') . '</p>';
    echo '<a href="' . esc_url(admin_url('admin.php?page=folderra-sfo-folders')) . '" class="button button-primary">' . esc_html__('Go to Folders', 'folderra-smart-folder-organizer') . '</a>';
    echo '</div>';
    
    // Box New Folder
    echo '<div style="background: #fff; padding: 20px; border-radius: 5px; border-left: 4px solid #46b450; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
    echo '<h3 style="margin: 0 0 10px 0;">➕ ' . esc_html__('New Folder', 'folderra-smart-folder-organizer') . '</h3>';
    echo '<p style="margin: 0 0 15px 0; color: #666;">' . esc_html__('Create a new folder to organize your content.', 'folderra-smart-folder-organizer') . '</p>';
    echo '<a href="' . esc_url(admin_url('admin.php?page=folderra-sfo-new-folder')) . '" class="button button-primary">' . esc_html__('Create Folder', 'folderra-smart-folder-organizer') . '</a>';
    echo '</div>';
    
        echo '</div>'; // CLOSE MAIN GRID FUNCTIONALITY

    
    // ===== VIDEO TUTORIAL SECTION =====
    echo '<div class="fold82sm-video-section" style="margin: 40px 0 20px 0; padding: 30px; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 12px; border: 1px solid #dee2e6; text-align: center;">';
    
    echo '<div style="display: flex; align-items: center; justify-content: center; gap: 15px; margin-bottom: 20px;">';
    echo '<span class="dashicons dashicons-video-alt3" style="font-size: 32px; color: #0073aa;"></span>';
    echo '<h2 style="margin: 0; color: #2c3e50; font-size: 24px;">' . esc_html__('Quick Start Video Tutorial', 'folderra-smart-folder-organizer') . '</h2>';
    echo '</div>';
    
    echo '<p style="margin-bottom: 25px; color: #5a6c7d; font-size: 16px; max-width: 700px; margin-left: auto; margin-right: auto; line-height: 1.5;">';
    echo esc_html__('Learn how to organize your content effectively with Folderra in under 3 minutes. Watch this quick tutorial to master smart folder management.', 'folderra-smart-folder-organizer');
    echo '</p>';
    
    // YouTube video embed (responsive)
    echo '<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 800px; margin: 0 auto; border-radius: 10px; box-shadow: 0 8px 25px rgba(0,0,0,0.15); border: 2px solid #fff; background: #000;">';
    echo '<iframe 
        style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none;" 
        src="https://www.youtube.com/embed/NwVXqgYZxzw" 
        title="' . esc_attr__('Folderra Smart Folder - Quick Start Tutorial', 'folderra-smart-folder-organizer') . '" 
        frameborder="0" 
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
        allowfullscreen
        loading="lazy">
    </iframe>';
    echo '</div>';
    
    // Additional resources
    echo '<div style="margin-top: 30px; display: flex; justify-content: center; gap: 20px; flex-wrap: wrap;">';
    
    echo '<a href="https://wpsmartfolder.com/documentation" target="_blank" rel="noopener noreferrer" 
        style="color: #0073aa; text-decoration: none; font-weight: 500; padding: 12px 24px; 
               background: #fff; border-radius: 6px; border: 1px solid #c3d9ff; 
               display: inline-flex; align-items: center; gap: 10px; transition: all 0.3s ease;"
        onmouseover="this.style.backgroundColor=\'#f0f7ff\'; this.style.boxShadow=\'0 4px 12px rgba(0,115,170,0.1)\';"
        onmouseout="this.style.backgroundColor=\'#fff\'; this.style.boxShadow=\'none\';">';
    echo '<span class="dashicons dashicons-sos" style="font-size: 18px;"></span>';
    echo esc_html__('📚 Full Documentation', 'folderra-smart-folder-organizer');
    echo '</a>';
    
    echo '<a href="https://wpsmartfolder.com/support" target="_blank" rel="noopener noreferrer" 
        style="color: #fff; text-decoration: none; font-weight: 500; padding: 12px 24px; 
               background: #0073aa; border-radius: 6px; border: 1px solid #005a87;
               display: inline-flex; align-items: center; gap: 10px; transition: all 0.3s ease;"
        onmouseover="this.style.backgroundColor=\'#005a87\'; this.style.boxShadow=\'0 4px 12px rgba(0,115,170,0.2)\';"
        onmouseout="this.style.backgroundColor=\'#0073aa\'; this.style.boxShadow=\'none\';">';
    echo '<span class="dashicons dashicons-email" style="font-size: 18px;"></span>';
    echo esc_html__('💬 Get Support', 'folderra-smart-folder-organizer');
    echo '</a>';
    
    echo '</div>'; // Chiude additional resources
    
    echo '</div>'; // Chiude fold82sm-video-section
    
    echo '</div>'; // Chiude .wrap
}

// Page to create new folders with templates
function fold82sm_new_folder_page() {
    if (!fold82sm_current_user_can_access()) {
        wp_die( esc_html__( 'You do not have permission to access Folderra Smart Folder.', 'folderra-smart-folder-organizer' ) );
    }

    fold82sm_navigation('new-folder');

    // Get the visible folders count for information (respects the same filters of the Folders screen)
    $folders_count = fold82sm_get_visible_folders_count();

    // Free templates
    $free_templates = array(
        'blog-posts' => array(
            'name'        => '📝 Blog Posts',
            'description' => 'Organize your blog articles in collections',
            'icon'        => 'dashicons-edit',
            'post_types'  => array('post'),
            'color'       => '#46b450',
        ),
        'pages' => array(
            'name'        => '📄 Pages',
            'description' => 'Organize your pages for better structure',
            'icon'        => 'dashicons-admin-page',
            'post_types'  => array('page'),
            'color'       => '#0073aa',
        ),
        'mixed' => array(
            'name'        => '📁 Mixed Content',
            'description' => 'Organize both pages and posts together',
            'icon'        => 'dashicons-category',
            'post_types'  => array('page', 'post'),
            'color'       => '#764ba2',
        ),
    );

    echo '<div class="wrap">';

    // Information bar
    echo '<div id="folder-info-message" class="folder-count-message info-message" style="background: #d1ecf1; border: 1px solid #bee5eb; padding: 12px; border-radius: 4px; margin-bottom: 20px;">';
    echo '<p style="margin: 0; color: #0c5460; font-size: 14px; font-weight: 500;">';
    echo '<strong>' . esc_html($folders_count) . '</strong> ' . esc_html__('smart folders created so far', 'folderra-smart-folder-organizer');
    echo '</p>';
    echo '</div>';

    echo '<h1>' . esc_html__('Create New Folder', 'folderra-smart-folder-organizer') . '</h1>';
    echo '<p style="font-size: 14px; color: #666;">' . esc_html__('Choose a template to organize your content effectively.', 'folderra-smart-folder-organizer') . '</p>';

    echo '<div id="new-folder-app" style="max-width: 1200px; margin: 30px auto;">';

    // =========================
// FREE TEMPLATES
// =========================
echo '<div class="template-section" style="margin-bottom: 40px;">';
echo '<h3 style="color: #333; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 2px solid #f0f0f0;">🎯 ' . esc_html__('Essential Templates', 'folderra-smart-folder-organizer') . '</h3>';

// 3-column grid layout for free templates
echo '<div class="templates-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">';

foreach ($free_templates as $slug => $template) {
    $icon_html = '📁';
    switch ($template['icon']) {
        case 'dashicons-edit':
            $icon_html = '📝';
            break;
        case 'dashicons-admin-page':
            $icon_html = '📄';
            break;
    }

    echo '
    <div class="template-card" data-template="' . esc_attr($slug) . '" 
         style="border: 2px solid ' . esc_attr($template['color']) . '; border-radius: 8px; padding: 25px; background: white; cursor: pointer; transition: all 0.3s ease; min-height: 140px; position: relative;">
        <div style="display: flex; align-items: flex-start; gap: 15px; margin-bottom: 15px;">
            <span style="font-size: 32px; flex-shrink: 0;">' . esc_html($icon_html) . '</span>
            <div style="flex: 1;">
                <h4 style="margin: 0 0 8px 0; color: #333; font-size: 18px; font-weight: 600;">' . esc_html($template['name']) . '</h4>
                <p style="margin: 0; color: #666; line-height: 1.5; font-size: 14px;">' . esc_html($template['description']) . '</p>
            </div>
        </div>
        <div style="position: absolute; bottom: 20px; right: 20px;">
            <span style="background: ' . esc_attr($template['color']) . '; color: white; padding: 8px 16px; border-radius: 4px; font-size: 13px; font-weight: 500;">' . esc_html__('Use Template', 'folderra-smart-folder-organizer') . '</span>
        </div>
    </div>';
}

echo '</div>'; // .templates-grid
echo '</div>'; // .template-section

// =========================
// PRO UPGRADE BANNER
// =========================
echo '<div class="upgrade-section" style="margin: 40px 0; padding: 25px; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border: 2px solid #dee2e6; border-radius: 8px; text-align: center;">';
echo '<h3 style="margin: 0 0 10px 0; color: #333; font-size: 22px;">🚀 ' . esc_html__('Want More Power?', 'folderra-smart-folder-organizer') . '</h3>';
echo '<p style="margin: 0 0 15px 0; color: #666; font-size: 15px; max-width: 700px; margin-left: auto; margin-right: auto;">';
echo esc_html__('Unlock advanced templates and professional features with Folderra PRO — a separate, powerful plugin.', 'folderra-smart-folder-organizer');
echo '</p>';
echo '<a href="https://wpsmartfolder.com/pro" target="_blank" rel="noopener noreferrer" class="button button-primary" style="background: #0073aa; border-color: #005a87; font-weight: bold; padding: 10px 25px;">';
echo esc_html__('Discover Folderra PRO', 'folderra-smart-folder-organizer');
echo '</a>';
echo '</div>';

// =========================
// PRO TEMPLATES SHOWCASE
// =========================
echo '<div class="pro-showcase-section" style="margin-bottom: 40px;">';
echo '<h3 style="color: #333; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 2px solid #f0f0f0;">✨ ' . esc_html__('Advanced Templates (Available in PRO)', 'folderra-smart-folder-organizer') . '</h3>';
echo '<p style="color: #666; margin-bottom: 25px; font-size: 14px;">';
echo esc_html__('The following professional templates are available in the separate Folderra PRO plugin:', 'folderra-smart-folder-organizer');
echo '</p>';

// PRO Templates Configuration
$pro_templates = array(
    'landing-page' => array(
        'name'        => 'Lead Generation',
        'description' => 'Create high-converting landing pages with built-in analytics and conversion tracking.',
        'icon'        => '🚀',
        'features'    => array('Conversion Analytics', 'A/B Testing Ready', 'Lead Magnets', 'Performance Dashboard'),
        'color'       => '#e74c3c',
        'coming_soon' => true,
    ),
    'ab-test' => array(
        'name'        => 'A/B Test',
        'description' => 'Run controlled content experiments to optimize engagement and conversion rates.',
        'icon'        => '🧪',
        'features'    => array('Split Testing', 'Statistical Analysis', 'Performance Reports', 'Winner Automation'),
        'color'       => '#3498db',
    ),
    'funnel' => array(
        'name'        => 'Sales Funnel',
        'description' => 'Build complete customer journeys from awareness to conversion with funnel analytics.',
        'icon'        => '📈',
        'features'    => array('Funnel Visualization', 'Drop-off Analysis', 'Automated Sequences', 'ROI Tracking'),
        'color'       => '#f39c12',
        'coming_soon' => true,
    ),
    'tag-folder' => array(
        'name'        => 'Dynamic Tag Folder',
        'description' => 'Automatically organize content by tags. Add a tag and content appears automatically.',
        'icon'        => '🏷️',
        'features'    => array('Auto-Organization', 'Tag-based Filtering', 'Dynamic Updates', 'Smart Content Rules'),
        'color'       => '#9b59b6',
    ),
    'category-folder' => array(
        'name'        => 'Dynamic Category Folder',
        'description' => 'Create auto-updating folders for specific blog categories with smart filtering.',
        'icon'        => '📚',
        'features'    => array('Category Automation', 'Smart Filtering', 'Cross-Category Rules', 'Dynamic Updates'),
        'color'       => '#1abc9c',
    ),
    'media-folder' => array(
        'name'        => 'Media Library Folder',
        'description' => 'Smart folders for your media library with subfolders, direct uploads, and advanced filtering for images, videos, and audio files.',
        'icon'        => '🖼️',
        'features'    => array('Media Type Filtering', 'Subfolders Support', 'Direct Upload to Subfolders', 'Bulk Operations'),
        'color'       => '#e67e22',
    ),
);

// PRO Templates Grid
echo '<div class="pro-templates-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">';

foreach ( $pro_templates as $slug => $template ) {

    $is_coming_soon = ! empty( $template['coming_soon'] );
    $card_classes   = 'pro-template-card' . ( $is_coming_soon ? ' coming-soon' : '' );

    echo '
    <div class="' . esc_attr( $card_classes ) . '" data-pro-template="' . esc_attr( $slug ) . '" 
         style="border: 2px dashed ' . esc_attr( $template['color'] ) . '; border-radius: 8px; padding: 25px; background: #f8f9fa; position: relative; min-height: 180px; cursor: pointer; transition: all 0.3s ease;">

        <div class="template-badges">
            <span class="pro-badge">PRO</span>' .
            ( $is_coming_soon ? '<span class="coming-soon-badge">Coming Soon</span>' : '' ) .
        '</div>

        <div style="display: flex; align-items: flex-start; gap: 15px; margin-bottom: 15px;">
            <span style="font-size: 32px; flex-shrink: 0; opacity: 0.9;">' . esc_html( $template['icon'] ) . '</span>
            <div style="flex: 1;">
                <h4 style="margin: 0 0 8px 0; color: #2c3e50; font-size: 18px; font-weight: 600;">' . esc_html( $template['name'] ) . '</h4>
                <p style="margin: 0 0 12px 0; color: #5a6c7d; line-height: 1.5; font-size: 14px;">' . esc_html( $template['description'] ) . '</p>
            </div>
        </div>

        <div style="position: absolute; bottom: 20px; right: 20px;">' .

            ( $is_coming_soon
                ? '<span class="button" style="background: #c3c4c7; color: #1d2327; border: none; padding: 8px 16px; border-radius: 4px; font-size: 13px; font-weight: 500;">Coming Soon</span>'
                : '<button class="button pro-learn-more-btn" style="background: ' . esc_attr( $template['color'] ) . '; color: white; border: none; padding: 8px 16px; border-radius: 4px; font-size: 13px; font-weight: 500; cursor: pointer;">' . esc_html__( 'Learn More', 'folderra-smart-folder-organizer' ) . '</button>'
            ) .

        '</div>
    </div>';
}


echo '</div>'; // .pro-templates-grid
echo '</div>'; // .pro-showcase-section

// =========================
// PRO TEMPLATE MODAL/POPUP STRUCTURE (HTML)
// =========================
echo '
<div id="fold82sm-pro-modal" style="display: none; position: fixed; z-index: 999999; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.7);">
    <div style="position: relative; background-color: #fff; margin: 5% auto; padding: 0; width: 90%; max-width: 600px; border-radius: 10px; box-shadow: 0 10px 30px rgba(0,0,0,0.3);">
        
        <!-- Modal Header -->
        <div style="padding: 20px 25px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h3 style="margin: 0; color: #333; font-size: 22px; display: flex; align-items: center; gap: 10px;">
                    <span id="fold82sm-pro-modal-icon" style="font-size: 28px;"></span>
                    <span id="fold82sm-pro-modal-title"></span>
                    <span style="background: #666; color: white; padding: 3px 10px; border-radius: 12px; font-size: 12px; font-weight: bold; margin-left: 10px;">PRO</span>
                </h3>
                <p id="fold82sm-pro-modal-subtitle" style="margin: 5px 0 0 0; color: #666; font-size: 14px;">' . esc_html__('Available in Folderra PRO plugin', 'folderra-smart-folder-organizer') . '</p>
            </div>
            <button id="fold82sm-pro-modal-close" style="background: none; border: none; font-size: 24px; color: #999; cursor: pointer; padding: 0; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">×</button>
        </div>
        
        <!-- Modal Body -->
        <div style="padding: 25px;">
            <div style="margin-bottom: 25px;">
                <h4 style="margin: 0 0 12px 0; color: #333; font-size: 16px;">' . esc_html__('Template Description', 'folderra-smart-folder-organizer') . '</h4>
                <p id="fold82sm-pro-modal-description" style="margin: 0; color: #555; line-height: 1.6; font-size: 15px;"></p>
            </div>
            
            <div style="margin-bottom: 25px;">
                <h4 style="margin: 0 0 12px 0; color: #333; font-size: 16px;">' . esc_html__('Key Features', 'folderra-smart-folder-organizer') . '</h4>
                <ul id="fold82sm-pro-modal-features" style="margin: 0; padding-left: 20px; color: #555; line-height: 1.6; font-size: 14px;"></ul>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #0073aa; margin-bottom: 25px;">
                <p style="margin: 0; color: #666; font-size: 14px; line-height: 1.5;">
                    <strong>' . esc_html__('Note:', 'folderra-smart-folder-organizer') . '</strong> ' . 
                    esc_html__('This template is part of the Folderra PRO plugin, a separate product that extends the functionality of Folderra Smart Folder Organizer.', 'folderra-smart-folder-organizer') .
                '</p>
            </div>
        </div>
        
        <!-- Modal Footer -->
        <div style="padding: 20px 25px; background: #f8f9fa; border-top: 1px solid #eee; border-radius: 0 0 10px 10px; text-align: center;">
            <a id="fold82sm-pro-modal-link" href="https://wpsmartfolder.com/pro" target="_blank" rel="noopener noreferrer" class="button button-primary" style="background: #0073aa; border-color: #005a87; color: white; font-weight: bold; padding: 12px 30px; font-size: 16px; text-decoration: none; display: inline-block; border-radius: 4px; margin-right: 15px;">
                🚀 ' . esc_html__('Get Folderra PRO', 'folderra-smart-folder-organizer') . '
            </a>
            <button id="fold82sm-pro-modal-close-btn" class="button" style="background: #6c757d; border-color: #545b62; color: white; padding: 12px 25px; font-size: 15px;">' . esc_html__('Close', 'folderra-smart-folder-organizer') . '</button>
        </div>
    </div>
</div>';

// Pass PRO templates data to JavaScript
wp_localize_script('fold82sm-new-folder', 'fold82smProTemplates', $pro_templates);

echo '</div>'; // close #new-folder-app
echo '</div>'; // close .wrap
}

/**
 * Return dynamic templates that actually exist in current folders.
 * We only expose filters for templates that have at least 1 folder created.
 *
 * @return array slug => count
 */
function fold82sm_get_existing_dynamic_templates_counts() {
    global $wpdb;

    $taxonomy = 'folderra_sfo_content_folder';
    $meta_key = 'folder_template';

    $dynamic_slugs = array('tag-folder', 'category-folder', 'media-folder');

    // Prepare placeholders for IN()
    $placeholders = implode(',', array_fill(0, count($dynamic_slugs), '%s'));

    // Count folders by template slug (only those 3)
    $sql = "
        SELECT tm.meta_value AS slug, COUNT(*) AS total
        FROM {$wpdb->termmeta} tm
        INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = tm.term_id
        WHERE tt.taxonomy = %s
          AND tm.meta_key = %s
          AND tm.meta_value IN ($placeholders)
        GROUP BY tm.meta_value
    ";

    $params = array_merge(array($taxonomy, $meta_key), $dynamic_slugs);
    $rows   = $wpdb->get_results($wpdb->prepare($sql, $params), ARRAY_A);

    $out = array();
    foreach ($rows as $r) {
        $slug = isset($r['slug']) ? (string) $r['slug'] : '';
        $tot  = isset($r['total']) ? (int) $r['total'] : 0;
        if ($slug && $tot > 0) {
            $out[$slug] = $tot;
        }
    }

    return $out;
}


// Page to manage folders list
function fold82sm_manage_page() {
    if (!fold82sm_current_user_can_access()) {
        wp_die( esc_html__( 'You do not have permission to access Folderra Smart Folder.', 'folderra-smart-folder-organizer' ) );
    }
    
    // Clear any term cache to ensure fresh data
    clean_term_cache(null, 'folderra_sfo_content_folder');
    
    fold82sm_navigation('folders');
    
    // Nonce check for form submission (graceful degradation)
    $nonce_verified = false;
    $nonce_action = 'folderra_sfo_filters_nonce';
    
    if (isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), $nonce_action)) {
        $nonce_verified = true;
    }
    
    // Get filter parameters with nonce-aware logic
    $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
    
    // Only use filter values if nonce is verified or no filters were submitted
    if ($nonce_verified || (!isset($_GET['folder_type']) && !isset($_GET['s']))) {
        $folder_type = isset($_GET['folder_type']) ? sanitize_text_field(wp_unslash($_GET['folder_type'])) : 'all';
        $search = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '';
    } else {
        // If nonce invalid but filters were attempted, use defaults
        $folder_type = 'all';
        $search = '';
    }
    
    // Get filtered folders
$data = fold82sm_get_filtered_folders([
    'page'        => $current_page,
    'per_page'    => $per_page,
    'folder_type' => $folder_type,
    'search'      => $search
]);

$folders     = $data['folders'];
$pagination  = $data['pagination'];

echo '<div class="wrap">';
echo '<h1>' . esc_html__('Folders List', 'folderra-smart-folder-organizer') . '</h1>';
echo '<p style="color: #666; margin-bottom: 20px;">' . esc_html__('Folders are sorted by creation date (newest first). Drag to reorder manually.', 'folderra-smart-folder-organizer') . '</p>';

// Filter controls with nonce
echo '<div class="fold82sm-filters" style="margin: 0 0 20px 0; padding: 15px; background: #f8f9fa; border-radius: 5px; border: 1px solid #e0e0e0;">';
echo '<form method="get" action="" style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">';
echo '<input type="hidden" name="page" value="folderra-sfo-folders">';
wp_nonce_field($nonce_action, '_wpnonce', false);

// Search
echo '<div>';
echo '<label style="margin-right: 5px; font-weight: bold; font-size: 13px;">' . esc_html__('Search:', 'folderra-smart-folder-organizer') . '</label>';
echo '<input type="text" name="s" value="' . esc_attr($search) . '" placeholder="' . esc_attr__('Search folders...', 'folderra-smart-folder-organizer') . '" style="padding: 5px 10px; border-radius: 3px; border: 1px solid #ddd; font-size: 13px; width: 200px;">';
echo '</div>';

// Folder type filter
echo '<div>';
echo '<label style="margin-right: 5px; font-weight: bold; font-size: 13px;">' . esc_html__('Folder Type:', 'folderra-smart-folder-organizer') . '</label>';
echo '<select name="folder_type" style="padding: 5px 10px; border-radius: 3px; border: 1px solid #ddd; font-size: 13px;">';

$type_options = [
    'all'   => __('All Types', 'folderra-smart-folder-organizer'),
    'post'  => __('Posts Only', 'folderra-smart-folder-organizer'),
    'page'  => __('Pages Only', 'folderra-smart-folder-organizer'),
    'mixed' => __('Mixed Content', 'folderra-smart-folder-organizer')
];

foreach ( $type_options as $value => $label ) {
    printf(
        '<option value="%1$s"%2$s>%3$s</option>',
        esc_attr( $value ),
        selected( $folder_type, $value, false ),
        esc_html( $label )
    );
}

/**
 * UX improvement: show Dynamic Templates only if at least one folder exists.
 * This does NOT enable new FREE features; it only improves filtering for PRO users.
 */
if ( function_exists( 'fold82sm_get_existing_dynamic_templates_counts' ) ) {
    $dyn = fold82sm_get_existing_dynamic_templates_counts();

    if ( ! empty( $dyn ) ) {
        echo '<optgroup label="' . esc_attr__( 'Dynamic Templates', 'folderra-smart-folder-organizer' ) . '">';

        $dyn_labels = [
            'tag-folder'      => __( 'Tag Folder', 'folderra-smart-folder-organizer' ),
            'category-folder' => __( 'Category Folder', 'folderra-smart-folder-organizer' ),
            'media-folder'    => __( 'Media Folder', 'folderra-smart-folder-organizer' ),
        ];

        foreach ( $dyn_labels as $slug => $label ) {
            if ( empty( $dyn[ $slug ] ) ) {
                continue; // show only if it exists
            }

            $count = (int) $dyn[ $slug ];

            printf(
                '<option value="%1$s"%2$s>%3$s</option>',
                esc_attr( $slug ),
                selected( $folder_type, $slug, false ),
                esc_html( sprintf( '%s (%d)', $label, $count ) )
            );
        }

        echo '</optgroup>';
    }
}

echo '</select>';
echo '</div>';

    
    // Items per page
    echo '<div>';
    echo '<label style="margin-right: 5px; font-weight: bold; font-size: 13px;">' . esc_html__('Items per page:', 'folderra-smart-folder-organizer') . '</label>';
    echo '<select name="per_page" style="padding: 5px 10px; border-radius: 3px; border: 1px solid #ddd; font-size: 13px;">';
    
    $per_page_options = [
        10 => '10',
        25 => '25',
        50 => '50',
        100 => '100',
        -1 => __('All', 'folderra-smart-folder-organizer')
    ];
    
        foreach ( $per_page_options as $value => $label ) {
        printf(
            '<option value="%1$s"%2$s>%3$s</option>',
            esc_attr( $value ),
            selected( $per_page, $value, false ),
            esc_html( $label )
        );
    }

    
    echo '</select>';
    echo '</div>';
    
    // Apply button
    echo '<div>';
    echo '<button type="submit" class="button button-primary" style="padding: 5px 15px; font-size: 13px;">' . esc_html__('Apply Filters', 'folderra-smart-folder-organizer') . '</button>';
    echo '</div>';
    
    // Reset button
    if ($search || $folder_type !== 'all' || $per_page != 10 || $current_page > 1) {
        echo '<div>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=folderra-sfo-folders')) . '" class="button" style="padding: 5px 15px; font-size: 13px;">' . esc_html__('Reset', 'folderra-smart-folder-organizer') . '</a>';
        echo '</div>';
    }
    
    echo '</form>';
    echo '</div>';
    
    echo '<div id="folders-sortable-container">';
    
    if (!empty($folders) && !is_wp_error($folders)) {
        echo '<div id="folders-sortable" class="folders-container">'; 
        foreach ($folders as $folder) {

    // Default count (normal smart folders)
    $pages_count = (int) $folder->count;

    // Read template slug
    $template_slug = get_term_meta( $folder->term_id, 'folder_template', true );

    // If dynamic templates, compute real count
    if ( in_array( $template_slug, array( 'tag-folder', 'category-folder', 'media-folder' ), true ) ) {
        $pages_count = (int) fold82sm_get_dynamic_folder_items_count( $folder->term_id, $template_slug );
    }

    // Folder display name (custom)
    $display_name = get_term_meta( $folder->term_id, 'folder_display_name', true );
    $final_name   = ! empty( $display_name ) ? $display_name : $folder->name;
            
            echo '<div class="folder-block sortable-folder" data-folder-id="' . esc_attr($folder->term_id) . '">';
            
            // Drag icon on LEFT
            echo '<div class="folder-drag-handle">';
            echo '<i class="dashicons dashicons-move" title="' . esc_attr__('Drag to reorder', 'folderra-smart-folder-organizer') . '" style="font-size: 16px;"></i>';
            echo '</div>';
            
            // Folder content in CENTER
            echo '<div class="folder-content">';
            echo '<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">';
            echo '<h3 class="folder-title" id="folder-title-' . esc_attr($folder->term_id) . '">' . esc_html($final_name) . '</h3>';
            echo '<i class="dashicons dashicons-edit folder-edit-icon" style="font-size: 14px; color: #0073aa; cursor: pointer; opacity: 0.7;" title="' . esc_attr__('Edit folder name', 'folderra-smart-folder-organizer') . '" data-folder-id="' . esc_attr($folder->term_id) . '" data-folder-name="' . esc_attr($final_name) . '"></i>';
            echo '</div>';
            
            // Show folder template type.
            $template_slug = get_term_meta( $folder->term_id, 'folder_template', true );
            $template_info = fold82sm_get_template_info( $template_slug );

            echo '<div style="display: flex; gap: 10px; align-items: center;">';

            // Folder ID.
            echo '<span class="folder-details">' . sprintf(
                /* translators: %s: smart folder ID. */
                esc_html__( 'ID: %s', 'folderra-smart-folder-organizer' ),
                esc_html( $folder->term_id )
            ) . '</span>';

           // Template name (safe fallback if missing).
            $template_name = isset( $template_info['name'] ) ? $template_info['name'] : '';
            echo '<span class="folder-details">' . esc_html( $template_name ) . '</span>';

            // Item count.
            echo '<span class="folder-pages-count">' . sprintf(
                /* translators: %s: number of items inside this folder. */
                esc_html__( '%s items', 'folderra-smart-folder-organizer' ),
                esc_html( $pages_count )
            ) . '</span>';

            echo '</div>';
            echo '</div>';


            
            // Button on RIGHT
            $folder_details_url = admin_url('admin.php?page=folderra-sfo-folder-details&folder_id=' . $folder->term_id);
            $folder_details_nonce = wp_create_nonce('folderra_sfo_folder_details_nonce');
            $folder_details_url = add_query_arg('_wpnonce', $folder_details_nonce, $folder_details_url);

            echo '<a class="folder-action-button" href="' . esc_url($folder_details_url) . '">' . esc_html__('Open', 'folderra-smart-folder-organizer') . '</a>';            
            echo '</div>';
        }
        echo '</div>';
        
        // Pagination with sanitized URLs
        if ($pagination['total_pages'] > 1) {
            $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '';
            
            echo '<div class="fold82sm-pagination" style="margin-top: 30px; padding: 15px; background: #f8f9fa; border-radius: 5px; border-top: 1px solid #ddd;">';
            echo '<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">';
            
            // Items info
            $start = (($current_page - 1) * $per_page) + 1;
            $end = $per_page > 0 ? min($current_page * $per_page, $pagination['total_items']) : $pagination['total_items'];
            
            echo '<div>';
            echo '<span style="color: #666; font-size: 13px;">';
            echo sprintf(
            /* translators: 1: first item number shown, 2: last item number shown, 3: total number of items. */
                esc_html__('Showing %1$s - %2$s of %3$s items', 'folderra-smart-folder-organizer'),
                '<strong>' . esc_html($start) . '</strong>',
                '<strong>' . esc_html($end) . '</strong>',
                '<strong>' . esc_html($pagination['total_items']) . '</strong>'
            );
            echo '</span>';
            echo '</div>';
            
            // Page navigation
            echo '<div style="display: flex; gap: 5px; align-items: center;">';
            
            // Previous button
            if ($pagination['has_prev']) {
                $prev_url = add_query_arg(['paged' => $current_page - 1], $request_uri);
                echo '<a href="' . esc_url($prev_url) . '" class="button" style="padding: 5px 10px; font-size: 12px; min-width: 80px;">&laquo; ' . esc_html__('Previous', 'folderra-smart-folder-organizer') . '</a>';
            }
            
            // Page numbers
            $max_pages_to_show = 5;
            $start_page = max(1, $current_page - floor($max_pages_to_show / 2));
            $end_page = min($pagination['total_pages'], $start_page + $max_pages_to_show - 1);
            
            // Adjust if we're near the end
            if ($end_page - $start_page + 1 < $max_pages_to_show) {
                $start_page = max(1, $end_page - $max_pages_to_show + 1);
            }
            
            for ($i = $start_page; $i <= $end_page; $i++) {
                if ($i == $current_page) {
                    echo '<span class="button button-primary" style="padding: 5px 10px; font-size: 12px; min-width: 32px; background: #0073aa; color: white; border-color: #0073aa;">' . esc_html($i) . '</span>';
                } else {
                    $page_url = add_query_arg(['paged' => $i], $request_uri);
                    echo '<a href="' . esc_url($page_url) . '" class="button" style="padding: 5px 10px; font-size: 12px; min-width: 32px;">' . esc_html($i) . '</a>';
                }
            }
            
            // Next button
            if ($pagination['has_next']) {
                $next_url = add_query_arg(['paged' => $current_page + 1], $request_uri);
                echo '<a href="' . esc_url($next_url) . '" class="button" style="padding: 5px 10px; font-size: 12px; min-width: 80px;">' . esc_html__('Next', 'folderra-smart-folder-organizer') . ' &raquo;</a>';
            }
            
            echo '</div>';
            echo '</div>';
            echo '</div>';
        }
    } else {
        echo '<div style="background: #fff; padding: 30px; text-align: center; border-radius: 5px; margin-top: 20px;">';
        echo '<p style="font-size: 16px; color: #666;">' . esc_html__('No folders found.', 'folderra-smart-folder-organizer') . '</p>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=folderra-sfo-new-folder')) . '" class="button button-primary">' . esc_html__('Create your first folder', 'folderra-smart-folder-organizer') . '</a>';
        echo '</div>';
    }
    
    echo '</div>';
    echo '</div>';
}

// Helper function to get template info
function fold82sm_get_template_info( $template_slug ) {

    // Normalize the template slug
    $template_slug = is_string( $template_slug ) ? sanitize_key( $template_slug ) : '';

    $templates = array(
        // FREE templates only
        'blog-posts' => array(
            'name'       => __( 'Blog Posts', 'folderra-smart-folder-organizer' ),
            'post_types' => array( 'post' ),
            'category'   => 'free',
        ),
        'pages' => array(
            'name'       => __( 'Pages', 'folderra-smart-folder-organizer' ),
            'post_types' => array( 'page' ),
            'category'   => 'free',
        ),
        'mixed' => array(
            'name'       => __( 'Mixed Content', 'folderra-smart-folder-organizer' ),
            'post_types' => array( 'page', 'post' ),
            'category'   => 'free',
        ),

        // SPECIAL AUTOMATIC TEMPLATES - AGGIUNGI QUESTI
        'auto-pages' => array(
            'name'       => __( 'All Pages (Special)', 'folderra-smart-folder-organizer' ),
            'post_types' => array( 'page' ),
            'category'   => 'special',
        ),
        'auto-posts' => array(
            'name'       => __( 'All Posts (Special)', 'folderra-smart-folder-organizer' ),
            'post_types' => array( 'post' ),
            'category'   => 'special',
        ),

        // PRO/Dynamic templates (labels only, no FREE feature unlock)
        'tag-folder' => array(
            'name'       => __( 'Tag Folder', 'folderra-smart-folder-organizer' ),
            'post_types' => array(), // dynamic
            'category'   => 'pro',
        ),
        'category-folder' => array(
            'name'       => __( 'Category Folder', 'folderra-smart-folder-organizer' ),
            'post_types' => array(), // dynamic
            'category'   => 'pro',
        ),
        'media-folder' => array(
            'name'       => __( 'Media Folder', 'folderra-smart-folder-organizer' ),
            'post_types' => array(), // dynamic
            'category'   => 'pro',
        ),

        // System fallback template
        'others' => array(
            'name'       => __( 'Others', 'folderra-smart-folder-organizer' ),
            'post_types' => array( 'post', 'page' ),
            'category'   => 'system',
        ),
    );

    // Default to "others" if template is not recognized
    return isset( $templates[ $template_slug ] ) ? $templates[ $template_slug ] : $templates['others'];
}

/**
 * Return the real item count for Dynamic folders (Tag/Category/Media).
 * Falls back to taxonomy term count for normal folders.
 */
function fold82sm_get_dynamic_folder_items_count( $folder_id, $template_slug ) {
    $folder_id     = absint( $folder_id );
    $template_slug = sanitize_key( $template_slug );

    if ( ! $folder_id ) {
        return 0;
    }

    // Read PRO dynamic rule (exists only for dynamic folders)
    $rule = get_term_meta( $folder_id, 'folderra_dynamic_rule', true );
    if ( ! is_array( $rule ) || empty( $rule['type'] ) ) {
        return 0;
    }

    // Small cache to avoid heavy queries on big folders list
    $cache_key = 'fold82sm_dyn_count_' . $folder_id;
    $cached    = get_transient( $cache_key );
    if ( false !== $cached ) {
        return (int) $cached;
    }

    $count = 0;

    switch ( $rule['type'] ) {
        case 'tag':
            $tag_slug = ! empty( $rule['tag_slug'] ) ? sanitize_title( $rule['tag_slug'] ) : '';
            if ( $tag_slug ) {
                $q = new WP_Query( array(
                    'post_type'      => array( 'post', 'page' ), // come nel PRO
                    'post_status'    => array( 'publish', 'private', 'draft', 'pending', 'future' ),
                    'posts_per_page' => 1,
                    'paged'          => 1,
                    'no_found_rows'  => false, // serve per found_posts
                    'fields'         => 'ids',
                    'tax_query'      => array(
                        array(
                            'taxonomy' => 'post_tag',
                            'field'    => 'slug',
                            'terms'    => $tag_slug,
                        ),
                    ),
                ) );
                $count = (int) $q->found_posts;
            }
            break;

        case 'category':
            $category_ids = array();
            if ( ! empty( $rule['category_ids'] ) && is_array( $rule['category_ids'] ) ) {
                $category_ids = array_filter( array_map( 'absint', $rule['category_ids'] ) );
            }
            if ( $category_ids ) {
                $q = new WP_Query( array(
                    'post_type'      => array( 'post' ),
                    'post_status'    => array( 'publish', 'private', 'draft', 'pending', 'future' ),
                    'posts_per_page' => 1,
                    'paged'          => 1,
                    'no_found_rows'  => false,
                    'fields'         => 'ids',
                    'tax_query'      => array(
                        array(
                            'taxonomy' => 'category',
                            'field'    => 'term_id',
                            'terms'    => $category_ids,
                        ),
                    ),
                ) );
                $count = (int) $q->found_posts;
            }
            break;

        case 'media':
    $media_type = ! empty( $rule['media_type'] ) ? sanitize_key( $rule['media_type'] ) : 'all';

    $q_args = array(
        'post_type'      => 'attachment',
        'post_status'    => array( 'inherit', 'private' ),
        'posts_per_page' => 1,
        'paged'          => 1,
        'no_found_rows'  => false, // serve per found_posts
        'fields'         => 'ids',
    );

    // Filter by media type if not "all"
    if ( 'all' !== $media_type ) {
        // WordPress accepts 'image' | 'video' | 'audio'
        $q_args['post_mime_type'] = $media_type;
    }

    $q     = new WP_Query( $q_args );
    $count = (int) $q->found_posts;
    break;

    }

    set_transient( $cache_key, (int) $count, 5 * MINUTE_IN_SECONDS );
    return (int) $count;
}


// ===== HELPER FUNCTIONS FOR CONSISTENCY =====

/**
 * Get folder query parameters (template and post types)
 * Centralized function to ensure consistency between PHP and AJAX
 */
function fold82sm_get_folder_query_params($folder_id) {
    $template_slug = get_term_meta($folder_id, 'folder_template', true);
    $template_info = fold82sm_get_template_info($template_slug);
    
    return [
        'template_slug' => $template_slug,
        'post_types' => $template_info['post_types'],
        'template_name' => $template_info['name']
    ];
}

// Helper function to get allowed content text
function fold82sm_get_allowed_content_text($post_types) {
    $labels = array();
    foreach ($post_types as $post_type) {
        $post_type_obj = get_post_type_object($post_type);
        if ($post_type_obj) {
            // Use English labels directly for consistency
            if ($post_type === 'post') {
                $labels[] = 'Post';
            } elseif ($post_type === 'page') {
                $labels[] = 'Page';
            } else {
                $labels[] = $post_type_obj->labels->singular_name;
            }
        }
    }
    
    if (count($labels) === 1) {
        return $labels[0] . ' only';
    } elseif (count($labels) === 2) {
        return $labels[0] . ' and ' . $labels[1];
    }
    
    return implode(', ', $labels);
}

// Page to view content of a single folder
function fold82sm_details_page() {
    if ( ! fold82sm_current_user_can_access() ) {
    wp_die( esc_html__( 'You do not have permission to access Folderra Smart Folder.', 'folderra-smart-folder-organizer' ) );
}

    // Get folder_id (sanitized from query string)
    $folder_id = 0;

    if ( isset( $_GET['folder_id'] ) ) {
        $folder_id = absint( wp_unslash( $_GET['folder_id'] ) );
    }


    // Basic folder ID validation
    if (!$folder_id) {
        echo '<div class="wrap">';
        echo '<div class="notice notice-error"><p>' . esc_html__('Invalid Folder ID.', 'folderra-smart-folder-organizer') . '</p></div>';
        echo '</div>';
        return;
    }

    // Verify nonce for folder details page
    $nonce_action = 'folderra_sfo_folder_details_nonce';

    if ( ! isset( $_GET['_wpnonce'] ) ) {
    // Se manca il nonce, rigenera la pagina con un nuovo nonce
    wp_safe_redirect( add_query_arg( 
        array( 
            'page' => 'folderra-sfo-folder-details',
            'folder_id' => $folder_id,
            '_wpnonce' => wp_create_nonce( $nonce_action )
        ), 
        admin_url( 'admin.php' ) 
    ) );
    exit;
}

if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), $nonce_action ) ) {
    // If nonce is invalid or expired, redirect to the same page with a new nonce
    wp_safe_redirect( add_query_arg( 
        array( 
            'page' => 'folderra-sfo-folder-details',
            'folder_id' => $folder_id,
            '_wpnonce' => wp_create_nonce( $nonce_action )
        ), 
        admin_url( 'admin.php' ) 
    ) );
    exit;
}

    // Breadcrumb
    echo '<div class="fold82sm-navigation" style="margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 5px; position: relative;">';
    echo '<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">';
    echo '<div style="flex: 1;">';
    echo '<h2 style="margin: 0 0 15px 0; color: #0073aa; display: flex; align-items: center; gap: 10px; font-size: 18px; font-weight: 600;">';
    echo '<img src="' . esc_url(plugins_url('assets/icon.png', __FILE__)) . '" style="width: 24px; height: 24px; border-radius: 3px;" alt="Folderra Smart Folder">';
    echo 'Folderra Smart Folder';
    echo '</h2>';
    echo '<nav style="display: flex; gap: 10px; flex-wrap: wrap;">';
    echo '<a href="' . esc_url(admin_url('admin.php?page=folderra-sfo-dashboard')) . '" style="padding: 8px 15px; background: #ffffff; color: #0073aa; text-decoration: none; border: 1px solid #0073aa; border-radius: 3px;">📊 Dashboard</a>';
    echo '<span style="color: #666;">›</span>';
    echo '<a href="' . esc_url(admin_url('admin.php?page=folderra-sfo-folders')) . '" style="padding: 8px 15px; background: #ffffff; color: #0073aa; text-decoration: none; border: 1px solid #0073aa; border-radius: 3px;">📁 Manage Folders</a>';
    echo '<span style="color: #666;">›</span>';
    echo '<span style="color: #333; padding: 8px 15px; background: #e9ecef; border-radius: 3px; font-weight: 500;">' . esc_html__('Folder Details', 'folderra-smart-folder-organizer') . '</span>';
    echo '</nav>';
    echo '</div>';
    echo '</div>';
    echo '</div>';

    $folder = get_term($folder_id, 'folderra_sfo_content_folder');

    if (!is_wp_error($folder)) {
        // ===== PAGINATION PARAMETERS  =====
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
        
        // Validate per_page values
        $valid_per_page_values = array(10, 25, 50, 100, -1);
        if (!in_array($per_page, $valid_per_page_values) && $per_page > 0) {
            $per_page = 10; // Default if invalid
        }

        $display_name = get_term_meta($folder_id, 'folder_display_name', true);
        $final_name = !empty($display_name) ? $display_name : $folder->name;

        // Get folder query parameters using helper
        $query_params = fold82sm_get_folder_query_params($folder_id);
        $template_info = [
            'name' => $query_params['template_name'],
            'post_types' => $query_params['post_types']
        ];

        // Content query with proper pagination
        // tax_query is required to filter posts by smart folder taxonomy
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
        $content_args = array(
            'post_type'      => $query_params['post_types'],
            'tax_query'      => array(
                array(
                    'taxonomy' => 'folderra_sfo_content_folder',
                    'field'    => 'term_id',
                    'terms'    => $folder_id,
                ),
            ),
            'orderby'        => 'menu_order',
            'order'          => 'ASC',
            'posts_per_page' => $per_page,
            'paged'          => $current_page,
            'post_status'    => array('publish', 'private', 'draft', 'pending', 'future')
        );

        $content_query = new WP_Query($content_args);
        $total_items   = $content_query->found_posts;
        $total_pages   = $per_page > 0 ? ceil($total_items / $per_page) : 1;

        echo '<div class="wrap">';
        echo '<div class="folder-details-container">';

        // ===== HEADER BOX =====
        echo '<div class="folder-header" style="background: #fff; padding: 20px; border-radius: 5px; margin-bottom: 20px;">';

        // Title + edit + dynamic badge.
        echo '<div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px; flex-wrap: wrap;">';

        // Folder title.
        echo '<h1 style="margin: 0;" id="folder-details-title">' . sprintf(
            /* translators: %s: smart folder name. */
            esc_html__( 'Folder: %s', 'folderra-smart-folder-organizer' ),
            esc_html( $final_name )
        ) . '</h1>';

        // Edit icon.
        echo '<i class="dashicons dashicons-edit folder-edit-icon"
                style="font-size: 16px; color: #0073aa; cursor: pointer; opacity: 0.7;"
                title="' . esc_attr__( 'Edit folder name', 'folderra-smart-folder-organizer' ) . '"
                data-folder-id="' . esc_attr( $folder->term_id ) . '"
                data-folder-name="' . esc_attr( $final_name ) . '"
            ></i>';

        echo '</div>';

        // Folder metadata info
        echo '<div style="display: flex; gap: 20px; align-items: center; flex-wrap: wrap; margin-bottom: 15px; padding: 15px; background: #f8f9fa; border-radius: 5px; border: 1px solid #e9ecef;">';

        // Template info
        echo '<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: white; border-radius: 4px; border: 1px solid #dee2e6;">';
        echo '<span class="dashicons dashicons-admin-generic" style="color: #0073aa; font-size: 16px;"></span>';
        echo '<span style="font-size: 13px; color: #333;"><strong>' . esc_html__('Template:', 'folderra-smart-folder-organizer') . '</strong> ' . esc_html($template_info['name']) . '</span>';
        echo '</div>';

        // Folder ID
        echo '<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: white; border-radius: 4px; border: 1px solid #dee2e6;">';
        echo '<span class="dashicons dashicons-id" style="color: #666; font-size: 16px;"></span>';
        echo '<span style="font-size: 13px; color: #333;"><strong>' . esc_html__('ID:', 'folderra-smart-folder-organizer') . '</strong> ' . esc_html($folder->term_id) . '</span>';
        echo '</div>';

        // Allowed content types
        echo '<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: white; border-radius: 4px; border: 1px solid #dee2e6;">';
        echo '<span class="dashicons dashicons-filter" style="color: #46b450; font-size: 16px;"></span>';
        echo '<span style="font-size: 13px; color: #333;"><strong>' . esc_html__('Allowed:', 'folderra-smart-folder-organizer') . '</strong> ' . esc_html(fold82sm_get_allowed_content_text($template_info['post_types'])) . '</span>';
        echo '</div>';

        // Total content in folder
        echo '<div style="display: flex; align-items: center; gap: 8px; padding: 8px 15px; background: #e7f3ff; border-radius: 4px; border: 1px solid #b3d7ff; min-width: 150px;">';
        echo '<span class="dashicons dashicons-admin-page" style="color: #0073aa; font-size: 18px;"></span>';
        echo '<div>';
        echo '<div style="font-size: 12px; color: #666; margin-bottom: 2px;">' . esc_html__('Total Content', 'folderra-smart-folder-organizer') . '</div>';
        echo '<div style="font-size: 20px; font-weight: bold; color: #0073aa;">' . esc_html($total_items) . '</div>';
        echo '</div>';
        echo '</div>';

        // Items per page (integrated in metadata bar)
        echo '<div style="display: flex; align-items: center; gap: 10px; padding: 8px 12px; background: white; border-radius: 4px; border: 1px solid #dee2e6;">';
        echo '<span class="dashicons dashicons-list-view" style="color: #666; font-size: 16px;"></span>';

        echo '<form method="get" action="" style="display:flex; align-items:center; gap:8px; margin:0;">';
        echo '<input type="hidden" name="page" value="folderra-sfo-folder-details">';
        echo '<input type="hidden" name="folder_id" value="' . esc_attr($folder_id) . '">';
        // quando cambi per_page, meglio ripartire da pagina 1
        echo '<input type="hidden" name="paged" value="1">';

        wp_nonce_field( $nonce_action, '_wpnonce', false );

        echo '<label style="font-weight: 600; font-size: 13px; color:#333; margin-right:4px;">' . esc_html__('Items:', 'folderra-smart-folder-organizer') . '</label>';

        echo '<select name="per_page" style="padding: 4px 8px; border-radius: 3px; border: 1px solid #ddd; font-size: 13px;">';

        $per_page_options = array(
            10  => '10',
            25  => '25',
            50  => '50',
            100 => '100',
            -1  => __('All', 'folderra-smart-folder-organizer')
        );

        foreach ( $per_page_options as $value => $label ) {
            printf(
                '<option value="%1$s"%2$s>%3$s</option>',
                esc_attr( $value ),
                selected( $per_page, $value, false ),
                esc_html( $label )
            );
        }

        echo '</select>';

        echo '<button type="submit" class="button button-primary" style="padding: 5px 12px; font-size: 13px; line-height: 1;">' . esc_html__('Apply', 'folderra-smart-folder-organizer') . '</button>';

        // Optional: Reset inline (solo se serve)
        if ( $per_page != 10 || $current_page > 1 ) {
            $reset_url = add_query_arg(
                array(
                    'page'      => 'folderra-sfo-folder-details',
                    'folder_id' => $folder_id,
                    '_wpnonce'  => wp_create_nonce( $nonce_action ),
                ),
                admin_url( 'admin.php' )
            );

            echo '<a href="' . esc_url( $reset_url ) . '" class="button" style="padding: 5px 10px; font-size: 13px; line-height: 1;">' . esc_html__( 'Reset', 'folderra-smart-folder-organizer' ) . '</a>';
        }

        echo '</form>';
        echo '</div>';


        echo '</div>'; // metadata box

        // ===== FOLDER ACTIONS (Add / Remove / Delete) =====
        echo '<div class="folder-actions" style="margin-top: 20px; display:flex; gap:10px; flex-wrap:wrap;">';

        // Normal folders: Add/Remove buttons enabled
        echo '<button id="add-page-btn" class="button button-primary" data-folder-id="' . esc_attr($folder->term_id) . '">' . esc_html__('Add Content', 'folderra-smart-folder-organizer') . '</button>';
        echo '<button id="remove-page-btn" class="button" data-folder-id="' . esc_attr($folder->term_id) . '">' . esc_html__('Remove Content', 'folderra-smart-folder-organizer') . '</button>';

        // Delete folder is always available
        echo '<button id="delete-folder-btn" class="button button-link-delete" data-folder-id="' . esc_attr($folder->term_id) . '">' . esc_html__('Delete Folder', 'folderra-smart-folder-organizer') . '</button>';
        echo '</div>'; // .folder-actions

        echo '</div>'; // .folder-header

        // ===== CONTENT LIST SECTION =====
        echo '<div class="folder-pages-section" style="background: #fff; padding: 20px; border-radius: 5px; margin-top: 20px;">';
        echo '<h2 style="margin: 0 0 20px 0;">' . esc_html__('Content in Folder', 'folderra-smart-folder-organizer') . '</h2>';

        echo '<div id="folder-pages" class="pages-container">';

        if ($content_query->have_posts()) {
            while ($content_query->have_posts()) {
                $content_query->the_post();
                global $post;

                $post_type_obj = get_post_type_object($post->post_type);
                $type_label = $post_type_obj ? $post_type_obj->labels->singular_name : $post->post_type;

                echo '<div class="content-block" data-content-id="' . esc_attr($post->ID) . '">';
                echo '<i class="dashicons dashicons-move content-drag" title="' . esc_attr__('Drag to reorder', 'folderra-smart-folder-organizer') . '"></i>';
                echo '<h2 class="content-title">' . esc_html(get_the_title()) . ' <span class="content-type-badge">' . esc_html($type_label) . '</span></h2>';

                // Desktop actions
                echo '<div class="content-actions">';
                echo '<a href="' . esc_url(get_permalink()) . '" target="_blank">';
                echo '<i class="dashicons dashicons-visibility" title="' . esc_attr__('View', 'folderra-smart-folder-organizer') . '"></i>';
                echo '</a>';
                echo '<a href="' . esc_url(get_edit_post_link()) . '">';
                echo '<i class="dashicons dashicons-edit" title="' . esc_attr__('Edit', 'folderra-smart-folder-organizer') . '"></i>';
                echo '</a>';
                echo '<a href="javascript:void(0);" class="duplicate-content-icon" data-content-id="' . esc_attr($post->ID) . '">';
                echo '<i class="dashicons dashicons-admin-page" title="' . esc_attr__('Duplicate', 'folderra-smart-folder-organizer') . '"></i>';
                echo '</a>';
                echo '<a href="javascript:void(0);" class="delete-content-icon" data-content-id="' . esc_attr($post->ID) . '">';
                echo '<i class="dashicons dashicons-trash" title="' . esc_attr__('Delete', 'folderra-smart-folder-organizer') . '"></i>';
                echo '</a>';
                echo '</div>';

                // Mobile actions
                echo '<div class="content-actions-menu">';
                echo '<button class="content-menu-toggle">';
                echo '<i class="dashicons dashicons-menu-alt3" title="' . esc_attr__('Actions menu', 'folderra-smart-folder-organizer') . '"></i>';
                echo '</button>';
                echo '<div class="content-dropdown-menu">';
                echo '<a href="' . esc_url(get_permalink()) . '" target="_blank" class="content-dropdown-item">';
                echo '<i class="dashicons dashicons-visibility"></i>';
                echo esc_html__('View', 'folderra-smart-folder-organizer');
                echo '</a>';
                echo '<a href="' . esc_url(get_edit_post_link()) . '" class="content-dropdown-item">';
                echo '<i class="dashicons dashicons-edit"></i>';
                echo esc_html__('Edit', 'folderra-smart-folder-organizer');
                echo '</a>';
                echo '<a href="javascript:void(0);" class="content-dropdown-item duplicate-content-mobile" data-content-id="' . esc_attr($post->ID) . '">';
                echo '<i class="dashicons dashicons-admin-page"></i>';
                echo esc_html__('Duplicate', 'folderra-smart-folder-organizer');
                echo '</a>';
                echo '<a href="javascript:void(0);" class="content-dropdown-item delete-content-mobile" data-content-id="' . esc_attr($post->ID) . '">';
                echo '<i class="dashicons dashicons-trash"></i>';
                echo esc_html__('Delete', 'folderra-smart-folder-organizer');
                echo '</a>';
                echo '</div>';
                echo '</div>';

                echo '</div>';
            }
            wp_reset_postdata();
        } else {
            // Empty state
            echo '<div style="text-align: center; padding: 60px 20px; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">';
            echo '<div style="font-size: 48px; margin-bottom: 20px; color: #ccc;">📁</div>';
            echo '<h3 style="color: #666; margin-bottom: 15px; font-size: 18px;">' . esc_html__('This folder is empty', 'folderra-smart-folder-organizer') . '</h3>';
            echo '<p style="color: #888; margin-bottom: 25px; font-size: 14px; max-width: 400px; margin-left: auto; margin-right: auto;">';
            echo sprintf(
            /* translators: %s: folder name wrapped in <strong> tag */
            esc_html__('Start organizing your content by adding pages or posts to %s', 'folderra-smart-folder-organizer'),
            '<strong>' . esc_html($final_name) . '</strong>'
        );
            echo '</p>';
            echo '<button class="button button-primary" onclick="jQuery(\'#add-page-btn\').click();" style="background: #0073aa; border-color: #0073aa; font-size: 14px; padding: 8px 20px;">';
            echo '<span style="font-size: 16px; margin-right: 8px;">+</span>';
            echo esc_html__('Add Your First Content', 'folderra-smart-folder-organizer');
            echo '</button>';
            echo '<p style="color: #999; margin-top: 15px; font-size: 12px;">';
            echo esc_html__('Click the button above to start adding content', 'folderra-smart-folder-organizer');
            echo '</p>';
            echo '</div>';
        }

        echo '</div>'; // .pages-container

        // ===== SERVER-SIDE PAGINATION (BOTTOM) =====
        if ($total_pages > 1) {
            $start = (($current_page - 1) * $per_page) + 1;
            $end = $per_page > 0 ? min($current_page * $per_page, $total_items) : $total_items;
            
            // Get current URL for pagination links
            $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '';
            
            echo '<div class="fold82sm-pagination" style="margin-top: 30px; padding: 15px; background: #f8f9fa; border-radius: 5px; border-top: 1px solid #ddd;">';
            echo '<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">';
            
            // Items info
            echo '<div>';
            echo '<span style="color: #666; font-size: 13px;">';
            echo sprintf(
            /* translators: 1: first item number shown, 2: last item number shown, 3: total number of items. */
                esc_html__('Showing %1$s - %2$s of %3$s items', 'folderra-smart-folder-organizer'),
                '<strong>' . esc_html($start) . '</strong>',
                '<strong>' . esc_html($end) . '</strong>',
                '<strong>' . esc_html($total_items) . '</strong>'
            );
            echo '</span>';
            echo '</div>';
            
            // Page navigation
            echo '<div style="display: flex; gap: 5px; align-items: center;">';
            
            // Previous button
            if ($current_page > 1) {
                $prev_url = add_query_arg(['paged' => $current_page - 1], $request_uri);
                echo '<a href="' . esc_url($prev_url) . '" class="button" style="padding: 5px 10px; font-size: 12px; min-width: 80px;">&laquo; ' . esc_html__('Previous', 'folderra-smart-folder-organizer') . '</a>';
            }
            
            // Page numbers
            $max_pages_to_show = 5;
            $start_page = max(1, $current_page - floor($max_pages_to_show / 2));
            $end_page = min($total_pages, $start_page + $max_pages_to_show - 1);
            
            // Adjust if we're near the end
            if ($end_page - $start_page + 1 < $max_pages_to_show) {
                $start_page = max(1, $end_page - $max_pages_to_show + 1);
            }
            
            for ($i = $start_page; $i <= $end_page; $i++) {
                if ($i == $current_page) {
                    echo '<span class="button button-primary" style="padding: 5px 10px; font-size: 12px; min-width: 32px; background: #0073aa; color: white; border-color: #0073aa;">' . esc_html($i) . '</span>';
                } else {
                    $page_url = add_query_arg(['paged' => $i], $request_uri);
                    echo '<a href="' . esc_url($page_url) . '" class="button" style="padding: 5px 10px; font-size: 12px; min-width: 32px;">' . esc_html($i) . '</a>';
                }
            }
            
            // Next button
            if ($current_page < $total_pages) {
                $next_url = add_query_arg(['paged' => $current_page + 1], $request_uri);
                echo '<a href="' . esc_url($next_url) . '" class="button" style="padding: 5px 10px; font-size: 12px; min-width: 80px;">' . esc_html__('Next', 'folderra-smart-folder-organizer') . ' &raquo;</a>';
            }
            
            echo '</div>';
            echo '</div>';
            echo '</div>';
        }

        echo '</div>'; // .folder-details-container
        echo '</div>'; // .wrap

    } else {
        echo '<div class="wrap">';
        echo '<div class="notice notice-error"><p>' . esc_html__('Error:', 'folderra-smart-folder-organizer') . ' ' . esc_html($folder->get_error_message()) . '</p></div>';
        echo '</div>';
    }
}

/**
 * Render a "Recently modified" dashboard box for a given post type.
 *
 * @param string $post_type 'page' or 'post'
 * @param string $title Box title
 * @param string $icon Dashicon class (without prefix)
 * @param int    $limit Max items
 * @param string $color 'blue' or 'green'
 */
function fold82sm_render_recently_modified_box( $post_type, $title, $icon, $limit = 6, $color = 'blue' ) {
    $allowed_statuses = array( 'publish', 'draft', 'pending', 'future', 'private' );

    // Determine box color
    if ( $color === 'green' ) {
        $border_color = '#27ae60';
        $shadow_color = 'rgba(39,174,96,0.15)';
        $icon_color   = '#27ae60';
    } else {
        $border_color = '#0073aa';
        $shadow_color = 'rgba(0,115,170,0.15)';
        $icon_color   = '#0073aa';
    }

    $q = new WP_Query( array(
        'post_type'              => $post_type,
        'post_status'            => $allowed_statuses,
        'posts_per_page'         => absint( $limit ),
        'orderby'                => 'modified',
        'order'                  => 'DESC',
        'no_found_rows'          => true,
        'ignore_sticky_posts'    => true,
        'update_post_meta_cache' => false,
        'update_post_term_cache' => false,
    ) );

    echo '<div class="fold82sm-recent-box" style="background:#fff; padding:20px; border-radius:8px; border-left:4px solid ' . esc_attr( $border_color ) . '; box-shadow:0 4px 12px ' . esc_attr( $shadow_color ) . '; min-width:0; width:100%; box-sizing:border-box;">';
    echo '  <div style="display:flex; align-items:center; gap:10px; margin-bottom:10px;">';
    echo '    <span class="dashicons dashicons-' . esc_attr( $icon ) . '" style="font-size:22px; color:' . esc_attr( $icon_color ) . ';"></span>';
    echo '    <h4 style="margin:0; color:#23282d; font-size:16px; font-weight:700;">' . esc_html( $title ) . '</h4>';
    echo '  </div>';

    echo '  <p style="margin:0 0 14px 0; font-size:13px; color:#666;">' . esc_html__( 'Jump back into what you were working on — instantly.', 'folderra-smart-folder-organizer' ) . '</p>';

    if ( $q->have_posts() ) {
        echo '<div class="fold82sm-recent-items" style="display:flex; flex-direction:column; gap:10px;">';

        while ( $q->have_posts() ) {
            $q->the_post();

            $post_id    = get_the_ID();
            $raw_title  = get_the_title( $post_id );
            $item_title = $raw_title ? $raw_title : esc_html__( '(no title)', 'folderra-smart-folder-organizer' );

            $edit_url = admin_url( 'post.php?post=' . $post_id . '&action=edit' );

            // Determine view or preview URL
            if ( 'publish' === get_post_status( $post_id ) ) {
                $view_url  = get_permalink( $post_id );
                $view_text = esc_html__( 'View', 'folderra-smart-folder-organizer' );
            } else {
                $view_url  = function_exists( 'get_preview_post_link' ) ? get_preview_post_link( $post_id ) : $edit_url;
                $view_text = esc_html__( 'Preview', 'folderra-smart-folder-organizer' );
            }

            $modified_ts    = get_post_modified_time( 'U', true, $post_id );
            $now_ts         = current_time( 'timestamp' );
            $diff_hours     = ( $now_ts - $modified_ts ) / 3600;
            $modified_human = human_time_diff( $modified_ts, $now_ts );
            $modified_exact = get_post_modified_time(
                get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
                true,
                $post_id
            );

            // Status label
            $status       = get_post_status( $post_id );
            $status_label = ucfirst( (string) $status );

            // Badge logic
            $badge = '';
            if ( $diff_hours <= 24 ) {
                $badge = '<span style="background:#28a745;color:#fff;font-size:10px;padding:2px 6px;border-radius:10px;margin-left:6px;">NEW</span>';
            } elseif ( $diff_hours <= 48 ) {
                $badge = '<span style="background:#ffc107;color:#000;font-size:10px;padding:2px 6px;border-radius:10px;margin-left:6px;">YESTERDAY</span>';
            }

            echo '<div class="fold82sm-recent-item" style="display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px; background:#f8f9fa; border-radius:6px; border:1px solid #e9ecef; min-width:0; width:100%; box-sizing:border-box;">';

            echo '  <div style="flex:1 1 auto; min-width:0; overflow:hidden;">';
            echo '    <div style="font-size:13px; font-weight:600; color:#2c3338; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">';
            echo esc_html( $item_title ) . $badge;
            echo '    </div>';

            echo '    <div style="font-size:12px; color:#666; margin-top:4px;">';
            echo '      <span style="background:#e9ecef;padding:2px 6px;border-radius:10px;margin-right:6px;font-size:11px;">' . esc_html( $status_label ) . '</span>';
            echo sprintf(
                /* translators: 1: human time diff, 2: exact datetime */
                esc_html__( 'Modified %1$s ago • %2$s', 'folderra-smart-folder-organizer' ),
                esc_html( $modified_human ),
                esc_html( $modified_exact )
            );
            echo '    </div>';
            echo '  </div>';

            echo '  <div style="display:flex; gap:8px; flex-shrink:0;">';
            echo '    <a class="button button-small" href="' . esc_url( $edit_url ) . '">' . esc_html__( 'Edit', 'folderra-smart-folder-organizer' ) . '</a>';
            echo '    <a class="button button-small" target="_blank" rel="noopener noreferrer" href="' . esc_url( $view_url ) . '">' . $view_text . '</a>';
            echo '  </div>';

            echo '</div>';
        } // end while

        echo '</div>'; // end items wrapper
        wp_reset_postdata();
    } else {
        echo '<div style="padding:14px; background:#f8f9fa; border-radius:6px; border:1px dashed #ddd; color:#666; font-size:13px;">';
        echo esc_html__( 'No items found yet.', 'folderra-smart-folder-organizer' );
        echo '</div>';
    }

    echo '</div>'; // end box
}

// Settings page
function fold82sm_settings_page() {
    if (!fold82sm_current_user_can_access()) {
        wp_die( esc_html__( 'You do not have permission to access Folderra Smart Folder.', 'folderra-smart-folder-organizer' ) );
    }
    
    // ADD MENU NAVIGATION
    fold82sm_navigation('settings');
    
    // Save settings if form is submitted
    if (isset($_POST['fold82sm_settings_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['fold82sm_settings_nonce'])), 'fold82sm_save_settings')) {
        fold82sm_save_settings();
    }
    
    // Get current settings
    $settings = fold82sm_get_settings();
    
    // Get all WordPress roles
    global $wp_roles;
    $all_roles = $wp_roles->roles;
    
    // Define role icons and descriptions
    $role_icons = array(
        'administrator' => 'dashicons-admin-users',
        'editor'        => 'dashicons-edit',
        'author'        => 'dashicons-admin-post',
        'contributor'   => 'dashicons-admin-comments',
        'subscriber'    => 'dashicons-admin-users'
    );
    
    $role_descriptions = array(
        'administrator' => __('Full access to all features (always enabled)', 'folderra-smart-folder-organizer'),
        'editor'        => __('Can manage folders and content', 'folderra-smart-folder-organizer'),
        'author'        => __('Can add content to folders', 'folderra-smart-folder-organizer'),
        'contributor'   => __('Limited access (recommended disabled)', 'folderra-smart-folder-organizer'),
        'subscriber'    => __('Read-only access (recommended disabled)', 'folderra-smart-folder-organizer')
    );
    
    echo '<div class="fold82sm-settings-container">';
    
    // Settings header
    echo '<div class="fold82sm-settings-header">';
    echo '<h1>';
    echo '<span class="dashicons dashicons-admin-settings"></span>';
    echo esc_html__('Settings', 'folderra-smart-folder-organizer');
    echo '</h1>';
    echo '<p>' . esc_html__('Configure general behavior and user access for the Folderra Smart Folder plugin.', 'folderra-smart-folder-organizer') . '</p>';
    echo '</div>';
    
    // Settings form
    echo '<div class="fold82sm-settings-form">';
    echo '<form method="post" action="">';
    wp_nonce_field('fold82sm_save_settings', 'fold82sm_settings_nonce');

    // General Settings Section
    echo '<div class="fold82sm-section-header">';
    echo '<span class="dashicons dashicons-admin-generic"></span>';
    echo esc_html__( 'General', 'folderra-smart-folder-organizer' );
    echo '</div>';

    echo '<p>' . esc_html__( 'Configure general Folderra behavior across the WordPress admin area.', 'folderra-smart-folder-organizer' ) . '</p>';

    echo '<table class="fold82sm-roles-table">';
    echo '<tbody>';

    // Redirect Pages toggle
    echo '<tr>';
    echo '<td>';
    echo '<div class="fold82sm-setting-switch-row">';
    echo '<div class="fold82sm-setting-label-group">';
    echo '<div class="fold82sm-role-checkbox" style="margin-bottom: 6px;">';
    echo '<span class="dashicons dashicons-admin-page fold82sm-role-icon"></span>';
    echo '<strong>' . esc_html__( 'Replace default Pages screen with Folderra All Pages', 'folderra-smart-folder-organizer' ) . '</strong>';
    echo '</div>';
    echo '<div class="fold82sm-role-desc">';
    echo '<span class="fold82sm-role-status fold82sm-role-enabled">' . esc_html__( 'Enabled by default', 'folderra-smart-folder-organizer' ) . '</span>';
    echo '<p>' . esc_html__( 'When enabled, clicking Pages in WordPress opens the Folderra All Pages view instead of the default WordPress list.', 'folderra-smart-folder-organizer' ) . '</p>';
    echo '</div>';
    echo '</div>';

    echo '<label class="fold82sm-switch" for="fold82sm_redirect_pages_to_all">';
    echo '<input type="checkbox" id="fold82sm_redirect_pages_to_all" name="redirect_pages_to_all" value="1" ' . checked( ! empty( $settings['redirect_pages_to_all'] ), true, false ) . '>';
    echo '<span class="fold82sm-slider" aria-hidden="true"></span>';
    echo '<span class="screen-reader-text">' . esc_html__( 'Toggle Pages redirect', 'folderra-smart-folder-organizer' ) . '</span>';
    echo '</label>';

    echo '</div>';
    echo '</td>';
    echo '<td></td>';
    echo '</tr>';

    // Redirect Posts toggle
    echo '<tr>';
    echo '<td>';
    echo '<div class="fold82sm-setting-switch-row">';
    echo '<div class="fold82sm-setting-label-group">';
    echo '<div class="fold82sm-role-checkbox" style="margin-bottom: 6px;">';
    echo '<span class="dashicons dashicons-edit fold82sm-role-icon"></span>';
    echo '<strong>' . esc_html__( 'Replace default Posts screen with Folderra All Posts', 'folderra-smart-folder-organizer' ) . '</strong>';
    echo '</div>';
    echo '<div class="fold82sm-role-desc">';
    echo '<span class="fold82sm-role-status fold82sm-role-enabled">' . esc_html__( 'Enabled by default', 'folderra-smart-folder-organizer' ) . '</span>';
    echo '<p>' . esc_html__( 'When enabled, clicking Posts in WordPress opens the Folderra All Posts view instead of the default WordPress list.', 'folderra-smart-folder-organizer' ) . '</p>';
    echo '</div>';
    echo '</div>';

    echo '<label class="fold82sm-switch" for="fold82sm_redirect_posts_to_all">';
    echo '<input type="checkbox" id="fold82sm_redirect_posts_to_all" name="redirect_posts_to_all" value="1" ' . checked( ! empty( $settings['redirect_posts_to_all'] ), true, false ) . '>';
    echo '<span class="fold82sm-slider" aria-hidden="true"></span>';
    echo '<span class="screen-reader-text">' . esc_html__( 'Toggle Posts redirect', 'folderra-smart-folder-organizer' ) . '</span>';
    echo '</label>';

    echo '</div>';
    echo '</td>';
    echo '<td></td>';
    echo '</tr>';

    // Close General table before starting next section
    echo '</tbody>';
    echo '</table>';
    
    // User Role Management Section
    echo '<div class="fold82sm-section-header">';
    echo '<span class="dashicons dashicons-admin-users"></span>';
    echo esc_html__('User Role Access Control', 'folderra-smart-folder-organizer');
    echo '</div>';
    
    echo '<p>' . esc_html__('Select which user roles can access and manage Folderra Smart Folder.', 'folderra-smart-folder-organizer') . '</p>';
    
    echo '<table class="fold82sm-roles-table">';
    echo '<thead>';
    echo '<tr>';
    echo '<th>' . esc_html__('Role', 'folderra-smart-folder-organizer') . '</th>';
    echo '<th>' . esc_html__('Access Permission', 'folderra-smart-folder-organizer') . '</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    
    foreach ($all_roles as $role_slug => $role_details) {
        $role_name        = $role_details['name'];
        $is_enabled       = in_array( $role_slug, $settings['allowed_roles'], true );
        $is_default       = in_array( $role_slug, array( 'administrator', 'editor' ), true );
        $is_administrator = ( 'administrator' === $role_slug );
        $icon_class       = isset( $role_icons[ $role_slug ] ) ? $role_icons[ $role_slug ] : 'dashicons-admin-users';
        $description      = isset( $role_descriptions[ $role_slug ] ) ? $role_descriptions[ $role_slug ] : '';
        
        echo '<tr>';
        echo '<td>';
        echo '<div class="fold82sm-role-checkbox">';
        
        // For Administrator: always included as hidden input + visual checkbox.
        if ( $is_administrator ) {
            echo '<input type="hidden" name="allowed_roles[]" value="administrator">';
            echo '<input type="checkbox" checked disabled>';
        } else {
            echo '<input type="checkbox" name="allowed_roles[]" value="' . esc_attr( $role_slug ) . '" ' . checked( $is_enabled, true, false ) . '>';
        }
        
        echo '<label>';
        echo '<span class="dashicons ' . esc_attr($icon_class) . ' fold82sm-role-icon"></span>';
        echo '<strong>' . esc_html($role_name) . '</strong>';
        if ($is_default) {
            echo '<span class="fold82sm-role-default">' . esc_html__('Default', 'folderra-smart-folder-organizer') . '</span>';
        }
        echo '</label>';
        echo '</div>';
        echo '</td>';
        echo '<td>';
        echo '<div class="fold82sm-role-desc">';
        if ( $is_administrator ) {
        echo '<span class="fold82sm-role-status fold82sm-role-always">' . esc_html__( 'Always Enabled', 'folderra-smart-folder-organizer' ) . '</span>';
        } elseif ( $is_enabled ) {
        echo '<span class="fold82sm-role-status fold82sm-role-enabled">' . esc_html__( 'Enabled', 'folderra-smart-folder-organizer' ) . '</span>';
        } else {
        echo '<span class="fold82sm-role-status fold82sm-role-disabled">' . esc_html__( 'Disabled', 'folderra-smart-folder-organizer' ) . '</span>';
        }

        echo '<p>' . esc_html($description) . '</p>';
        echo '</div>';
        echo '</td>';
        echo '</tr>';
    }
    
    echo '</tbody>';
    echo '</table>';
    
    // Save button
    echo '<div style="margin-top: 30px;">';
    echo '<button type="submit" class="fold82sm-save-button">';
    echo '<span class="dashicons dashicons-yes-alt"></span>';
    echo esc_html__('Save Settings', 'folderra-smart-folder-organizer');
    echo '</button>';
    echo '</div>';
    
    echo '</form>';
    echo '</div>'; // .fold82sm-settings-form
    
    // Information panel
    echo '<div class="fold82sm-info-panel">';
    echo '<h3>';
    echo '<span class="dashicons dashicons-info"></span>';
    echo esc_html__('About User Role Permissions', 'folderra-smart-folder-organizer');
    echo '</h3>';
    
    echo '<ul>';
    echo '<li><strong>' . esc_html__('Administrator', 'folderra-smart-folder-organizer') . ':</strong> ' . esc_html__('Full access to all features. This role cannot be disabled for security reasons.', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li><strong>' . esc_html__('Editor', 'folderra-smart-folder-organizer') . ':</strong> ' . esc_html__('Can create, edit, and delete folders and content. Recommended for content managers.', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li><strong>' . esc_html__('Author', 'folderra-smart-folder-organizer') . ':</strong> ' . esc_html__('Can add their own content to existing folders but cannot manage folder structure.', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li><strong>' . esc_html__('Contributor', 'folderra-smart-folder-organizer') . ':</strong> ' . esc_html__('Limited access. Can only view assigned content. Not recommended for folder management.', 'folderra-smart-folder-organizer') . '</li>';
    echo '<li><strong>' . esc_html__('Subscriber', 'folderra-smart-folder-organizer') . ':</strong> ' . esc_html__('Read-only access. Can only view content in folders they have access to.', 'folderra-smart-folder-organizer') . '</li>';
    echo '</ul>';
    
    echo '<div class="fold82sm-info-note">';
    echo '<strong>' . esc_html__('Note:', 'folderra-smart-folder-organizer') . '</strong> ';
    echo esc_html__('Changes to role permissions take effect immediately. Users will see the Folderra menu based on their assigned permissions.', 'folderra-smart-folder-organizer');
    echo '</div>';
    echo '</div>'; // .fold82sm-info-panel
    
    echo '</div>'; // .fold82sm-settings-container
}

// Save settings function
function fold82sm_save_settings() {
    // Verify nonce with proper sanitization
    if (!isset($_POST['fold82sm_settings_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['fold82sm_settings_nonce'])), 'fold82sm_save_settings')) {
        echo '<div class="notice notice-error"><p>' . esc_html__('Security check failed.', 'folderra-smart-folder-organizer') . '</p></div>';
        return;
    }

    // Get current settings merged with defaults
    $current_settings = fold82sm_get_settings();

    // Prepare new settings
    $new_settings = array();

    // Process allowed roles
    if (isset($_POST['allowed_roles']) && is_array($_POST['allowed_roles'])) {
        $new_settings['allowed_roles'] = array_map('sanitize_key', wp_unslash($_POST['allowed_roles']));

        // Always include administrator for security
        if (!in_array('administrator', $new_settings['allowed_roles'], true)) {
            $new_settings['allowed_roles'][] = 'administrator';
        }
    } else {
        $new_settings['allowed_roles'] = array('administrator', 'editor');
    }

    // Process general toggles
    $new_settings['redirect_pages_to_all'] = isset($_POST['redirect_pages_to_all']) ? 1 : 0;
    $new_settings['redirect_posts_to_all'] = isset($_POST['redirect_posts_to_all']) ? 1 : 0;

    // Preserve any future settings keys unless intentionally overwritten
    $new_settings = array_merge($current_settings, $new_settings);

    // Save settings
    update_option('fold82sm_settings', $new_settings);

    // Show success message
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Settings saved successfully!', 'folderra-smart-folder-organizer') . '</p></div>';
}

// ===== AJAX FUNCTIONS =====

// AJAX function to save folders order
add_action('wp_ajax_fold82sm_save_folders_order', 'fold82sm_save_folders_order');
function fold82sm_save_folders_order() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('You do not have permission to manage folders.', 'folderra-smart-folder-organizer')], 403);
    }

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

    if (empty($folders_order)) {
        wp_send_json_error(['message' => __('No ordering data received.', 'folderra-smart-folder-organizer')]);
        return;
    }

    foreach ($folders_order as $index => $folder_id) {
        $folder_id = intval($folder_id);
        update_term_meta($folder_id, 'folder_order', intval($index));
    }

        wp_send_json_success(['message' => __('Folder order saved successfully!', 'folderra-smart-folder-organizer')]);
}

// FUNCTION TO SAVE PAGE ORDER AFTER DRAG AND DROP
add_action('wp_ajax_fold82sm_save_page_order', 'fold82sm_save_page_order');
function fold82sm_save_page_order() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }

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


    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;



    if (empty($page_order) || !$folder_id) {
        wp_send_json_error(array('message' => 'Invalid data.'));
        return;
    }

    // Update page order
    foreach ($page_order as $index => $page_id) {
        $page_id = absint($page_id);


        
        // Update 'menu_order' field with current order
        wp_update_post(array(
            'ID' => $page_id,
            'menu_order' => intval($index)
        ));
    }

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

// AJAX function to delete a folder
add_action('wp_ajax_fold82sm_delete_folder', 'fold82sm_delete_folder');
function fold82sm_delete_folder() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }
    
    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;

    if ($folder_id) {               
        $result = wp_delete_term($folder_id, 'folderra_sfo_content_folder');

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        } else {
            wp_send_json_success(['message' => __('Folder deleted successfully!', 'folderra-smart-folder-organizer')]);
        }
    } else {
        wp_send_json_error(['message' => __('Invalid Folder ID.', 'folderra-smart-folder-organizer')]);
    }
}

// AJAX function to get content in a folder
add_action('wp_ajax_fold82sm_get_content_in_folder', 'fold82sm_get_content_in_folder');
function fold82sm_get_content_in_folder() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }
    
    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;
    $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
    $per_page = isset($_POST['per_page']) ? intval($_POST['per_page']) : 10;
    
    if (!$folder_id) {
        wp_send_json_error(['message' => 'Invalid Folder ID.']);
        return;
    }
    
    // Get folder query parameters using helper (ensures consistency with page load)
$query_params = fold82sm_get_folder_query_params($folder_id);
$allowed_post_types = $query_params['post_types'];
    
    // Get content assigned to the folder with proper pagination
    // tax_query is required for filtering by smart folder taxonomy
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
    $content_args = array(
        'post_type' => $allowed_post_types,
        'tax_query' => array(
            array(
                'taxonomy' => 'folderra_sfo_content_folder',
                'field'    => 'term_id',
                'terms'    => $folder_id,
            ),
        ),
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'posts_per_page' => $per_page,
        'paged' => $page,
        'post_status' => array('publish', 'private', 'draft', 'pending', 'future')
    );
    
    $content_query = new WP_Query($content_args);
    $content = $content_query->posts;
    $total_items = $content_query->found_posts;
    
    if (!empty($content)) {
        $content_data = [];
        foreach ($content as $item) {
            $post_type_obj = get_post_type_object($item->post_type);
            $content_data[] = [
                'id'    => $item->ID,
                'title' => $item->post_title,
                'type'  => $post_type_obj ? $post_type_obj->labels->singular_name : $item->post_type,
                'view_url' => get_permalink($item->ID),
                'edit_url' => get_edit_post_link($item->ID),
                'icon'  => ($item->post_type === 'post') ? 'dashicons-edit' : 'dashicons-admin-page'
            ];
        }
        
        // Return pagination info
        wp_send_json_success([
            'content' => $content_data,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $per_page,
                'total_items' => $total_items,
                'total_pages' => $per_page > 0 ? ceil($total_items / $per_page) : 1,
                'has_prev' => $page > 1,
                'has_next' => $per_page > 0 ? ($page < ceil($total_items / $per_page)) : false
            ]
        ]);
    } else {
        // Empty state
        $folder = get_term($folder_id, 'folderra_sfo_content_folder');
        $folder_name = !empty($folder) ? $folder->name : 'this folder';
        
        $empty_state_html = '
        <div style="text-align: center; padding: 60px 20px; background: #f8f9fa; border-radius: 8px; border: 2px dashed #ddd;">
            <div style="font-size: 48px; margin-bottom: 20px; color: #ccc;">📁</div>
            <h3 style="color: #666; margin-bottom: 15px; font-size: 18px;">' . esc_html__('This folder is empty', 'folderra-smart-folder-organizer') . '</h3>
            <p style="color: #888; margin-bottom: 25px; font-size: 14px; max-width: 400px; margin-left: auto; margin-right: auto;">
                ' . sprintf(
            /* translators: %s: folder name wrapped in <strong> tag */
            esc_html__('Start organizing your content by adding pages or posts to %s', 'folderra-smart-folder-organizer'),
            '<strong>' . esc_html($folder_name) . '</strong>'
        ) . '
            </p>
            <button class="button button-primary" onclick="jQuery(\'#add-page-btn\').click();" style="background: #0073aa; border-color: #0073aa; font-size: 14px; padding: 8px 20px;">
                <span style="font-size: 16px; margin-right: 8px;">+</span>
                ' . esc_html__('Add Your First Content', 'folderra-smart-folder-organizer') . '
            </button>
        </div>';
        
        wp_send_json_success([
            'content' => [],
            'pagination' => [
                'current_page' => $page,
                'per_page' => $per_page,
                'total_items' => 0,
                'total_pages' => 0,
                'has_prev' => false,
                'has_next' => false
            ],
            'empty_state' => true,
            'empty_html' => $empty_state_html
        ]);
    }
}

// AJAX function to get available content for a folder
add_action('wp_ajax_fold82sm_get_available_content', 'fold82sm_get_available_content');
function fold82sm_get_available_content() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }

    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;

    if (!$folder_id) {
        wp_send_json_error(['message' => 'Invalid Folder ID.']);
        return;
    }

    // Get folder template to determine allowed post types
    $template_slug = get_term_meta($folder_id, 'folder_template', true);
    
    // Define allowed post types based on template
    $allowed_post_types = ['page', 'post']; // Default mixed
    
    if ($template_slug === 'pages') {
        $allowed_post_types = ['page']; // Only pages
    } elseif ($template_slug === 'blog-posts') {
        $allowed_post_types = ['post']; // Only posts
    } elseif ($template_slug === 'mixed') {
        $allowed_post_types = ['page', 'post']; // Both pages and posts
    }

    // Get content already assigned to the folder
    // tax_query is required for filtering by smart folder taxonomy
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
    $content_in_folder = get_posts(array(
        'post_type' => $allowed_post_types,
        'tax_query' => array(
            array(
                'taxonomy' => 'folderra_sfo_content_folder',
                'field'    => 'term_id',
                'terms'    => $folder_id,
            ),
        ),
        'fields' => 'ids',
        'posts_per_page' => -1
    ));

    // Get all available content not already assigned to the folder
    // Use tax_query with NOT IN for better performance (replaces post__not_in)
    // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
    $available_content = get_posts(array(
        'post_type' => $allowed_post_types,
        'tax_query' => array(
            array(
                'taxonomy' => 'folderra_sfo_content_folder',
                'field'    => 'term_id',
                'terms'    => $folder_id,
                'operator' => 'NOT IN', // Posts NOT in this folder
            ),
        ),
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC'
    ));

    if (!empty($available_content)) {
        $content_data = [];
        foreach ($available_content as $item) {
            $post_type_obj = get_post_type_object($item->post_type);
            $content_data[] = [
                'id'    => $item->ID,
                'title' => $item->post_title,
                'type'  => $post_type_obj ? $post_type_obj->labels->singular_name : $item->post_type,
                'icon'  => ($item->post_type === 'post') ? 'dashicons-edit' : 'dashicons-admin-page'
            ];
        }
        wp_send_json_success(['content' => $content_data]);
    } else {
        wp_send_json_error(['message' => 'No available content to add.']);
    }
}

// AJAX function to add content to folder
add_action('wp_ajax_fold82sm_add_content_to_folder', 'fold82sm_add_content_to_folder');
function fold82sm_add_content_to_folder() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }
    
    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;
    $content_id = isset($_POST['content_id']) ? absint($_POST['content_id']) : 0;

    if (!$folder_id || !$content_id) {
        wp_send_json_error(array('message' => __('Invalid Folder ID or Content ID.', 'folderra-smart-folder-organizer')));
        return;
    }

    $result = wp_set_post_terms($content_id, $folder_id, 'folderra_sfo_content_folder', true);

    if (is_wp_error($result)) {
        wp_send_json_error(array('message' => $result->get_error_message()));
    } else {
        wp_send_json_success(array('message' => 'Content added successfully!'));
    }
}

// AJAX function to remove content from folder
add_action('wp_ajax_fold82sm_remove_content_from_folder', 'fold82sm_remove_content_from_folder');
function fold82sm_remove_content_from_folder() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }

    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;
    $content_id = isset($_POST['content_id']) ? absint($_POST['content_id']) : 0;

    if (!$folder_id || !$content_id) {
        wp_send_json_error(array('message' => 'Invalid Folder ID or Content ID.'));
        return;
    }

    // Remove content from folder
    wp_remove_object_terms($content_id, $folder_id, 'folderra_sfo_content_folder');
    wp_send_json_success(array('message' => 'Content removed successfully!'));
}

// AJAX function to duplicate a page
add_action('wp_ajax_fold82sm_duplicate_page', 'fold82sm_duplicate_page');
function fold82sm_duplicate_page() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }

    $page_id = isset($_POST['page_id']) ? absint($_POST['page_id']) : 0;
    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;

    if (!$page_id) {
        wp_send_json_error(['message' => 'Invalid Page ID.']);
        return;
    }

    // Get original page
    $original_page = get_post($page_id);
    
    if (!$original_page) {
        wp_send_json_error(['message' => 'Original page not found.']);
        return;
    }

    // Prepare data for new page
    $page_data = array(
        'post_title'    => $original_page->post_title . ' - Copy',
        'post_content'  => $original_page->post_content,
        'post_status'   => $original_page->post_status,
        'post_type'     => $original_page->post_type,
        'post_author'   => get_current_user_id(),
        'post_excerpt'  => $original_page->post_excerpt,
        'menu_order'    => $original_page->menu_order + 1,
    );

    // Insert new page
    $new_page_id = wp_insert_post($page_data);

    if (is_wp_error($new_page_id)) {
        wp_send_json_error(['message' => 'Error during page duplication.']);
        return;
    }

    // Copy metadata
    $meta_data = get_post_meta($page_id);
    foreach ($meta_data as $key => $values) {
        foreach ($values as $value) {
            add_post_meta($new_page_id, $key, maybe_unserialize($value));
        }
    }

    // If folder is specified, add the duplicate page to the folder
        if ($folder_id) {
        $result = wp_set_post_terms($new_page_id, $folder_id, 'folderra_sfo_content_folder', true);
        
        if (is_wp_error($result)) {
            // If assignment fails, delete the duplicate page
            wp_delete_post($new_page_id, true);
            wp_send_json_error(['message' => 'Error assigning duplicated page to folder.']);
            return;
        }
    }

    wp_send_json_success([
        'message' => 'Page duplicated successfully!',
        'new_page_id' => $new_page_id,
        'new_page_title' => $page_data['post_title']
    ]);
}

// AJAX function to create folder from template
add_action('wp_ajax_fold82sm_create_folder_from_template', 'fold82sm_create_folder_from_template');
function fold82sm_create_folder_from_template() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }
    $folder_name = isset($_POST['folder_name']) ? sanitize_text_field(wp_unslash($_POST['folder_name'])) : '';
    $template_slug = isset($_POST['template_slug']) ? sanitize_text_field(wp_unslash($_POST['template_slug'])) : '';
    
    if (empty($folder_name) || empty($template_slug)) {
        wp_send_json_error(['message' => __('Folder name and template are required.', 'folderra-smart-folder-organizer')]);
        return;
    }

    // Define template configurations (FREE TEMPLATES ONLY)
    $templates_config = array(
        'blog-posts' => array(
            'name' => 'Blog Posts',
            'post_types' => array('post')
        ),
        'pages' => array(
            'name' => 'Pages',
            'post_types' => array('page')
        ),
        'mixed' => array(
            'name' => 'Mixed Content',
            'post_types' => array('page', 'post')
        )
    );

    // Create folder
    $result = wp_insert_term($folder_name, 'folderra_sfo_content_folder');
    
    if (is_wp_error($result)) {
        wp_send_json_error(['message' => $result->get_error_message()]);
    } else {
        $folder_id = absint($result['term_id']);              
        // Save template metadata with post types
        update_term_meta($folder_id, 'folder_template', $template_slug);
        update_term_meta($folder_id, 'folder_display_name', $folder_name);
        update_term_meta($folder_id, 'folder_order', 0);
        
        // Save allowed post types for this template
        if (isset($templates_config[$template_slug])) {
            update_term_meta($folder_id, 'allowed_post_types', $templates_config[$template_slug]['post_types']);
        }

        // Clear cache for immediate visibility
        clean_term_cache($folder_id, 'folderra_sfo_content_folder');
        
        $redirect_url = admin_url('admin.php?page=folderra-sfo-folder-details&folder_id=' . $folder_id);
        $nonce_action = 'folderra_sfo_folder_details_nonce';
        $nonce = wp_create_nonce($nonce_action);
        $redirect_url = add_query_arg('_wpnonce', $nonce, $redirect_url);
        
        wp_send_json_success([
            'folder_id' => $folder_id,
            'redirect_url' => $redirect_url,
            'message' => 'Folder created successfully!'
        ]);
    }
}


// AJAX function to update folder name
add_action('wp_ajax_fold82sm_update_folder_name', 'fold82sm_update_folder_name');
function fold82sm_update_folder_name() {
    check_ajax_referer('fold82sm_nonce', 'nonce');

    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }

    $folder_id = isset($_POST['folder_id']) ? absint($_POST['folder_id']) : 0;


    $new_name = isset($_POST['new_name']) ? sanitize_text_field(wp_unslash($_POST['new_name'])) : '';

    if (!$folder_id || empty($new_name)) {
        wp_send_json_error(['message' => __('Invalid Folder ID or folder name.', 'folderra-smart-folder-organizer')]);
        return;
    }

    // SAVE THE NAME AS METADATA
    $result = update_term_meta($folder_id, 'folder_display_name', $new_name);
    
    // We also update the official name of the term for compatibility
    $term_result = wp_update_term($folder_id, 'folderra_sfo_content_folder', array(
        'name' => $new_name
    ));

    if (is_wp_error($term_result) && !$result) {
        wp_send_json_error(['message' => 'Error updating folder name.']);
    } else {
        wp_send_json_success([
            'message' => __('Folder name updated successfully!', 'folderra-smart-folder-organizer'),
            'new_name' => $new_name
        ]);
    }
}

// AJAX function to save folder selection in metabox
add_action('wp_ajax_fold82sm_save_folder_selection', 'fold82sm_save_folder_selection');
function fold82sm_save_folder_selection() {
    check_ajax_referer('fold82sm_nonce', 'nonce');
    
    if (!current_user_can('fold82sm_access')) {
        wp_send_json_error(['message' => __('Permission denied.', 'folderra-smart-folder-organizer')], 403);
    }
    
    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $folder_ids = isset($_POST['folder_ids']) ? array_map('intval', $_POST['folder_ids']) : [];
    
    if (!$post_id) {
        wp_send_json_error(['message' => 'Invalid Post ID.']);
        return;
    }
    
    $post = get_post($post_id);
    if (!$post) {
        wp_send_json_error(['message' => 'Post not found.']);
        return;
    }
      
    // Use wp_set_object_terms instead of wp_set_post_terms
    $result = wp_set_object_terms($post_id, $folder_ids, 'folderra_sfo_content_folder', false);
    
    if (is_wp_error($result)) {
        wp_send_json_error(['message' => $result->get_error_message()]);
    } else {
        wp_send_json_success(['message' => 'Folder assignment saved successfully!']);
    }
}

// ===== META BOX IN EDITOR =====
add_action( 'add_meta_boxes', 'fold82sm_add_meta_box' );
function fold82sm_add_meta_box() {

    $post_types = array( 'post', 'page' );

    foreach ( $post_types as $post_type ) {
        add_meta_box(
            'fold82sm_meta_box',
            esc_html__( 'Smart Folder', 'folderra-smart-folder-organizer' ),
            'fold82sm_meta_box_callback',
            $post_type,
            'side',
            'default'
        );
    }
}

// Meta box callback (FULL metabox UI)
function fold82sm_meta_box_callback( $post ) {
    if ( ! function_exists( 'fold82sm_current_user_can_access' ) || ! fold82sm_current_user_can_access() ) {
        echo '<div style="padding: 10px; background: #f8f9fa; border: 1px solid #e5e5e5; border-radius: 3px; text-align: center;">';
        echo '<p style="margin: 0; color: #666; font-size: 12px;">' .
            esc_html__( 'You do not have permission to manage folders.', 'folderra-smart-folder-organizer' ) .
        '</p>';
        echo '</div>';
        return;
    }

    echo '<div class="fold82sm-metabox-wrap" style="padding: 2px 0;">';

    echo '<input type="text" id="wpsmartfolder-search" placeholder="' .
        esc_attr__( 'Search folders...', 'folderra-smart-folder-organizer' ) .
    '" style="width:100%; margin: 6px 0 10px 0;" />';

    echo '<div style="display:flex; justify-content:space-between; align-items:center; font-size:11px; color:#666; margin-bottom:8px;">';
    echo '<span><strong id="selected-count">0</strong> ' . esc_html__( 'selected', 'folderra-smart-folder-organizer' ) . '</span>';
    echo '<span><strong id="total-count">0</strong> ' . esc_html__( 'shown', 'folderra-smart-folder-organizer' ) . '</span>';
    echo '</div>';

    echo '<div id="wpsmartfolder-folders-container" style="border:1px solid #e5e5e5; border-radius:4px; padding:8px; max-height:220px; overflow:auto; background:#fff;"></div>';

    echo '<div style="margin-top:10px; display:flex; gap:8px;">';
    echo '<button type="button" class="button button-primary" id="wpsmartfolder-save-selection" disabled style="flex:1;">' .
        esc_html__( 'Save Selection', 'folderra-smart-folder-organizer' ) .
    '</button>';
    echo '</div>';

    echo '<p style="margin:10px 0 0 0; color:#666; font-size:11px; line-height:1.3;">' .
        esc_html__( 'Assign this content to one or more folders.', 'folderra-smart-folder-organizer' ) .
    '</p>';

    echo '</div>';
}


// Enqueue metabox script only on post editor screens
add_action( 'admin_enqueue_scripts', 'fold82sm_enqueue_metabox_assets' );
function fold82sm_enqueue_metabox_assets( $hook ) {
    if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
        return;
    }

    if ( ! function_exists( 'fold82sm_current_user_can_access' ) || ! fold82sm_current_user_can_access() ) {
        return;
    }

    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
    if ( ! $screen || empty( $screen->post_type ) ) {
        return;
    }

    if ( ! in_array( $screen->post_type, array( 'post', 'page' ), true ) ) {
        return;
    }

    global $post;
    $post_id = ( $post && isset( $post->ID ) ) ? absint( $post->ID ) : 0;
    $post_type = $screen->post_type;

    // Get all folders and filter by post type compatibility
    $folders = get_terms(
        array(
            'taxonomy'   => 'folderra_sfo_content_folder',
            'hide_empty' => false,
        )
    );

    $available_folders = array();

if ( ! is_wp_error( $folders ) ) {

    $allowed_metabox_templates = array( 'blog-posts', 'pages', 'mixed' );

    foreach ( $folders as $f ) {

        // Get folder template to check allowed post types
        $template_slug = get_term_meta( $f->term_id, 'folder_template', true );
        $template_slug = is_string( $template_slug ) ? sanitize_key( $template_slug ) : '';

        if ( ! in_array( $template_slug, $allowed_metabox_templates, true ) ) {
            continue;
        }

        $template_info = fold82sm_get_template_info( $template_slug );

        // Check if this folder can contain the current post type
        $post_types = ( isset( $template_info['post_types'] ) && is_array( $template_info['post_types'] ) )
            ? $template_info['post_types']
            : array();

        if ( in_array( $post_type, $post_types, true ) ) {
            $available_folders[] = array(
                'id'    => absint( $f->term_id ),
                'name'  => $f->name,
                'count' => absint( $f->count ),
            );
        }
    }
}

    // Selected folders for this post
    $selected_terms = wp_get_object_terms(
        $post_id,
        'folderra_sfo_content_folder',
        array( 'fields' => 'ids' )
    );

    $selected_folders = array();
    if ( ! is_wp_error( $selected_terms ) && is_array( $selected_terms ) ) {
        $selected_folders = array_map( 'absint', $selected_terms );
    }

    wp_enqueue_script(
        'fold82sm-metabox',
        plugins_url( 'js/wpsmartfolder-metabox.js', __FILE__ ),
        array( 'jquery' ),
        defined( 'FOLD82SM_VERSION' ) ? FOLD82SM_VERSION : '1.4.0',
        true
    );

    wp_localize_script(
        'fold82sm-metabox',
        'fold82smMetaboxData',
        array(
            'ajax_url'          => admin_url( 'admin-ajax.php' ),
            'action'            => 'fold82sm_save_folder_selection',
            'nonce'             => wp_create_nonce( 'fold82sm_nonce' ),
            'post_id'           => $post_id,
            'available_folders' => $available_folders,
            'selected_folders'  => $selected_folders,
            'i18n'              => array(
                'no_folders_found' => esc_html__( 'No folders found', 'folderra-smart-folder-organizer' ),
                'saving'           => esc_html__( 'Saving...', 'folderra-smart-folder-organizer' ),
                'saved'            => esc_html__( 'Saved!', 'folderra-smart-folder-organizer' ),
                'error_saving'     => esc_html__( 'Error saving selection', 'folderra-smart-folder-organizer' ),
            ),
        )
    );
}

/**
 * Gutenberg editor fixes: hide the default Smart Folders taxonomy panel
 * (we keep only Folderra custom metabox with Save button).
 */
add_action( 'enqueue_block_editor_assets', 'folderra_enqueue_editor_fixes' );
function folderra_enqueue_editor_fixes() {

    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
    if ( ! $screen || ! in_array( $screen->post_type, array( 'post', 'page' ), true ) ) {
        return;
    }

    // Optional: limit to users who can access Folderra
    if ( function_exists( 'fold82sm_current_user_can_access' ) && ! fold82sm_current_user_can_access() ) {
        return;
    }

    wp_enqueue_script(
        'folderra-editor-fixes',
        plugins_url( 'js/folderra-editor-fixes.js', __FILE__ ),
        array( 'wp-data', 'wp-dom-ready', 'wp-edit-post' ),
        '1.4.0',
        true
    );
}


// ===== SCRIPT AND STYLE MANAGEMENT =====

// Function to load scripts and styles in WordPress backend
add_action('admin_enqueue_scripts', 'fold82sm_enqueue_scripts');
function fold82sm_enqueue_scripts($hook) {
    
    if ( ! function_exists( 'fold82sm_current_user_can_access' ) || ! fold82sm_current_user_can_access() ) {
    return;
}
    
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
    $our_pages = array(
    'folderra-sfo-dashboard',
    'folderra-sfo-new-folder',
    'folderra-sfo-folders',
    'folderra-sfo-folder-details',
    'fold82sm-settings',
    'folderra-sfo-special-folder',
    'folderra-sfo-media-organizer'
);
    
    // Load styles on ALL plugin pages
    if ( in_array( $page, $our_pages, true ) ) {
        // Get plugin directory URL
        $plugin_url = plugin_dir_url(__FILE__);
        
        // Construct CSS URL
        $css_url = $plugin_url . 'css/wpsmartfolder.css';
        
        // Verify file exists
        $css_path = plugin_dir_path(__FILE__) . 'css/wpsmartfolder.css';
        
        if ( file_exists( $css_path ) ) {
    wp_enqueue_style(
        'fold82sm-admin-css',
        $css_url,
        array(),
        FOLD82SM_VERSION,
        'all'
        );
      }

    }

    // Load settings page script
    if ($page === 'fold82sm-settings') {
        wp_enqueue_script('fold82sm-settings', plugins_url('js/wpsmartfolder-settings.js', __FILE__), array('jquery'), FOLD82SM_VERSION, true);
    }
    
    // Check if we are on "New Folder" page
    if ($page === 'folderra-sfo-new-folder') {
        wp_enqueue_script(
            'fold82sm-new-folder',
            plugins_url('js/wpsmartfolder-new-folder.js', __FILE__),
            array('jquery'),
            FOLD82SM_VERSION,
            true
        );

        // Base JS data
        $js_data = array(
            'ajax_url'      => admin_url('admin-ajax.php'),
            'nonce'         => wp_create_nonce('fold82sm_nonce'),
        );

        wp_localize_script('fold82sm-new-folder', 'fold82smData', $js_data);
    }

    // Check if we are on folder details page
    if ($page === 'folderra-sfo-folder-details') {
        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_script('fold82sm-admin', plugins_url('js/wpsmartfolder-admin.js', __FILE__), array('jquery', 'jquery-ui-sortable'), FOLD82SM_VERSION, true);
        wp_localize_script('fold82sm-admin', 'fold82smData', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('fold82sm_nonce')
        ));
    }

    // Check if we are on folders list page
    if ($page === 'folderra-sfo-folders') {
        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_script('fold82sm-folders', plugins_url('js/wpsmartfolder-folders.js', __FILE__), array('jquery', 'jquery-ui-sortable'), FOLD82SM_VERSION, true);
        wp_localize_script('fold82sm-folders', 'fold82smData', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('fold82sm_nonce')
        ));
    }

    // Dashboard mini analytics script
if ( $page === 'folderra-sfo-dashboard' ) {
    wp_enqueue_script(
        'fold82sm-dashboard-analytics',
        plugins_url( 'js/wpsmartfolder-dashboard-analytics.js', __FILE__ ),
        array( 'jquery' ),
        FOLD82SM_VERSION,
        true
    );

    wp_localize_script(
        'fold82sm-dashboard-analytics',
        'fold82smMiniAnalytics',
        array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'fold82sm_mini_analytics' ),
            'limit'    => 5,
        )
    );
}

// Media Organizer script (only on its page)
if ( $page === 'folderra-sfo-media-organizer' ) {

    // Load WP pointer library (required for $.fn.pointer)
    wp_enqueue_script( 'wp-pointer' );
    wp_enqueue_style( 'wp-pointer' );

    // Load Special Folder styles for consistent UI
$sf_css_path = plugin_dir_path( __FILE__ ) . 'css/special-folder.css';
if ( file_exists( $sf_css_path ) ) {
    wp_enqueue_style(
        'fold82sm-special-folder-css',
        plugins_url( 'css/special-folder.css', __FILE__ ),
        array( 'fold82sm-admin-css' ),
        FOLD82SM_VERSION
    );
}

    wp_enqueue_script(
        'fold82sm-media-organizer',
        plugins_url( 'js/folderra-media-organizer.js', __FILE__ ),
        array( 'jquery', 'wp-pointer' ),
        FOLD82SM_VERSION,
        true
    );

    wp_localize_script(
        'fold82sm-media-organizer',
        'fold82smMediaOrganizer',
        array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'fold82sm_media_organizer' ),
        )
    );
}

// Special Folder script (only on its page)
if ( $page === 'folderra-sfo-special-folder' ) {
    wp_enqueue_style(
        'fold82sm-special-folder-css',
        plugins_url( 'css/special-folder.css', __FILE__ ),
        array( 'fold82sm-admin-css' ),
        FOLD82SM_VERSION
    );

    wp_enqueue_script( 'jquery-ui-sortable' );

    wp_enqueue_script(
        'fold82sm-special-folder-js',
        plugins_url( 'js/special-folder.js', __FILE__ ),
        array( 'jquery', 'jquery-ui-sortable' ),
        FOLD82SM_VERSION,
        true
    );

    $folder_type = isset( $_GET['folder_type'] ) ? sanitize_text_field( wp_unslash( $_GET['folder_type'] ) ) : 'pages';
    $post_type   = ( $folder_type === 'pages' ) ? 'page' : 'post';
    $slug        = ( $folder_type === 'pages' ) ? 'all-pages' : 'all-posts';
    $folder      = get_term_by( 'slug', $slug, 'folderra_sfo_content_folder' );
    $folder_id   = ( $folder && ! is_wp_error( $folder ) ) ? (int) $folder->term_id : 0;

    wp_localize_script(
        'fold82sm-special-folder-js',
        'fold82smSpecialData',
        array(
            'ajax_url'    => admin_url( 'admin-ajax.php' ),
            'nonce'       => wp_create_nonce( 'fold82sm_nonce' ),
            'post_type'   => $post_type,
            'folder_id'   => $folder_id,
            'folder_type' => $folder_type,
        )
    );
}

}

// ===== PLUGIN ROW META =====

// Add upgrade message in plugin list (WordPress.org compliant)
add_filter('plugin_row_meta', 'fold82sm_plugin_row_meta', 10, 2);
function fold82sm_plugin_row_meta($links, $file) {
    if (plugin_basename(__FILE__) === $file) {
        $upgrade_link = array(
            'upgrade' => '<a href="https://wpsmartfolder.com/pro" target="_blank" rel="noopener noreferrer">' . __('Upgrade to PRO', 'folderra-smart-folder-organizer') . '</a>'
        );
        $links = array_merge($links, $upgrade_link);
    }
    return $links;
}

// Add settings link
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'fold82sm_plugin_action_links' );
function fold82sm_plugin_action_links( $links ) {
    $settings_url  = admin_url( 'admin.php?page=fold82sm-settings' );
    $settings_link = array(
        'settings' => '<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings', 'folderra-smart-folder-organizer' ) . '</a>',
    );
    return array_merge( $settings_link, $links );
}


add_action( 'admin_init', 'fold82sm_maybe_redirect_default_content_screens' );

/**
 * Redirect default Posts and Pages list screens to Folderra special views.
 *
 * @return void
 */
function fold82sm_maybe_redirect_default_content_screens() {
    if ( ! is_admin() ) {
        return;
    }

    if ( wp_doing_ajax() ) {
        return;
    }

    if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
        return;
    }

    if ( ! current_user_can( 'fold82sm_access' ) ) {
        return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $pagenow = isset( $GLOBALS['pagenow'] ) ? $GLOBALS['pagenow'] : '';

    if ( 'edit.php' !== $pagenow ) {
        return;
    }

    // Allow manual bypass for troubleshooting or plugin compatibility.
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset( $_GET['folderra_bypass'] ) ) {
        return;
    }

    // Avoid redirect when filters, searches, bulk actions, pagination,
    // custom ordering, or other query-modifying operations are present.
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $allowed_query_keys = array( 'post_type' );

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $current_query_keys = array_keys( $_GET );
    $unexpected_keys    = array_diff( $current_query_keys, $allowed_query_keys );

    if ( ! empty( $unexpected_keys ) ) {
        return;
    }

    $settings = fold82sm_get_settings();

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : 'post';

    if ( 'page' === $post_type && ! empty( $settings['redirect_pages_to_all'] ) ) {
        $redirect_url = add_query_arg(
            array(
                'page'        => 'folderra-sfo-special-folder',
                'folder_type' => 'pages',
                '_wpnonce'    => wp_create_nonce( 'folderra_special_folder_nonce' ),
            ),
            admin_url( 'admin.php' )
        );

        wp_safe_redirect( $redirect_url );
        exit;
    }

    if ( 'post' === $post_type && ! empty( $settings['redirect_posts_to_all'] ) ) {
        $redirect_url = add_query_arg(
            array(
                'page'        => 'folderra-sfo-special-folder',
                'folder_type' => 'posts',
                '_wpnonce'    => wp_create_nonce( 'folderra_special_folder_nonce' ),
            ),
            admin_url( 'admin.php' )
        );

        wp_safe_redirect( $redirect_url );
        exit;
    }
}

// ===== ENHANCED ACTIVATION NOTICE =====

// Show activation notice only on plugins.php page
add_action('admin_notices', 'fold82sm_enhanced_activation_notice');
function fold82sm_enhanced_activation_notice() {
    // Show ONLY on plugins.php page
    global $pagenow;
    if ($pagenow !== 'plugins.php') {
        return;
    }
    
    if (get_option('fold82sm_show_activation_notice', false)) {
        // Check if there are ANY folders in the system
        $folders_count = fold82sm_get_visible_folders_count();

        
        $is_first_install = ($folders_count == 0);
        
        if ($is_first_install) {
            // FIRST INSTALL - Enhanced welcome notice
            ?>
            <div class="notice notice-info is-dismissible" style="border-left-color: #0073aa; padding: 20px; margin: 15px 0;">
                <div style="display: flex; align-items: flex-start; gap: 15px;">
                    <div style="font-size: 32px; line-height: 1;">🎉</div>
                    <div style="flex: 1;">
                        <h3 style="margin: 0 0 10px 0; color: #0073aa; font-size: 18px;">
                            <?php esc_html_e('Welcome to Folderra Smart Folder!', 'folderra-smart-folder-organizer'); ?>
                        </h3>
                        <p style="margin: 0 0 15px 0; font-size: 14px; line-height: 1.5;">
                            <?php esc_html_e('Get started by creating your first folder to organize your content.', 'folderra-smart-folder-organizer'); ?>
                        </p>
                        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                            <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-new-folder')); ?>" class="button button-primary" style="padding: 8px 16px; font-weight: bold;">
                                <?php esc_html_e('✨ Create Your First Folder', 'folderra-smart-folder-organizer'); ?>
                            </a>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-dashboard')); ?>" class="button" style="padding: 8px 16px;">
                                <?php esc_html_e('📊 View Dashboard', 'folderra-smart-folder-organizer'); ?>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        } else {
            // REACTIVATION - Enhanced success notice
            ?>
            <div class="notice notice-success is-dismissible" style="border-left-color: #46b450; border-left-width: 4px; padding: 20px; margin: 15px 0; background: #f7fff7;">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="font-size: 28px; line-height: 1;">✅</div>
                    <div style="flex: 1;">
                        <h3 style="margin: 0 0 8px 0; color: #2c5b2d; font-size: 18px; font-weight: 700;">
                            <?php esc_html_e('Folderra Smart Folder Reactivated Successfully!', 'folderra-smart-folder-organizer'); ?>
                        </h3>
                        <p style="margin: 0 0 15px 0; font-size: 14px; line-height: 1.5; color: #333;">
                            <strong><?php esc_html_e('Welcome back!', 'folderra-smart-folder-organizer'); ?></strong> 
                            <?php 
                            printf(
                                /* translators: %s: number of folders */
        esc_html__('You have %s existing folders ready to use.', 'folderra-smart-folder-organizer'),
                                '<strong style="color: #0073aa;">' . esc_html($folders_count) . '</strong>'
                            ); 
                            ?>
                        </p>
                        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                            <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-dashboard')); ?>" class="button button-primary" style="padding: 8px 20px; font-weight: bold; background: #0073aa; border-color: #005a87;">
                                <span style="margin-right: 5px;">🚀</span>
                                <?php esc_html_e('Open Dashboard', 'folderra-smart-folder-organizer'); ?>
                            </a>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-folders')); ?>" class="button" style="padding: 8px 16px; background: #f0f7ff; border-color: #0073aa; color: #0073aa;">
                                <span style="margin-right: 5px;">📁</span>
                                <?php 
                                printf(
                                    /* translators: %s: number of folders. */
                                    esc_html__('Manage %s Folders', 'folderra-smart-folder-organizer'),
                                    '<strong>' . esc_html($folders_count) . '</strong>'
                                ); 
                                ?>
                            </a>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=folderra-sfo-new-folder')); ?>" class="button" style="padding: 8px 16px;">
                                <span style="margin-right: 5px;">➕</span>
                                <?php esc_html_e('Add New Folder', 'folderra-smart-folder-organizer'); ?>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
        
        delete_option('fold82sm_show_activation_notice');
    }
}

// ===== Includes: Media Organizer =====
require_once plugin_dir_path( __FILE__ ) . 'includes/class-folderra-media-organizer.php';

// Set activation notice flag
register_activation_hook(__FILE__, 'fold82sm_set_activation_notice_flag');

function fold82sm_set_activation_notice_flag() {
    add_option('fold82sm_show_activation_notice', true);
    add_option('fold82sm_show_welcome', true);

    $settings = get_option('fold82sm_settings', array());

    if (!is_array($settings)) {
        $settings = array();
    }

    $settings = wp_parse_args(
        $settings,
        array(
            'allowed_roles'         => array('administrator', 'editor'),
            'redirect_pages_to_all' => 1,
            'redirect_posts_to_all' => 1,
        )
    );

    update_option('fold82sm_settings', $settings);
}

/**
 * Plugin availability check for extensions
 * Only checks plugin existence
 */
function fold82sm_core_available() {
    return true;
}

/**
 * Signal that core plugin is loaded
 * Standard hook practice
 */
add_action('plugins_loaded', function() {
    do_action('fold82sm_core_loaded');
}, 5);

// Helper function to get relationships count using WordPress API
function fold82sm_get_relationships_count() {
    // Get all folder IDs using WordPress API
    $folders = get_terms(array(
        'taxonomy'   => 'folderra_sfo_content_folder',
        'hide_empty' => false,
        'fields'     => 'ids',
        'number'     => 0, // Get all folders
    ));
    
    if (is_wp_error($folders) || empty($folders)) {
        return 0;
    }
    
    // Sum the count of all relationships (posts in folders)
    $total_relationships = 0;
    foreach ($folders as $folder_id) {
        $folder = get_term($folder_id, 'folderra_sfo_content_folder');
        if (!is_wp_error($folder)) {
            $total_relationships += $folder->count;
        }
    }
    
    return $total_relationships;
}

/**
 * Check if Folderra PRO is installed/active (signal only).
 *
 * @return bool
 */
function fold82sm_is_pro_active() {
    // PRO defines this constant in wp-smart-folder-pro.php
    if ( defined( 'WP_SMART_FOLDER_PRO_VERSION' ) ) {
        return true;
    }

    // PRO main init function
    if ( function_exists( 'wpsmartfolder_pro_init' ) ) {
        return true;
    }

    return false;
}

/**
 * Check if Folderra PRO license is valid.
 * Safe: returns false when PRO is not active or licensing function is unavailable.
 *
 * @return bool
 */
function fold82sm_is_pro_licensed() {
    if ( function_exists( 'wpsmartfolder_pro_is_licensed' ) ) {
        return (bool) wpsmartfolder_pro_is_licensed();
    }
    return false;
}


// Get filtered folders
function fold82sm_get_filtered_folders($args = []) {
    $defaults = [
        'page'        => 1,
        'per_page'    => 10,
        'folder_type' => 'all',
        'search'      => ''
    ];

    $args = wp_parse_args($args, $defaults);

    // SIMPLE ORDERING LOGIC:
    // 1. First by folder_order ASC (if set via drag & drop)
    // 2. Then by creation date DESC (newest first for unordered folders)
    // Note: No orderby/meta_key in query - sorting done manually after
    $query_args = [
        'taxonomy'   => 'folderra_sfo_content_folder',
        'hide_empty' => false,
    ];

    // Apply folder type filter
    if ($args['folder_type'] !== 'all') {
        $folder_type = (string) $args['folder_type'];
        $meta_filter = null;

        switch ($folder_type) {
            case 'post':
                $meta_filter = [
                    'key'     => 'folder_template',
                    'value'   => ['blog-posts', 'category-folder'],
                    'compare' => 'IN'
                ];
                break;

            case 'page':
                $meta_filter = [
                    'key'     => 'folder_template',
                    'value'   => ['pages', 'landing-page'],
                    'compare' => 'IN'
                ];
                break;

            case 'mixed':
                $meta_filter = [
                    'key'     => 'folder_template',
                    'value'   => ['mixed', 'ab-test', 'funnel', 'tag-folder'],
                    'compare' => 'IN'
                ];
                break;

            // ✅ Dynamic templates - filter only those folders
            case 'tag-folder':
            case 'category-folder':
            case 'media-folder':
                $meta_filter = [
                    'key'     => 'folder_template',
                    'value'   => $folder_type,
                    'compare' => '='
                ];
                break;
        }

        if (!empty($meta_filter)) {
            // get_terms expects meta_query as an array of clauses
            $query_args['meta_query'] = [$meta_filter];
        }
    }

    // Apply search (get_terms uses name__like for term name)
    if (!empty($args['search'])) {
        $query_args['name__like'] = sanitize_text_field($args['search']);
    }

    // Hide nested folders from the main folders list.
if ( empty( $query_args['meta_query'] ) || ! is_array( $query_args['meta_query'] ) ) {
    $query_args['meta_query'] = array();
}

$query_args['meta_query'][] = array(
    'key'     => 'folderra_parent_folder',
    'compare' => 'NOT EXISTS',
);

// Hide PRO Dynamic folders when PRO is inactive or license is not valid.
// Dynamic folders are identified by:
// - folderra_dynamic_rule term_meta (PRO engine)
// - folder_template meta values (tag-folder/category-folder/media-folder/media-subfolder)
if ( ! fold82sm_is_pro_licensed() ) {

    // 1) Exclude any folder that has a dynamic rule.
    $query_args['meta_query'][] = array(
        'key'     => 'folderra_dynamic_rule',
        'compare' => 'NOT EXISTS',
    );

    // 2) Extra safety: exclude known PRO-only dynamic templates (even if rule meta is missing).
    $query_args['meta_query'][] = array(
        'relation' => 'OR',
        array(
            'key'     => 'folder_template',
            'compare' => 'NOT EXISTS',
        ),
        array(
            'key'     => 'folder_template',
            'value'   => array( 'tag-folder', 'category-folder', 'media-folder', 'media-subfolder' ),
            'compare' => 'NOT IN',
        ),
    );
}


// Hide special auto-generated folders (e.g. All Pages / All Posts) from the main folders list.
$query_args['meta_query'][] = array(
    'key'     => 'folder_is_special',
    'compare' => 'NOT EXISTS',
);

    // Get all folders
    $all_folders = get_terms($query_args);

    if (is_wp_error($all_folders)) {
        return [
            'folders' => [],
            'pagination' => [
                'current_page' => $args['page'],
                'per_page'     => $args['per_page'],
                'total_items'  => 0,
                'total_pages'  => 0,
                'has_prev'     => false,
                'has_next'     => false
            ]
        ];
    }

    // SIMPLE SORTING: Manual order first, then new folders
    usort($all_folders, function($a, $b) {
        $order_a = get_term_meta($a->term_id, 'folder_order', true);
        $order_b = get_term_meta($b->term_id, 'folder_order', true);

        $date_a = get_term_meta($a->term_id, 'folder_created_date', true);
        $date_b = get_term_meta($b->term_id, 'folder_created_date', true);

        // Both have manual order
        if ($order_a !== '' && $order_b !== '') {
            return intval($order_a) - intval($order_b);
        }

        // Only A has manual order
        if ($order_a !== '' && $order_b === '') {
            return -1; // A comes first
        }

        // Only B has manual order
        if ($order_a === '' && $order_b !== '') {
            return 1; // B comes first
        }

        // Neither has manual order, sort by creation date (newest first)
        return intval($date_b) - intval($date_a);
    });

    $total_items = count($all_folders);

    // Calculate pagination
    $offset      = ($args['page'] - 1) * $args['per_page'];
    $total_pages = $args['per_page'] > 0 ? ceil($total_items / $args['per_page']) : 1;

    // Apply pagination
    if ($args['per_page'] > 0) {
        $all_folders = array_slice($all_folders, $offset, $args['per_page']);
    }

    return [
        'folders' => $all_folders,
        'pagination' => [
            'current_page' => $args['page'],
            'per_page'     => $args['per_page'],
            'total_items'  => $total_items,
            'total_pages'  => $total_pages,
            'has_prev'     => $args['page'] > 1,
            'has_next'     => $args['page'] < $total_pages
        ]
    ];
}


// ===== PRO INTEGRATION - BACKWARD COMPATIBILITY =====

/**
 * Get available templates - backward compatibility for PRO plugin
 *
 * The PRO plugin expects this function to exist and to apply the
 * 'fold82sm_available_templates' filter to allow PRO (and other
 * add-ons) to register their templates.
 *
 * @param array $templates Existing templates
 * @return array Templates array (including PRO templates when available)
 */
function fold82sm_get_available_templates( $templates = array() ) {
    // Ensure we always work with an array
    $templates = (array) $templates;

    /**
     * Filter: allow Folderra PRO (and other add-ons) to add templates.
     *
     * The PRO version hooks here with:
     * add_filter( 'fold82sm_available_templates', 'fold82sm_pro_add_templates', 10, 1 );
     */
    return apply_filters( 'fold82sm_available_templates', $templates );
}

/**
 * Initialize PRO integration - backward compatibility
 * The PRO plugin expects this hook to be triggered when the FREE is fully loaded.
 */
add_action( 'plugins_loaded', function () {
    // Hook for PRO plugin to initialize its integration with the FREE version
    do_action( 'fold82sm_pro_loaded' );
}, 5 );

// ===== AUTOMATIC FOLDERS FUNCTIONALITY =====

// Include automatic folders functionality
require_once plugin_dir_path(__FILE__) . 'includes/wpsmartfolder-automatic.php';
// ===== MINI ANALYTICS (FREE) =====
require_once plugin_dir_path(__FILE__) . 'includes/class-fold82sm-mini-analytics.php';
Fold82SM_Mini_Analytics::init();
