<?php
namespace orderflow\Admin;

use orderflow\Core\Base;
use orderflow\Courier\Courier;
use orderflow\Traits\Core;

class Order_List_Columns extends Base {
    use Core;

    public function __construct() {
        if ( ! self::is_license_active()  ) {
            return;
        }
        // Add custom columns
        add_filter('manage_edit-shop_order_columns', [$this, 'add_columns'], 20);
        add_filter('manage_woocommerce_page_wc-orders_columns', [$this, 'add_columns'], 20);
        // Add content to custom columns
        add_action('manage_shop_order_posts_custom_column', [$this, 'render_column_content'], 20, 2);
        add_action('manage_woocommerce_page_wc-orders_custom_column', [$this, 'render_column_content'], 20, 2);

        // Add AJAX handler for BATCH loading courier history
        add_action('wp_ajax_load_courier_history_batch', [$this, 'load_courier_history_batch']);
        add_action('wp_ajax_nopriv_load_courier_history_batch', [$this, 'load_courier_history_batch']);

        // Add AJAX handler for refreshing courier history (Individual refresh is kept)
        add_action('wp_ajax_refresh_courier_history', [$this, 'refresh_courier_history']);
        add_action('wp_ajax_nopriv_refresh_courier_history', [$this, 'refresh_courier_history']);

        // Add JavaScript for AJAX functionality
        add_action('admin_footer', [$this, 'add_courier_history_script']);
    }

    /**
     * Add custom columns to WooCommerce order list
     */
    public function add_columns($columns) {
        $new_columns = [];
        $fraud_checker_enabled = get_option('ads_enable_fraud_checker', false);
        foreach ($columns as $key => $label) {
            $new_columns[$key] = $label;
            if ($key === 'order_number') {
                $new_columns['ads_fb_status'] = __('FB Status', 'woocommerce');
            }
            if ($key === 'order_total') {
                if( $fraud_checker_enabled ) {
                    $new_columns['ads_customer_courier_history'] = __('History', 'woocommerce');
                }
                $new_columns['ads_customer_access'] = __('Access', 'woocommerce');
            }
        }
        return $new_columns;
    }

    /**
     * Render content for custom columns
     */
    public function render_column_content($column, $order_or_post_id) {
        $order = is_a($order_or_post_id, 'WC_Order') ? $order_or_post_id : wc_get_order($order_or_post_id);
        if (!$order) {
            return;
        }

        // FB Status column
        if ($column === 'ads_fb_status') {
            $order_id = $order->get_id();
            
            // Use WooCommerce meta API instead of get_post_meta for better compatibility
            // WooCommerce 3.0+ uses $order->get_meta(), older versions use get_post_meta()
            if (method_exists($order, 'get_meta')) {
                $results = $order->get_meta('ads_purchase_event_results', true);
            } else {
                $results = get_post_meta($order_id, 'ads_purchase_event_results', true);
            }
            
            $sent_count = 1;
            if (is_array($results) && !empty($results)) {
                // Check first result
                $first_result = $results[0];
                if (isset($first_result['event_name']) && $first_result['event_name'] === 'Purchase') {
                    if (isset($first_result['sent_count'])) {
                        $sent_count = $first_result['sent_count'];
                    }
                    echo '<span style="
                        display: inline-block;
                        background-color: #d4edda;
                        color: #155724;
                        padding: 2px 6px;
                        border-radius: 4px;
                        font-size: 11px;
                    ">Purchase * ' . esc_html($sent_count) . '</span>';
                }
            }
        }

        // Customer Access column
        if ($column === 'ads_customer_access') {
            $phone = $this->normalize_phone_number($order->get_billing_phone());
            $email = $order->get_billing_email();
            $ip_address = $order->get_customer_ip_address();
            $phone_data = $this->fetch_customer_record('phone_number', $phone);
            $email_data = $this->fetch_customer_record('email_address', $email);
            $ip_address_data = $this->fetch_customer_record('ip_address', $ip_address);

            if ($phone && get_option('ads_block_phone_numbers') == true ) {
                echo '<span data-type="phone_number" data-value="' . esc_attr($phone) . '" class="ads-customer-access-btn ' . $this->determine_customer_access_class($phone_data) . '">Phone</span>';
            }

            if ($email && get_option('ads_block_email_addresses')  == true  ) {
                echo '<span data-type="email_address" data-value="' . esc_attr($email) . '" class="ads-customer-access-btn ' . $this->determine_customer_access_class($email_data) . '">Email</span>';
            }

            if ($ip_address && get_option('ads_block_ip_addresses')  == true ) {
                echo '<span data-type="ip_address" data-value="' . esc_attr($ip_address) . '" class="ads-customer-access-btn ' . $this->determine_customer_access_class($ip_address_data) . '">IP Address</span>';
            }
        }

        // Courier History column - Placeholder for AJAX content
        $fraud_checker_enabled = get_option('ads_enable_fraud_checker', false);
        if ($fraud_checker_enabled && $column === 'ads_customer_courier_history') {
            $phone = $this->normalize_phone_number($order->get_billing_phone());

            if (!$phone || strlen($phone) != 11) {
                echo '<span>Invalid Phone</span>';
                return;
            }

            // Get courier history from cache or DB (no API calls here)
            // Get courier history statistics (uses cache if available)
            $courier_history = Courier::calculate_courier_history_statistics($phone, true);

            if($courier_history !== null) {
                // If cached data exists, display it immediately
                // Generate HTML response with courier history data
                $html = $this->generate_courier_history_html($phone, $order_or_post_id, $courier_history);
                echo '<div class="courier-history-container loaded" data-phone="' . esc_attr($phone) . '" data-order-id="' . esc_attr($order->get_id()) . '">';
                echo $html;
                echo '</div>';
                return;
            }
            // Display a loading spinner and container for the actual content
            echo '<div class="courier-history-container" data-phone="' . esc_attr($phone) . '" data-order-id="' . esc_attr($order->get_id()) . '">';
            echo '<div class="loading-spinner" style="display: inline-block; width: 16px; height: 16px; border: 2px solid #f3f3f3; border-top: 2px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite;"></div>';
            echo '<span style="margin-left: 8px; font-size: 12px;">Loading...</span>';
            echo '</div>';
        }
    }

    /**
     * AJAX handler for BATCH loading courier history.
     * This replaces individual AJAX calls with a single call for multiple orders.
     */
    public function load_courier_history_batch() {

        check_ajax_referer('load_courier_history_batch_nonce', 'nonce');

        $orders_json = isset($_POST['orders']) ? stripslashes($_POST['orders']) : '[]';
        $orders_data = json_decode($orders_json, true);

        if (empty($orders_data) || !is_array($orders_data)) {
            wp_send_json_error(['message' => 'Invalid batch data']);
        }

        $response_data = [];

        // Loop through the batch of orders
        foreach ($orders_data as $order) {
            $phone    = isset($order['phone']) ? sanitize_text_field($order['phone']) : '';
            $order_id = isset($order['order_id']) ? intval($order['order_id']) : 0;

            if (!$phone || strlen($phone) != 11 || !$order_id) {
                $response_data[] = [
                    'order_id' => $order_id,
                    'success'  => false,
                    'message'  => 'Invalid phone or order ID'
                ];
                continue;
            }

            // Get courier history statistics (uses cache if available)
            $courier_history = Courier::calculate_courier_history_statistics($phone);

            // Generate HTML response with courier history data
            $html = $this->generate_courier_history_html($phone, $order_id, $courier_history);

            $response_data[] = [
                'order_id' => $order_id,
                'success'  => true,
                'html'     => $html
            ];
        }

        // Send a single success response with all history data
        wp_send_json_success(['history_data' => $response_data]);
    }

    /**
     * AJAX handler for refreshing courier history (Kept as is)
     */
    public function refresh_courier_history() {
        check_ajax_referer('refresh_courier_history_nonce', 'nonce');

        $phone = isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '';
        $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;

        if (!$phone || strlen($phone) != 11 || !$order_id) {
            wp_send_json_error(['message' => 'Invalid request parameters']);
        }

        // Force refresh by directly fetching from all courier APIs
        $courier_history = Courier::fetch_courier_history_from_apis($phone);

        if (empty($courier_history)) {
            wp_send_json_error(['message' => 'No valid data received from courier services']);
        }

        // Update the database with fresh data
        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_customers_data';

        // Check if this phone number already exists in database
        $existing_data = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$table_name} WHERE data_type = %s AND data_value = %s",
                'phone_number',
                $phone
            )
        );

        if ($existing_data) {
            // Update existing record with fresh data
            $wpdb->update(
                $table_name,
                [
                    'data_courier_history' => json_encode($courier_history),
                    'data_courier_history_last_update_time' => current_time('mysql'),
                ],
                [
                    'data_type' => 'phone_number',
                    'data_value' => $phone,
                ],
                [
                    '%s',
                    '%s',
                ],
                [
                    '%s',
                    '%s',
                ]
            );
        } else {
            // Insert new record with fresh data
            $wpdb->insert(
                $table_name,
                [
                    'data_type'  => 'phone_number',
                    'data_value' => $phone,
                    'data_courier_history' => json_encode($courier_history),
                    'data_courier_history_last_update_time' => current_time('mysql'),
                ],
                [
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                ]
            );
        }

        // Calculate statistics from the fresh courier history data
        $total_success = isset($courier_history['success_parcel']) ? $courier_history['success_parcel'] : 0;
        $total_cancel = isset($courier_history['cancel_parcel']) ? $courier_history['cancel_parcel'] : 0;
        $total_order = isset($courier_history['total_parcel']) ? $courier_history['total_parcel'] : 0;

        // Calculate percentages safely (avoid division by zero)
        $success_percent = ($total_order > 0) ? ($total_success / $total_order) * 100 : 0;
        $cancel_percent = ($total_order > 0) ? ($total_cancel / $total_order) * 100 : 0;

        $courier_history_percent = [
            'total_order' => $total_order,
            'total_success' => $total_success,
            'total_cancel' => $total_cancel,
            'success_percent' => $success_percent,
            'cancel_percent' => $cancel_percent,
        ];

        // Generate HTML response with updated data
        $response = [
            'success' => true,
            'html' => $this->generate_courier_history_html($phone, $order_id, $courier_history_percent)
        ];

        // Send success response with updated HTML
        wp_send_json_success($response);
    }

    /**
     * Generate HTML for courier history display
     */
    private function generate_courier_history_html($phone, $order_id, $courier_history) {
        $success_percent = $courier_history['success_percent'] ?? 0;
        $cancel_percent  = $courier_history['cancel_percent'] ?? 0;
        $total_success   = $courier_history['total_success'] ?? 0;
        $total_cancel    = $courier_history['total_cancel'] ?? 0;
        $total_order     = $courier_history['total_order'] ?? 0;

        ob_start();
        ?>
        <div class="courier-history-stats" style="margin-bottom: 8px; font-size: 12px;">
            <span class="stat-label" title="Total Orders"><strong>All:</strong> <?php echo esc_html($total_order); ?></span>
            <span class="stat-label success" title="Successful Orders"><strong>Succ:</strong> <?php echo esc_html($total_success); ?></span>
            <span class="stat-label cancel" title="Cancelled Orders"><strong>Canc:</strong> <?php echo esc_html($total_cancel); ?></span>
        </div>
        <div class="courier-progress-container" style="display: flex; align-items: center; width: 100%; max-width: 500px;">
            <div class="progress-wrapper" style="flex: 0 0 80%; margin-right: 8px; position: relative;">
                <div class="progress-bar" style="width: 100%; height: 14px; background: linear-gradient(90deg, #e53e3e, #fc8181); border-radius: 8px; overflow: hidden; box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);">
                    <div class="progress-segment success" style="width: <?php echo esc_attr($success_percent); ?>%; height: 100%; background: linear-gradient(90deg, #28a745, #5cb85c); float: left;"></div>
                    <div class="progress-segment cancel" style="width: <?php echo esc_attr($cancel_percent); ?>%; height: 100%; background: linear-gradient(90deg, #dc3545, #e74c3c); float: left;"></div>
                </div>
                <div class="progress-indicator" style="position: absolute; top: -20px; right: 0; font-size: 10px; color: #666;">
                    <?php echo round($success_percent); ?>%
                </div>
            </div>
            <div class="refresh-wrapper" style="flex: 0 0 20%;">
                <button class="refresh-courier-history" data-phone="<?php echo esc_attr($phone); ?>" data-order-id="<?php echo esc_attr($order_id); ?>" style="width: 32px; height: 32px; border-radius: 50%; background: #f8f9fa; border: 1px solid #dee2e6; color: #6c757d; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s;">
                    <span class="dashicons dashicons-update" style="font-size: 16px; line-height: 1;"></span>
                </button>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Add JavaScript for courier history functionality
     */
    public function add_courier_history_script() {
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                // Batch size to control the number of simultaneous requests
                const BATCH_SIZE = 15; // Set a controlled batch size (e.g., 15-20)
                const DELAY_MS = 100; // Small delay between batches

                /**
                 * Loads courier history for all visible rows in batches.
                 */
                function loadAllCourierHistoryBatch() {
                    var $containers = $('.courier-history-container:not(.loaded):not(.loading)');

                    if ($containers.length === 0) {
                        return;
                    }

                    var batch_data = [];

                    // Select a batch of containers to process
                    $containers.slice(0, BATCH_SIZE).each(function() {
                        var $container = $(this);
                        var phone = $container.data('phone');
                        var order_id = $container.data('order-id');

                        if (phone && order_id) {
                            batch_data.push({
                                phone: phone,
                                order_id: order_id
                            });
                            // Set loading state
                            $container.addClass('loading');
                        }
                    });

                    if (batch_data.length === 0) {
                        return;
                    }

                    // Single AJAX call for the entire batch
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'load_courier_history_batch',
                            nonce: '<?php echo wp_create_nonce('load_courier_history_batch_nonce'); ?>',
                            orders: JSON.stringify(batch_data)
                        },
                        success: function(response) {
                            if (response.success && response.data.history_data) {
                                $.each(response.data.history_data, function(index, item) {
                                    var $container = $('.courier-history-container[data-order-id="' + item.order_id + '"]');

                                    if (item.success) {
                                        $container.html(item.html);
                                        $container.addClass('loaded');
                                    } else {
                                        $container.html('<span class="error">Data error.</span>');
                                    }
                                    $container.removeClass('loading');
                                });

                                // Recursively call the function for the next batch after a small delay
                                if ($('.courier-history-container:not(.loaded)').length > 0) {
                                    setTimeout(loadAllCourierHistoryBatch, DELAY_MS);
                                }

                            } else {
                                // Handle batch failure
                                $containers.slice(0, BATCH_SIZE).each(function() {
                                    $(this).html('<span class="error">Server error.</span>').removeClass('loading');
                                });
                            }
                        },
                        error: function() {
                            // Handle network error
                            $containers.slice(0, BATCH_SIZE).each(function() {
                                $(this).html('<span class="error">Network error.</span>').removeClass('loading');
                            });
                        }
                    });
                }

                // Start batch loading after page load
                setTimeout(loadAllCourierHistoryBatch, 500);

                // Load courier history for new rows when pagination or filtering is used
                $(document).ajaxComplete(function(event, xhr, settings) {
                    if (settings.data && settings.data.indexOf('action=load_courier_history_batch') === -1 && settings.data.indexOf('action=refresh_courier_history') === -1) {
                        // Re-initialize loading state for new, unloaded rows
                        $('.courier-history-container:not(.loaded)').html(
                            '<div class="loading-spinner" style="display: inline-block; width: 16px; height: 16px; border: 2px solid #f3f3f3; border-top: 2px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite;"></div>' +
                            '<span style="margin-left: 8px; font-size: 12px;">Loading...</span>'
                        );
                        setTimeout(loadAllCourierHistoryBatch, 500);
                    }
                });

                // Handle refresh button click
                $(document).on('click','.refresh-courier-history', function(e) {
                    e.preventDefault();

                    var $button = $(this);
                    var $container = $button.closest('.courier-history-container'); // Use container class
                    var phone = $button.data('phone');
                    var order_id = $button.data('order-id');

                    // Show loading state
                    $button.prop('disabled', true);
                    $button.css('background', '#e9ecef');
                    $button.find('.dashicons').addClass('spinning');
                    $container.addClass('loading');

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'refresh_courier_history',
                            nonce: '<?php echo wp_create_nonce('refresh_courier_history_nonce'); ?>',
                            phone: phone,
                            order_id: order_id
                        },
                        success: function(response) {
                            console.log('refresh_courier_history', response);
                            
                            if (response.success) {
                                $container.html(response.data.html);
                                $container.addClass('loaded');
                            } else {
                                alert('Error: ' + response.data.message);
                            }
                        },
                        error: function() {
                            alert('An error occurred while refreshing courier history.');
                        },
                        complete: function() {
                            $button.prop('disabled', false);
                            $button.css('background', '#f8f9fa');
                            $button.find('.dashicons').removeClass('spinning');
                            $container.removeClass('loading');
                        }
                    });
                });
            });
        </script>
        <style>
            .dashicons.spinning {
                animation: rotation 2s infinite linear;
            }
            @keyframes rotation {
                from { transform: rotate(0deg); }
                to { transform: rotate(359deg); }
            }

            .stat-label {
                cursor: help;
                position: relative;
            }

            .stat-label.success {
                color: #28a745;
            }

            .stat-label.cancel {
                color: #dc3545;
            }

            .refresh-courier-history:hover {
                background: #e9ecef !important;
                transform: scale(1.05);
            }

            .progress-segment.success {
                border-right: 1px solid rgba(255,255,255,0.3);
            }

            .progress-indicator {
                font-weight: 600;
            }

            .loading-spinner {
                display: inline-block;
                width: 16px;
                height: 16px;
                border: 2px solid #f3f3f3;
                border-top: 2px solid #3498db;
                border-radius: 50%;
                animation: spin 1s linear infinite;
            }

            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
        <?php
    }
}