<?php
/**
 * Archived Order Status Filter
 *
 * Adds archived orders count to WooCommerce order list page status filters
 *
 * @package ArchiveMaster
 * @since 1.8.3
 */

namespace ARCHM\Admin;

if ( ! defined('ABSPATH') ) {
    // phpcs:ignore Universal.PHP.RequireExitDieParentheses.Missing
    exit;
}

use ARCHM\Features\Sqlite;
use ARCHM\Helpers\DBHelper;
use Automattic\WooCommerce\Utilities\OrderUtil;

class ArchivedOrderStatusFilter {
    use DBHelper;

    /**
     * Initialize the class
     *
     * @since 1.8.3
     */
    public function __construct() {
        // Hook into WooCommerce order status views (Legacy - works when HPOS is disabled)
        // This filter works on edit.php?post_type=shop_order page
        add_filter('views_edit-shop_order', [ $this, 'add_archived_status_view' ], 20);
        // For HPOS (High-Performance Order Storage) - use multiple approaches
        // Only runs when HPOS is enabled (admin.php?page=wc-orders)
        if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
            // Try the views filter
            add_filter('woocommerce_order_list_table_views', [ $this, 'add_archived_status_view_hpos' ], 20);

            // Also inject via JavaScript for HPOS React components
            add_action('admin_footer', [ $this, 'inject_archived_status_via_js' ]);
        }

        // Clear cache when orders are archived/unarchived
        add_action('archm_order_archived', [ $this, 'clear_count_cache' ]);
        add_action('archm_order_unarchived', [ $this, 'clear_count_cache' ]);
        add_action('archm_orders_bulk_archived', [ $this, 'clear_count_cache' ]);
        add_action('archm_orders_bulk_unarchived', [ $this, 'clear_count_cache' ]);
    }

    /**
     * Clear the archived orders count cache
     *
     * @since 1.8.3
     */
    public function clear_count_cache() {
        delete_transient('archm_total_archived_orders_count');
    }

    /**
     * Add archived status view to order list (Legacy - when HPOS is disabled)
     * Works on edit.php?post_type=shop_order page
     *
     * @param array $views Existing views
     * @return array Modified views
     * @since 1.8.3
     */
    public function add_archived_status_view( $views ) {
        // Only run on shop_order post type pages (legacy system)
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( ! isset($_GET['post_type']) || 'shop_order' !== $_GET['post_type'] ) {
            return $views;
        }

        $archived_count = $this->get_total_archived_orders_count();

        if ( $archived_count > 0 ) {
            $class = '';
            $archived_url = admin_url('admin.php?page=master-archives#/archived-order');

            // Check if we're currently viewing archived orders
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if ( isset($_GET['page']) && 'master-archives' === $_GET['page'] ) {
                $class = 'current';
            }
            // Insert archived view after other status views
            // WordPress views format: 'key' => '<a href="...">Label <span class="count">(count)</span></a>'
            $views['archived'] = sprintf(
                '<a href="%s" class="%s">%s <span class="count">(%s)</span></a>',
                esc_url($archived_url),
                esc_attr($class),
                esc_html__('Archived Orders', 'archive-master'),
                number_format_i18n($archived_count)
            );
        }

        return $views;
    }

    /**
     * Add archived status view to order list (HPOS)
     *
     * @param array $views Existing views
     * @return array Modified views
     * @since 1.8.3
     */
    public function add_archived_status_view_hpos( $views ) {
        // error_log('HPOS filter called - views: ' . print_r($views, true));
        $archived_count = $this->get_total_archived_orders_count();
        // error_log('HPOS archived_count: ' . $archived_count);

        if ( $archived_count > 0 ) {
            $archived_url = admin_url('admin.php?page=master-archives#/archived-order');

            $views['archived'] = [
                'url'   => esc_url($archived_url),
                'name'  => esc_html__('Archived', 'archive-master'),
                'count' => $archived_count,
            ];
        }
        return $views;
    }

    /**
     * Inject archived status via JavaScript for HPOS React components
     *
     * @since 1.8.3
     */
    public function inject_archived_status_via_js() {
        // Only on wc-orders page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( ! isset($_GET['page']) || 'wc-orders' !== $_GET['page'] ) {
            return;
        }

        $archived_count = $this->get_total_archived_orders_count();

        if ( $archived_count <= 0 ) {
            return;
        }

        $archived_url = admin_url('admin.php?page=master-archives#/archived-order');
        $formatted_count = number_format_i18n($archived_count);
        ?>
        <script type="text/javascript">
        (function($) {
            var attempts = 0;
            var maxAttempts = 10;
            
            function addArchivedStatusFilter() {
                attempts++;
                
                // Check if already added
                if ($('.archm-archived-status-filter').length > 0) {
                    return;
                }
                
                // Try multiple strategies to find status filters
                var statusFilters = null;
                
                // Strategy 1: Look for common WooCommerce status filter containers
                var containers = $('.woocommerce-orders-table__status-filters, .subsubsub, [data-testid="order-status-filters"], .woocommerce-orders-table__filters, nav.woocommerce-orders-table__filters');
                if (containers.length > 0) {
                    statusFilters = containers.first();
                }
                
                // Strategy 2: Find by text content (All, Processing, etc.)
                if (!statusFilters || statusFilters.length === 0) {
                    var allLink = $('a:contains("All"), button:contains("All")').first();
                    if (allLink.length > 0) {
                        statusFilters = allLink.closest('nav, div, ul, .woocommerce-orders-table__filters').first();
                    }
                }
                
                // Strategy 3: Look for elements containing status counts
                if (!statusFilters || statusFilters.length === 0) {
                    var countElements = $('span.count, .count');
                    if (countElements.length > 0) {
                        statusFilters = countElements.first().closest('nav, div, ul, section').first();
                    }
                }
                
                // Strategy 4: Look near the "Bulk actions" dropdown
                if (!statusFilters || statusFilters.length === 0) {
                    var bulkActions = $('select[name="action"], select[name="bulk_action"]').first();
                    if (bulkActions.length > 0) {
                        statusFilters = bulkActions.closest('.tablenav, .woocommerce-orders-table__filters, div').find('nav, ul, .subsubsub').first();
                    }
                }
                
                if (!statusFilters || statusFilters.length === 0) {
                    if (attempts < maxAttempts) {
                        setTimeout(addArchivedStatusFilter, 500);
                    }
                    return;
                }
                
                var filtersContainer = statusFilters.first();
                
                // Find existing status list items (li elements)
                var existingListItems = filtersContainer.find('li');
                
                // Create a new list item for archived status
                var archivedListItem = $('<li>')
                    .addClass('archm-archived-status-li');
                
                // Create archived filter link matching WooCommerce style
                var archivedLink = $('<a>')
                    .addClass('archm-archived-status-filter archived-order')
                    .attr('href', '<?php echo esc_js($archived_url); ?>')
                    .html('<?php echo esc_js(__('Archived Orders', 'archive-master')); ?> <span class="count">(<?php echo esc_js($formatted_count); ?>)</span>');
                
                // Apply WooCommerce standard status filter link styles
                // WooCommerce uses color #2271b1 for status filter links
                archivedLink.css({
                    'text-decoration': 'none',
                    'color': '#2271b1',
                    'display': 'inline-block',
                    'line-height': '2',
                    'padding': '.2em'
                });
                
                // Match hover and other states from existing links if available
                if (existingListItems.length > 0) {
                    var firstListItem = existingListItems.first();
                    var firstLink = firstListItem.find('a').first();
                    
                    // Copy any additional styles or classes that might be needed
                    if (firstLink.length > 0) {
                        // Ensure we use WooCommerce's standard color
                        archivedLink.css('color', '#2271b1');
                    }
                    
                    // Copy any classes from existing list items if needed
                    var existingClasses = firstListItem.attr('class');
                    if (existingClasses) {
                        // Keep only relevant classes, remove status-specific ones
                        var classesToKeep = existingClasses.split(' ').filter(function(cls) {
                            return cls && !cls.match(/^wc-|^status-|^order-/);
                        });
                        if (classesToKeep.length > 0) {
                            archivedListItem.addClass(classesToKeep.join(' '));
                        }
                    }
                    
                    // Append link to list item
                    archivedListItem.append(archivedLink);
                    
                    // Create separator before archived status (WooCommerce uses " | " between status filters)
                    // Match WooCommerce's separator styling - it's typically a text node or span with specific styling
                    var separator = $('<span>').text(' | ').css({
                        'margin': '0 0.5em',
                        'color': '#999',
                        'display': 'inline-block'
                    }).addClass('archm-status-separator');
                    
                    // Insert separator BEFORE the archived list item (after the last existing list item)
                    var lastListItem = existingListItems.last();
                    lastListItem.after(separator);
                    separator.after(archivedListItem);
                } else {
                    // Fallback: if no list items found, try to find the container and create structure
                    archivedListItem.append(archivedLink);
                    
                    // Check if container is a ul, if not, wrap in ul
                    if (!filtersContainer.is('ul')) {
                        var ulContainer = filtersContainer.find('ul').first();
                        if (ulContainer.length > 0) {
                            ulContainer.append(archivedListItem);
                        } else {
                            // Create ul if it doesn't exist
                            var newUl = $('<ul>').addClass('subsubsub');
                            newUl.append(archivedListItem);
                            filtersContainer.append(newUl);
                        }
                    } else {
                        filtersContainer.append(archivedListItem);
                    }
                }
            }
            
            // Run on page load
            $(document).ready(function() {
                addArchivedStatusFilter();
            });
            
            // Also try after delays (React components load asynchronously)
            setTimeout(addArchivedStatusFilter, 1000);
            setTimeout(addArchivedStatusFilter, 2000);
            setTimeout(addArchivedStatusFilter, 3000);
            setTimeout(addArchivedStatusFilter, 5000);
        })(jQuery);
        </script>
        <?php
    }

    /**
     * Get total archived orders count from the appropriate storage
     * Uses transient cache to improve performance
     *
     * @return int Total archived orders count
     * @since 1.8.3
     */
    private function get_total_archived_orders_count() {
        // Use transient cache (5 minutes) to avoid querying on every page load
        $cache_key = 'archm_total_archived_orders_count';
        $cached_count = get_transient($cache_key);

        if ( false !== $cached_count ) {
            return (int) $cached_count;
        }

        try {
            global $wpdb;
            $selected_database = get_option('archm_selected_database', 'sqlite');
            $table_name = $wpdb->prefix . 'archived_orders';

            $count = 0;

            // SQLite or Google Drive storage
            if ( 'sqlite' === $selected_database || 'google_drive' === $selected_database ) {
                $sqlite = Sqlite::get_instance();
                if ( $sqlite->is_connected() ) {
                    $count = $sqlite->count_total_archived_order();
                }
            } elseif ( 'rds' === $selected_database || 'custom_mysql' === $selected_database ) {
                // RDS or Custom MySQL storage
                // Initialize database settings
                $this->set_remote_db_settings();

                if ( $this->is_bd_connected() ) {
                    // Set remote db instance
                    $this->set_db_instance();

                    if ( $this->remote_db && ! $this->remote_db->last_error ) {
                        $count = $this->remote_db->get_var(
                            $this->remote_db->prepare('SELECT COUNT(*) FROM %i WHERE 1', $table_name)
                        );
                        $count = $count ? (int) $count : 0;
                    }
                }
            }

            // Cache the result for 5 minutes
            set_transient($cache_key, $count, 5 * MINUTE_IN_SECONDS);

            return $count;
        } catch ( \Exception $e ) {
            // Log error but don't break the page
            // Error logging disabled for performance
            return 0;
        }
    }
}
