<?php
namespace PrimeLink\Modules\Imports\Service;

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

/**
 * Intelligent Anomaly Detection Service
 * Detects anomalies in import data to protect business from bad data
 */
class AnomalyDetectionService {
    
    /**
     * Check if anomaly detection is enabled for import
     */
    public static function is_enabled( $import_id ) {
        $settings = get_option( 'mt_primelink_settings', array() );
        $global_enabled = ! empty( $settings['anomaly_detection_enabled'] );
        
        // Check import-specific setting
        $import_settings = get_post_meta( $import_id, '_mt_primelink_anomaly_detection', true );
        if ( $import_settings !== '' ) {
            return ! empty( $import_settings['enabled'] );
        }
        
        return $global_enabled;
    }
    
    /**
     * Analyze item for anomalies
     * 
     * @param array $item_data Current item data
     * @param array $previous_data Previous version of item (if exists)
     * @param string $import_type Import type (product, order, customer, coupon)
     * @param int $import_id Import ID
     * @return array Array of detected anomalies
     */
    public static function analyze_item( $item_data, $previous_data = null, $import_type = 'product', $import_id = 0 ) {
        if ( ! self::is_enabled( $import_id ) ) {
            return array();
        }
        
        $anomalies = array();
        $config = self::get_config( $import_id );
        
        if ( $import_type === 'product' ) {
            $anomalies = array_merge( $anomalies, self::detect_price_anomalies( $item_data, $previous_data, $config ) );
            $anomalies = array_merge( $anomalies, self::detect_content_anomalies( $item_data, $previous_data, $config ) );
            $anomalies = array_merge( $anomalies, self::detect_stock_anomalies( $item_data, $previous_data, $config ) );
            $anomalies = array_merge( $anomalies, self::detect_data_quality_anomalies( $item_data, $config ) );
        } elseif ( $import_type === 'order' ) {
            $anomalies = array_merge( $anomalies, self::detect_order_anomalies( $item_data, $previous_data, $config ) );
        } elseif ( $import_type === 'customer' ) {
            $anomalies = array_merge( $anomalies, self::detect_customer_anomalies( $item_data, $previous_data, $config ) );
        }
        
        return $anomalies;
    }
    
    /**
     * Detect price anomalies
     */
    private static function detect_price_anomalies( $item_data, $previous_data, $config ) {
        $anomalies = array();
        
        // Get current price - handle nested structure from ImportRunner
        $current_price = isset( $item_data['regular_price'] ) 
            ? floatval( $item_data['regular_price'] ) 
            : ( isset( $item_data['product']['regular_price'] ) ? floatval( $item_data['product']['regular_price'] ) : 0 );
        $current_sale_price = isset( $item_data['sale_price'] ) 
            ? floatval( $item_data['sale_price'] ) 
            : ( isset( $item_data['product']['sale_price'] ) ? floatval( $item_data['product']['sale_price'] ) : 0 );
        $active_price = $current_sale_price > 0 ? $current_sale_price : $current_price;
        
        // Get SKU - handle nested structure from ImportRunner
        $sku = $item_data['sku'] ?? $item_data['product']['sku'] ?? '';
        
        // Check if price is zero or negative (only for products with SKU - new products might not have price yet)
        // Skip this check if previous_data exists but has no price (it's a new product being updated)
        // CRITICAL: A product is considered NEW if:
        // 1. previous_data is null (no existing product found)
        // 2. OR previous_data exists but has NO valid price (empty string, null, or 0)
        $is_new_product = false;
        if ( $previous_data === null ) {
            $is_new_product = true;
        } elseif ( is_array( $previous_data ) ) {
            // Check if previous data has a valid price
            $prev_reg = $previous_data['regular_price'] ?? '';
            $prev_sale = $previous_data['sale_price'] ?? '';
            
            // Normalize to float (empty string/null becomes 0)
            $prev_reg_float = ( $prev_reg === '' || $prev_reg === null ) ? 0 : floatval( $prev_reg );
            $prev_sale_float = ( $prev_sale === '' || $prev_sale === null ) ? 0 : floatval( $prev_sale );
            
            // If both prices are 0 or empty, treat as new product (no price was ever set)
            if ( $prev_reg_float <= 0 && $prev_sale_float <= 0 ) {
                $is_new_product = true;
            }
        }
        
        if ( $active_price <= 0 && ! empty( $sku ) && ! $is_new_product ) {
            $anomalies[] = array(
                'type' => 'price_zero',
                'level' => 'critical',
                'field' => 'price',
                'message' => sprintf( 'Price is zero or negative: %s (SKU: %s)', $active_price, $sku ?? 'N/A' ),
                'value' => $active_price,
                'previous_value' => $previous_data['regular_price'] ?? $previous_data['sale_price'] ?? null,
            );
        }
        
        // Compare with previous price if available
        // IMPORTANT: Only compare if we have a valid previous price (product exists and has a price)
        // For new products, previous_data might be null or have price = 0, which would cause false positives
        // Also skip comparison if previous price is too small (< 0.01) to avoid false positives from rounding errors
        if ( $previous_data ) {
            // CRITICAL: Normalize previous prices - handle empty strings, null, and formatted values
            // WooCommerce may return empty string '' or null, which floatval() converts to 0
            $prev_reg = $previous_data['regular_price'] ?? '';
            $prev_sale = $previous_data['sale_price'] ?? '';
            
            // Convert to float, but treat empty strings and null as 0 (no price set)
            $previous_price = ( $prev_reg === '' || $prev_reg === null ) ? 0 : floatval( $prev_reg );
            $previous_sale_price = ( $prev_sale === '' || $prev_sale === null ) ? 0 : floatval( $prev_sale );
            
            // Determine active previous price (sale price takes precedence if > 0)
            $previous_active_price = $previous_sale_price > 0 ? $previous_sale_price : $previous_price;
            
            // CRITICAL: Only compare prices if BOTH previous and current prices are valid (> 0.01)
            // This prevents false positives for:
            // - New products (previous_price = 0 or empty)
            // - Products with no previous price set (empty string from WooCommerce)
            // - Products with very small prices that might cause calculation errors
            // - Products where previous price was never set (WooCommerce returns empty string)
            if ( $previous_active_price >= 0.01 && $active_price >= 0.01 ) {
                // CRITICAL: Check if prices are essentially the same (within 0.01 difference)
                // This prevents false positives from rounding errors or minor formatting differences
                // Example: 100.00 vs 100.01 should not trigger an anomaly
                $price_difference = abs( $active_price - $previous_active_price );
                if ( $price_difference < 0.01 ) {
                    // Prices are essentially identical (within 1 cent) - skip all anomaly checks
                    // This prevents false positives from rounding errors
                } else {
                    // Avoid division by zero and ensure we have valid prices
                    $price_change_percent = ( ( $active_price - $previous_active_price ) / $previous_active_price ) * 100;
                    
                    // Check for significant price drop (feed price much lower than existing)
                    // Example: existing = 80, new = 20 → 75% drop → CRITICAL
                    // BUT: Skip this check if current price is 0 (already handled above)
                    $drop_threshold = $config['price_drop_threshold'] ?? 50; // Default 50%
                    if ( $price_change_percent < -$drop_threshold ) {
                    $anomalies[] = array(
                        'type' => 'price_drop',
                        'level' => 'critical',
                        'field' => 'price',
                        'message' => sprintf( 
                            'Significant price drop detected: %.2f%% decrease (from %s to %s). Feed price is much lower than existing.',
                            abs( $price_change_percent ),
                            $previous_active_price,
                            $active_price
                        ),
                        'value' => $active_price,
                        'previous_value' => $previous_active_price,
                        'change_percent' => $price_change_percent,
                    );
                }
                
                // Check for significant price increase (feed price much higher than existing)
                // Example: existing = 20, new = 80 → 300% increase → CRITICAL
                $increase_threshold = $config['price_increase_threshold'] ?? 200; // Default 200% (3x)
                if ( $price_change_percent > $increase_threshold ) {
                    $anomalies[] = array(
                        'type' => 'price_increase',
                        'level' => 'critical', // Changed from 'warning' to 'critical' - both directions are critical
                        'field' => 'price',
                        'message' => sprintf( 
                            'Significant price increase detected: %.2f%% increase (from %s to %s). Feed price is much higher than existing.',
                            $price_change_percent,
                            $previous_active_price,
                            $active_price
                        ),
                        'value' => $active_price,
                        'previous_value' => $previous_active_price,
                        'change_percent' => $price_change_percent,
                    );
                    }
                    
                    // Additional check: absolute value difference might also be suspicious
                    // Example: existing = 1000, new = 100 → only 90% drop, but 900 difference is huge
                    $absolute_difference = abs( $active_price - $previous_active_price );
                    $max_absolute_change = $config['max_absolute_price_change'] ?? 0; // 0 = disabled
                    if ( $max_absolute_change > 0 && $absolute_difference > $max_absolute_change ) {
                        // Check if this is already covered by percentage check
                        $already_detected = false;
                        foreach ( $anomalies as $anomaly ) {
                            if ( in_array( $anomaly['type'], array( 'price_drop', 'price_increase' ) ) ) {
                                $already_detected = true;
                                break;
                            }
                        }
                        
                        if ( ! $already_detected ) {
                            $anomalies[] = array(
                                'type' => 'price_absolute_change',
                                'level' => 'warning',
                                'field' => 'price',
                                'message' => sprintf( 
                                    'Large absolute price difference: %s change (from %s to %s). Exceeds maximum allowed change of %s.',
                                    $absolute_difference > 0 ? '+' . $absolute_difference : $absolute_difference,
                                    $previous_active_price,
                                    $active_price,
                                    $max_absolute_change
                                ),
                                'value' => $active_price,
                                'previous_value' => $previous_active_price,
                                'absolute_difference' => $absolute_difference,
                            );
                        }
                    }
                }
            }
        }
        
        // Check against historical average (if available)
        // Skip this check for new products (when previous_data is null or has no price)
        // This prevents false positives when importing new products
        // SKU already extracted above, reuse it
        if ( ! empty( $sku ) && ! $is_new_product ) {
            $historical_avg = self::get_historical_price_average( $sku );
            // Only check deviation if we have a valid historical average (> 0.01) and current price is valid
            if ( $historical_avg >= 0.01 && $active_price >= 0.01 ) {
                $deviation = abs( ( $active_price - $historical_avg ) / $historical_avg ) * 100;
                $max_deviation = $config['price_deviation_threshold'] ?? 50; // Default 50% deviation
                
                if ( $deviation > $max_deviation ) {
                    $anomalies[] = array(
                        'type' => 'price_deviation',
                        'level' => 'warning',
                        'field' => 'price',
                        'message' => sprintf( 
                            'Price deviates %.2f%% from historical average (%s vs %s avg)',
                            $deviation,
                            $active_price,
                            $historical_avg
                        ),
                        'value' => $active_price,
                        'historical_average' => $historical_avg,
                        'deviation_percent' => $deviation,
                    );
                }
            }
        }
        
        return $anomalies;
    }
    
    /**
     * Detect content anomalies
     */
    private static function detect_content_anomalies( $item_data, $previous_data, $config ) {
        $anomalies = array();
        
        // CRITICAL: Detect if this is a new product
        // A product is considered NEW if:
        // 1. previous_data is null (no existing product found by ImportRunner)
        // 2. OR previous_data exists but has NO meaningful content to compare (empty description)
        // For new products, we MUST NOT compare content changes - there's nothing to compare with
        $is_new_product = false;
        if ( $previous_data === null ) {
            $is_new_product = true;
        } elseif ( is_array( $previous_data ) ) {
            // Check if previous data has meaningful content to compare
            $prev_desc = trim( $previous_data['post_content'] ?? $previous_data['description'] ?? '' );
            // If previous description is empty, there's nothing to compare with = treat as new product
            if ( empty( $prev_desc ) ) {
                $is_new_product = true;
            }
        }
        
        // Handle nested structure from ImportRunner (mapped data is in buckets)
        // Check both flat structure and nested structure for compatibility
        $current_description = $item_data['post_content'] 
            ?? $item_data['post']['post_content'] 
            ?? $item_data['description'] 
            ?? '';
        $current_excerpt = $item_data['post_excerpt'] 
            ?? $item_data['post']['post_excerpt'] 
            ?? $item_data['short_description'] 
            ?? '';
        $current_title = $item_data['post_title'] 
            ?? $item_data['post']['post_title'] 
            ?? $item_data['name'] 
            ?? '';
        
        // Trim whitespace to avoid false positives from spaces-only titles
        $current_title = trim( $current_title );
        
        // Check for empty required fields (skip for new products if title is being set for first time)
        if ( empty( $current_title ) && ! $is_new_product ) {
            $anomalies[] = array(
                'type' => 'missing_title',
                'level' => 'critical',
                'field' => 'title',
                'message' => 'Product title is empty',
                'value' => '',
            );
        }
        
        // Check for suspicious content in description
        $suspicious_patterns = $config['suspicious_patterns'] ?? array(
            'spam_keywords' => array( 'viagra', 'casino', 'lottery', 'winner' ),
            'suspicious_domains' => array( '.tk', '.ml', '.ga' ),
            'script_patterns' => array( '<script', 'javascript:', 'onerror=', 'onclick=' ),
        );
        
        $content_to_check = $current_description . ' ' . $current_excerpt;
        foreach ( $suspicious_patterns['spam_keywords'] as $keyword ) {
            if ( stripos( $content_to_check, $keyword ) !== false ) {
                $anomalies[] = array(
                    'type' => 'suspicious_content',
                    'level' => 'critical',
                    'field' => 'description',
                    'message' => sprintf( 'Suspicious keyword detected: "%s"', $keyword ),
                    'value' => substr( $content_to_check, 0, 200 ),
                );
            }
        }
        
        // Check for script injection attempts
        foreach ( $suspicious_patterns['script_patterns'] as $pattern ) {
            if ( stripos( $content_to_check, $pattern ) !== false ) {
                $anomalies[] = array(
                    'type' => 'script_injection',
                    'level' => 'critical',
                    'field' => 'description',
                    'message' => sprintf( 'Potential script injection detected: "%s"', $pattern ),
                    'value' => substr( $content_to_check, 0, 200 ),
                );
            }
        }
        
        // Compare with previous content if available
        // CRITICAL: Skip this check completely for new products (when previous_data === null)
        // For new products, there's nothing to compare with, so any comparison would be a false positive
        // We ONLY compare if previous_data exists (meaning a product was found, so it's an UPDATE)
        if ( $is_new_product ) {
            // This is a new product - skip all content comparison
            // Do nothing, return early from content comparison
        } elseif ( $previous_data ) {
            $previous_description = trim( $previous_data['post_content'] ?? $previous_data['description'] ?? '' );
            $current_description_trimmed = trim( $current_description );
            
            // Only compare if we have BOTH previous and current descriptions (both non-empty after trim)
            // This ensures we only compare meaningful content changes
            if ( ! empty( $previous_description ) && ! empty( $current_description_trimmed ) ) {
                $similarity = self::calculate_text_similarity( $previous_description, $current_description_trimmed );
                $min_similarity = $config['content_change_threshold'] ?? 0.3; // Default 0.3 (30% similarity)
                
                // Backwards compatibility: admin UI stores content_change_threshold as percentage (0–100)
                // while similarity is 0.0–1.0. If a percentage slipped through (e.g. 30), normalize it.
                if ( $min_similarity > 1 ) {
                    $min_similarity = $min_similarity / 100;
                }
                
                // Clamp to valid range just in case
                if ( $min_similarity < 0 ) {
                    $min_similarity = 0;
                } elseif ( $min_similarity > 1 ) {
                    $min_similarity = 1;
                }
                
                // Only flag as anomaly if similarity is below threshold
                // Note: similarity is returned as decimal (0.0 to 1.0), so 0.3 = 30%
                // Similarity of 1.0 = 100% = identical (should NOT be flagged)
                // Similarity of 0.0 = 0% = completely different (SHOULD be flagged if < 0.3)
                if ( $similarity < $min_similarity ) {
                    $anomalies[] = array(
                        'type' => 'content_change',
                        'level' => 'warning',
                        'field' => 'description',
                        'message' => sprintf( 
                            'Description changed significantly (%.1f%% similarity)',
                            100 * $similarity
                        ),
                        'value' => substr( $current_description, 0, 200 ),
                        'previous_value' => substr( $previous_description, 0, 200 ),
                        'similarity' => $similarity,
                    );
                }
            }
        }
        // If $is_new_product is true (previous_data === null), we completely skip content comparison (no anomalies for new products)
        
        return $anomalies;
    }
    
    /**
     * Detect stock anomalies
     */
    private static function detect_stock_anomalies( $item_data, $previous_data, $config ) {
        $anomalies = array();
        
        $current_stock = isset( $item_data['stock_quantity'] ) ? intval( $item_data['stock_quantity'] ) : null;
        $current_stock_status = $item_data['stock_status'] ?? '';
        
        // Check for suspiciously high stock
        $max_stock_threshold = $config['max_stock_threshold'] ?? 10000;
        if ( $current_stock !== null && $current_stock > $max_stock_threshold ) {
            $anomalies[] = array(
                'type' => 'high_stock',
                'level' => 'warning',
                'field' => 'stock',
                'message' => sprintf( 'Stock quantity is unusually high: %d', $current_stock ),
                'value' => $current_stock,
            );
        }
        
        // Compare with previous stock
        if ( $previous_data ) {
            $previous_stock = isset( $previous_data['stock_quantity'] ) ? intval( $previous_data['stock_quantity'] ) : null;
            
            if ( $previous_stock !== null && $current_stock !== null ) {
                // Check for sudden stock drop to zero
                if ( $previous_stock > 0 && $current_stock === 0 && $current_stock_status !== 'outofstock' ) {
                    $anomalies[] = array(
                        'type' => 'stock_zero',
                        'level' => 'warning',
                        'field' => 'stock',
                        'message' => 'Stock suddenly dropped to zero (was ' . $previous_stock . ')',
                        'value' => $current_stock,
                        'previous_value' => $previous_stock,
                    );
                }
                
                // Check for significant stock change
                if ( $previous_stock > 0 ) {
                    $stock_change_percent = abs( ( ( $current_stock - $previous_stock ) / $previous_stock ) * 100 );
                    $stock_change_threshold = $config['stock_change_threshold'] ?? 90; // Default 90%
                    
                    if ( $stock_change_percent > $stock_change_threshold ) {
                        $anomalies[] = array(
                            'type' => 'stock_change',
                            'level' => 'info',
                            'field' => 'stock',
                            'message' => sprintf( 
                                'Significant stock change: %.1f%% (from %d to %d)',
                                $stock_change_percent,
                                $previous_stock,
                                $current_stock
                            ),
                            'value' => $current_stock,
                            'previous_value' => $previous_stock,
                            'change_percent' => $stock_change_percent,
                        );
                    }
                }
            }
        }
        
        return $anomalies;
    }
    
    /**
     * Detect data quality anomalies
     */
    private static function detect_data_quality_anomalies( $item_data, $config ) {
        $anomalies = array();
        
        // Check for missing SKU (if required)
        // CRITICAL: Handle nested structure from ImportRunner (SKU can be in product['sku'] or directly in item_data['sku'])
        $sku = $item_data['sku'] 
            ?? $item_data['product']['sku'] 
            ?? '';
        
        if ( empty( $sku ) && ( $config['require_sku'] ?? true ) ) {
            $anomalies[] = array(
                'type' => 'missing_sku',
                'level' => 'warning',
                'field' => 'sku',
                'message' => 'SKU is missing',
                'value' => '',
            );
        }
        
        // Validate URLs if present
        if ( ! empty( $item_data['external_url'] ) ) {
            if ( ! filter_var( $item_data['external_url'], FILTER_VALIDATE_URL ) ) {
                $anomalies[] = array(
                    'type' => 'invalid_url',
                    'level' => 'warning',
                    'field' => 'external_url',
                    'message' => 'Invalid URL format',
                    'value' => $item_data['external_url'],
                );
            }
        }
        
        return $anomalies;
    }
    
    /**
     * Detect order anomalies
     */
    private static function detect_order_anomalies( $item_data, $previous_data, $config ) {
        $anomalies = array();
        
        // Check for zero or negative order total
        $total = floatval( $item_data['total'] ?? $item_data['order_total'] ?? 0 );
        if ( $total <= 0 ) {
            $anomalies[] = array(
                'type' => 'zero_total',
                'level' => 'critical',
                'field' => 'total',
                'message' => 'Order total is zero or negative',
                'value' => $total,
            );
        }
        
        return $anomalies;
    }
    
    /**
     * Detect customer anomalies
     */
    private static function detect_customer_anomalies( $item_data, $previous_data, $config ) {
        $anomalies = array();
        
        // Validate email
        $email = $item_data['email'] ?? $item_data['billing_email'] ?? '';
        if ( ! empty( $email ) && ! is_email( $email ) ) {
            $anomalies[] = array(
                'type' => 'invalid_email',
                'level' => 'warning',
                'field' => 'email',
                'message' => 'Invalid email format',
                'value' => $email,
            );
        }
        
        return $anomalies;
    }
    
    /**
     * Get configuration for anomaly detection
     */
    private static function get_config( $import_id = 0 ) {
        $settings = get_option( 'mt_primelink_settings', array() );
        $default_config = array(
            'price_drop_threshold' => 50, // 50% drop = critical (e.g., 80 → 20 = 75% drop)
            'price_increase_threshold' => 200, // 200% increase = critical (e.g., 20 → 80 = 300% increase)
            'price_deviation_threshold' => 50, // 50% deviation from avg = warning
            'max_absolute_price_change' => 0, // 0 = disabled, set value to check absolute difference
            'stock_change_threshold' => 90, // 90% change = info
            'max_stock_threshold' => 10000,
            'content_change_threshold' => 0.3, // 30% similarity threshold
            'require_sku' => true,
            'suspicious_patterns' => array(
                'spam_keywords' => array(),
                'suspicious_domains' => array(),
                'script_patterns' => array( '<script', 'javascript:', 'onerror=', 'onclick=' ),
            ),
        );
        
        // Merge with import-specific config
        if ( $import_id > 0 ) {
            $import_config = get_post_meta( $import_id, '_mt_primelink_anomaly_detection', true );
            if ( is_array( $import_config ) && isset( $import_config['config'] ) ) {
                $default_config = array_merge( $default_config, $import_config['config'] );
            }
        }
        
        // Merge with global settings
        if ( isset( $settings['anomaly_detection_config'] ) ) {
            $default_config = array_merge( $default_config, $settings['anomaly_detection_config'] );
        }
        
        return $default_config;
    }
    
    /**
     * Get historical price average for SKU
     */
    private static function get_historical_price_average( $sku ) {
        global $wpdb;
        
        // Get last 30 days of price history
        $meta_key = '_regular_price';
        $thirty_days_ago = date( 'Y-m-d H:i:s', strtotime( '-30 days' ) );
        
        $product_id = wc_get_product_id_by_sku( $sku );
        if ( ! $product_id ) {
            return 0;
        }
        
        // Get price from post meta history (simplified - în realitate ar trebui să ai un history table)
        $price = get_post_meta( $product_id, $meta_key, true );
        
        return floatval( $price );
    }
    
    /**
     * Calculate text similarity (simple implementation)
     */
    private static function calculate_text_similarity( $text1, $text2 ) {
        // Simple similarity using similar_text
        similar_text( strtolower( $text1 ), strtolower( $text2 ), $percent );
        return $percent / 100;
    }
    
    /**
     * Check if should pause import based on anomalies
     */
    public static function should_pause_import( $anomalies ) {
        foreach ( $anomalies as $anomaly ) {
            if ( $anomaly['level'] === 'critical' ) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Send urgent alert email
     */
    public static function send_urgent_alert( $import_id, $item_data, $anomalies, $item_index = 0 ) {
        $settings = get_option( 'mt_primelink_settings', array() );
        $admin_email = get_option( 'admin_email' );
        
        // Get critical anomalies only
        $critical_anomalies = array_filter( $anomalies, function( $anomaly ) {
            return $anomaly['level'] === 'critical';
        } );
        
        if ( empty( $critical_anomalies ) ) {
            return;
        }
        
        $subject = sprintf( 
            '[URGENT] Critical Anomaly Detected - Import #%d',
            $import_id
        );
        
        $message = "🚨 CRITICAL ANOMALY DETECTED - Action Required!\n\n";
        $message .= sprintf( "Import ID: #%d\n", $import_id );
        $message .= sprintf( "Row: %d\n\n", $item_index + 1 );
        
        foreach ( $critical_anomalies as $anomaly ) {
            $message .= sprintf( 
                "⚠️ %s: %s\n",
                strtoupper( $anomaly['type'] ),
                $anomaly['message']
            );
            
            if ( isset( $anomaly['value'] ) ) {
                $message .= sprintf( "   Current Value: %s\n", $anomaly['value'] );
            }
            if ( isset( $anomaly['previous_value'] ) ) {
                $message .= sprintf( "   Previous Value: %s\n", $anomaly['previous_value'] );
            }
            $message .= "\n";
        }
        
        $message .= "Product Details:\n";
        // Handle nested structure from ImportRunner
        $product_title = $item_data['post_title'] 
            ?? $item_data['post']['post_title'] 
            ?? $item_data['name'] 
            ?? 'N/A';
        $product_sku = $item_data['sku'] 
            ?? $item_data['product']['sku'] 
            ?? 'N/A';
        $product_price = $item_data['regular_price'] 
            ?? $item_data['product']['regular_price'] 
            ?? 'N/A';
        $message .= sprintf( "  Title: %s\n", $product_title );
        $message .= sprintf( "  SKU: %s\n", $product_sku );
        $message .= sprintf( "  Price: %s\n", $product_price );
        
        $message .= "\n";
        $message .= "The import has been PAUSED pending your review.\n\n";
        $message .= "Review now: " . admin_url( "admin.php?page=mt-primelink-imports&action=review&import_id={$import_id}&item_index={$item_index}" ) . "\n\n";
        $message .= "You may want to contact the supplier immediately if this is unexpected.\n";
        
        // Send email
        wp_mail( $admin_email, $subject, $message );
        
        // Also log it
        \PrimeLink\Helpers\LoggerHelper::error(
            'Critical anomaly detected',
            array(
                'import_id' => $import_id,
                'item_index' => $item_index,
                'anomalies' => $critical_anomalies,
            )
        );
    }
    
    /**
     * Store anomaly for review
     */
    public static function store_anomaly( $import_id, $item_index, $item_data, $anomalies ) {
        $existing = get_post_meta( $import_id, '_mt_primelink_anomalies', true );
        if ( ! is_array( $existing ) ) {
            $existing = array();
        }
        
        $existing[] = array(
            'item_index' => $item_index,
            'item_data' => $item_data,
            'anomalies' => $anomalies,
            'detected_at' => current_time( 'mysql' ),
            'status' => 'pending', // pending, approved, rejected, modified
        );
        
        update_post_meta( $import_id, '_mt_primelink_anomalies', $existing );
    }
}

