<?php
/**
 * Import Performance Helper
 * Optimizes import performance by disabling non-critical hooks and using bulk operations
 *
 * @package PrimeLink
 */

namespace PrimeLink\Helpers;

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

final class ImportPerformanceHelper {

    /**
     * Hooks to disable during fast import
     */
    private static $hooks_to_disable = array(
        // WordPress core hooks
        'save_post',
        'transition_post_status',
        'wp_insert_post',
        'wp_insert_post_data',
        'edit_post',
        'post_updated',
        'added_post_meta',
        'updated_post_meta',
        'deleted_post_meta',
        'set_object_terms',
        'added_term_relationship',
        'deleted_term_relationships',
        
        // WooCommerce hooks (if available)
        'woocommerce_new_product',
        'woocommerce_update_product',
        'woocommerce_new_product_variation',
        'woocommerce_update_product_variation',
        'woocommerce_product_set_stock',
        'woocommerce_variation_set_stock',
        'woocommerce_reduce_order_stock',
        'woocommerce_restore_order_stock',
    );

    /**
     * Store original hook callbacks
     */
    private static $original_hooks = array();

    /**
     * Enable fast mode - disable non-critical hooks
     */
    public static function enable_fast_mode() {
        if ( ! empty( self::$original_hooks ) ) {
            return; // Already enabled
        }

        // Store and remove hooks
        foreach ( self::$hooks_to_disable as $hook ) {
            global $wp_filter;
            if ( isset( $wp_filter[ $hook ] ) ) {
                self::$original_hooks[ $hook ] = $wp_filter[ $hook ];
                unset( $wp_filter[ $hook ] );
            }
        }

        // Disable autosave
        if ( ! defined( 'AUTOSAVE_INTERVAL' ) ) {
            define( 'AUTOSAVE_INTERVAL', 86400 ); // 24 hours
        }

        // Disable revisions
        if ( ! defined( 'WP_POST_REVISIONS' ) ) {
            define( 'WP_POST_REVISIONS', false );
        }

        // Increase memory limit if possible
        if ( function_exists( 'ini_set' ) ) {
            @ini_set( 'memory_limit', '512M' );
        }

        // Disable object cache during import
        wp_suspend_cache_addition( true );
    }

    /**
     * Disable fast mode - restore hooks
     */
    public static function disable_fast_mode() {
        if ( empty( self::$original_hooks ) ) {
            return; // Already disabled
        }

        // Restore hooks
        global $wp_filter;
        foreach ( self::$original_hooks as $hook => $callbacks ) {
            $wp_filter[ $hook ] = $callbacks;
        }

        // Re-enable cache
        wp_suspend_cache_addition( false );

        // Clear cache
        wp_cache_flush();

        // Reset
        self::$original_hooks = array();
    }

    /**
     * Batch create products using bulk insert
     * 
     * @param array $products_data Array of product data arrays
     * @return array Array of created product IDs
     */
    public static function batch_create_products( $products_data ) {
        if ( empty( $products_data ) ) {
            return array();
        }

        $now = current_time( 'mysql' );
        $now_gmt = current_time( 'mysql', 1 );
        $author_id = get_current_user_id();

        // Prepare post data for bulk insert
        $posts_data = array();
        foreach ( $products_data as $product_data ) {
            $posts_data[] = array(
                'post_author'    => $author_id,
                'post_date'      => $now,
                'post_date_gmt'  => $now_gmt,
                'post_content'   => $product_data['post']['post_content'] ?? '',
                'post_title'     => $product_data['post']['post_title'] ?? '',
                'post_excerpt'   => $product_data['post']['post_excerpt'] ?? '',
                'post_status'    => $product_data['post']['post_status'] ?? 'publish',
                'post_name'      => ! empty( $product_data['post']['post_name'] ) 
                    ? sanitize_title( $product_data['post']['post_name'] ) 
                    : sanitize_title( $product_data['post']['post_title'] ?? '' ),
                'post_type'      => 'product',
                'comment_status' => 'closed',
                'ping_status'    => 'closed',
                'post_modified'  => $now,
                'post_modified_gmt' => $now_gmt,
            );
        }

        // Bulk insert posts
        $product_ids = DatabaseOptimizationHelper::bulk_insert_posts( $posts_data );

        if ( empty( $product_ids ) ) {
            return array();
        }

        // Prepare meta data for bulk insert
        $meta_data = array();
        foreach ( $products_data as $index => $product_data ) {
            if ( ! isset( $product_ids[ $index ] ) ) {
                continue;
            }

            $product_id = $product_ids[ $index ];

            // Product meta
            if ( ! empty( $product_data['product'] ) ) {
                foreach ( $product_data['product'] as $key => $value ) {
                    if ( $value !== '' && $value !== null ) {
                        $meta_data[] = array(
                            'post_id'   => $product_id,
                            'meta_key'  => '_' . $key,
                            'meta_value' => $value,
                        );
                    }
                }
            }

            // Custom meta
            if ( ! empty( $product_data['meta'] ) ) {
                foreach ( $product_data['meta'] as $key => $value ) {
                    $meta_data[] = array(
                        'post_id'   => $product_id,
                        'meta_key'  => $key,
                        'meta_value' => $value,
                    );
                }
            }

            // Import tracking meta
            if ( ! empty( $product_data['import_id'] ) ) {
                $meta_data[] = array(
                    'post_id'   => $product_id,
                    'meta_key'  => '_mt_primelink_import_id',
                    'meta_value' => absint( $product_data['import_id'] ),
                );
            }
        }

        // Bulk insert meta
        if ( ! empty( $meta_data ) ) {
            DatabaseOptimizationHelper::bulk_update_post_meta( $meta_data );
        }

        return $product_ids;
    }

    /**
     * Batch assign terms to products
     * 
     * @param array $term_assignments Array of arrays with keys: product_id, taxonomy, terms
     * @return void
     */
    public static function batch_assign_terms( $term_assignments ) {
        if ( empty( $term_assignments ) ) {
            return;
        }

        global $wpdb;

        // Group by taxonomy
        $grouped = array();
        foreach ( $term_assignments as $assignment ) {
            $taxonomy = $assignment['taxonomy'] ?? '';
            $product_id = absint( $assignment['product_id'] ?? 0 );
            $terms = $assignment['terms'] ?? array();

            if ( empty( $taxonomy ) || $product_id < 1 || empty( $terms ) ) {
                continue;
            }

            if ( ! isset( $grouped[ $taxonomy ] ) ) {
                $grouped[ $taxonomy ] = array();
            }

            if ( ! isset( $grouped[ $taxonomy ][ $product_id ] ) ) {
                $grouped[ $taxonomy ][ $product_id ] = array();
            }

            $grouped[ $taxonomy ][ $product_id ] = array_merge(
                $grouped[ $taxonomy ][ $product_id ],
                (array) $terms
            );
        }

        // Assign terms for each taxonomy
        foreach ( $grouped as $taxonomy => $products ) {
            foreach ( $products as $product_id => $terms ) {
                $terms = array_unique( array_filter( $terms ) );
                if ( ! empty( $terms ) ) {
                    wp_set_object_terms( $product_id, $terms, $taxonomy, false );
                }
            }
        }
    }

    /**
     * Check if fast mode is enabled in settings
     * 
     * @return bool
     */
    public static function is_fast_mode_enabled() {
        $settings = get_option( 'mt_primelink_settings', array() );
        return ! empty( $settings['fast_import_mode'] );
    }
}

