<?php
namespace PrimeLink\Modules\Variations;

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

class VariationImportService {
    /**
     * Find an existing variation by a given field (variation_id, sku, parent + attributes)
     * 
     * @param array $variation_data Variation data
     * @param string $match_by Match by field
     * @param array $batch_lookups Optional batch lookup results (for optimization)
     * @return int Variation ID or 0 if not found
     */
    public static function find_existing_variation_id( $variation_data, $match_by, $batch_lookups = null ) {
        $match_by = (string) $match_by;
        
        // Match by variation_id
        if ( $match_by === 'variation_id' && ! empty( $variation_data['variation_id'] ) ) {
            $variation_id = absint( $variation_data['variation_id'] );
            $variation = wc_get_product( $variation_id );
            return ( $variation && $variation->is_type( 'variation' ) ) ? $variation_id : 0;
        }
        
        // Match by SKU (most reliable for variations)
        if ( $match_by === 'sku' && ! empty( $variation_data['sku'] ) ) {
            $sku = sanitize_text_field( $variation_data['sku'] );
            
            // Use batch lookup if available
            if ( $batch_lookups && isset( $batch_lookups['variations_by_sku'][ $sku ] ) ) {
                return absint( $batch_lookups['variations_by_sku'][ $sku ] );
            }
            
            // Fallback to individual lookup
            global $wpdb;
            $variation_id = $wpdb->get_var( $wpdb->prepare(
                "SELECT post_id FROM {$wpdb->postmeta} 
                WHERE meta_key = '_sku' AND meta_value = %s 
                AND post_id IN (SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product_variation') 
                LIMIT 1",
                $sku
            ) );
            return $variation_id > 0 ? absint( $variation_id ) : 0;
        }
        
        // Match by parent + attributes
        if ( $match_by === 'parent_attributes' && ! empty( $variation_data['parent_id'] ) && ! empty( $variation_data['attributes'] ) ) {
            $parent_id = absint( $variation_data['parent_id'] );
            $attributes = $variation_data['attributes'];
            
            if ( is_string( $attributes ) ) {
                $attributes = json_decode( $attributes, true );
            }
            
            if ( ! is_array( $attributes ) ) {
                return 0;
            }
            
            $parent = wc_get_product( $parent_id );
            if ( ! $parent || ! $parent->is_type( 'variable' ) ) {
                return 0;
            }
            
            // Get all variations of this parent
            $variation_ids = $parent->get_children();
            
            foreach ( $variation_ids as $variation_id ) {
                $variation = wc_get_product( $variation_id );
                if ( ! $variation || ! $variation->is_type( 'variation' ) ) {
                    continue;
                }
                
                $variation_attrs = $variation->get_attributes();
                $match = true;
                
                foreach ( $attributes as $attr_name => $attr_value ) {
                    $attr_key = strpos( $attr_name, 'pa_' ) === 0 ? $attr_name : 'pa_' . sanitize_title( $attr_name );
                    if ( ! isset( $variation_attrs[ $attr_key ] ) || $variation_attrs[ $attr_key ] !== $attr_value ) {
                        $match = false;
                        break;
                    }
                }
                
                if ( $match ) {
                    return absint( $variation_id );
                }
            }
        }
        
        return 0;
    }

    /**
     * Create a new WooCommerce product variation from mapped data
     */
    public static function create_variation( $variation_data, $import_id = 0 ) {
        // Parent product ID is required
        if ( empty( $variation_data['parent_id'] ) ) {
            return 0;
        }
        
        $parent_id = absint( $variation_data['parent_id'] );
        $parent = wc_get_product( $parent_id );
        
        if ( ! $parent ) {
            \PrimeLink\Helpers\LoggerHelper::error(
                'Variation Import Error: Parent product not found',
                array( 'parent_id' => $parent_id )
            );
            return 0;
        }
        
        // Ensure parent is variable type
        if ( ! $parent->is_type( 'variable' ) ) {
            wp_set_object_terms( $parent_id, 'variable', 'product_type', false );
            $parent = wc_get_product( $parent_id );
        }
        
        // Create variation
        $variation = new \WC_Product_Variation();
        $variation->set_parent_id( $parent_id );
        
        // Set attributes
        if ( ! empty( $variation_data['attributes'] ) ) {
            $attributes = $variation_data['attributes'];
            if ( is_string( $attributes ) ) {
                $attributes = json_decode( $attributes, true );
            }
            if ( is_array( $attributes ) ) {
                $variation->set_attributes( $attributes );
            }
        }
        
        // Set SKU
        if ( ! empty( $variation_data['sku'] ) ) {
            $variation->set_sku( sanitize_text_field( $variation_data['sku'] ) );
        }
        
        // Set prices
        if ( isset( $variation_data['regular_price'] ) && $variation_data['regular_price'] !== '' ) {
            $variation->set_regular_price( (string) $variation_data['regular_price'] );
        }
        if ( isset( $variation_data['sale_price'] ) && $variation_data['sale_price'] !== '' ) {
            $variation->set_sale_price( (string) $variation_data['sale_price'] );
        }
        
        // Set stock
        if ( isset( $variation_data['stock_quantity'] ) && $variation_data['stock_quantity'] !== '' ) {
            $variation->set_manage_stock( true );
            $variation->set_stock_quantity( absint( $variation_data['stock_quantity'] ) );
        } elseif ( isset( $variation_data['manage_stock'] ) ) {
            $variation->set_manage_stock( (bool) $variation_data['manage_stock'] );
        }
        
        if ( ! empty( $variation_data['stock_status'] ) ) {
            $variation->set_stock_status( sanitize_text_field( $variation_data['stock_status'] ) );
        }
        
        // Set dimensions
        if ( isset( $variation_data['weight'] ) && $variation_data['weight'] !== '' ) {
            $variation->set_weight( (string) $variation_data['weight'] );
        }
        if ( isset( $variation_data['length'] ) && $variation_data['length'] !== '' ) {
            $variation->set_length( (string) $variation_data['length'] );
        }
        if ( isset( $variation_data['width'] ) && $variation_data['width'] !== '' ) {
            $variation->set_width( (string) $variation_data['width'] );
        }
        if ( isset( $variation_data['height'] ) && $variation_data['height'] !== '' ) {
            $variation->set_height( (string) $variation_data['height'] );
        }
        
        // Set tax class
        if ( ! empty( $variation_data['tax_class'] ) ) {
            $variation->set_tax_class( sanitize_text_field( $variation_data['tax_class'] ) );
        }
        
        // Set backorders
        if ( isset( $variation_data['backorders'] ) ) {
            $variation->set_backorders( sanitize_text_field( $variation_data['backorders'] ) );
        }
        
        // Set description
        if ( ! empty( $variation_data['description'] ) ) {
            $variation->set_description( wp_kses_post( $variation_data['description'] ) );
        }
        
        // Set short description
        if ( ! empty( $variation_data['short_description'] ) ) {
            $variation->set_short_description( wp_kses_post( $variation_data['short_description'] ) );
        }
        
        // Set image
        if ( ! empty( $variation_data['image'] ) ) {
            $image_id = \PrimeLink\Modules\Imports\Service\ImportMapper::maybe_attach_image( $variation_data['image'], $variation->get_id() );
            if ( $image_id ) {
                $variation->set_image_id( $image_id );
            }
        }
        
        // Set gallery
        if ( ! empty( $variation_data['gallery'] ) ) {
            $gallery_ids = array();
            $urls = \PrimeLink\Modules\Imports\Service\ImportMapper::normalize_list( $variation_data['gallery'] );
            foreach ( $urls as $url ) {
                $img_id = \PrimeLink\Modules\Imports\Service\ImportMapper::maybe_attach_image( $url, $parent_id );
                if ( $img_id ) {
                    $gallery_ids[] = $img_id;
                }
            }
            if ( ! empty( $gallery_ids ) ) {
                update_post_meta( $variation->get_id(), '_variation_gallery', implode( ',', $gallery_ids ) );
            }
        }
        
        // Set status
        $status = ! empty( $variation_data['status'] ) ? sanitize_text_field( $variation_data['status'] ) : 'publish';
        $variation->set_status( $status );
        
        // Save variation
        $variation_id = $variation->save();
        
        if ( is_wp_error( $variation_id ) ) {
            \PrimeLink\Helpers\LoggerHelper::error(
                'Variation Import Error: ' . $variation_id->get_error_message(),
                array(
                    'parent_id' => $parent_id,
                    'data' => $variation_data,
                )
            );
            return 0;
        }
        
        // Store import tracking
        if ( $import_id > 0 ) {
            update_post_meta( $variation_id, '_mt_primelink_import_id', absint( $import_id ) );
        }
        
        return absint( $variation_id );
    }

    /**
     * Update an existing WooCommerce product variation
     */
    public static function update_variation( $variation_id, $variation_data, $update_fields = array() ) {
        $variation = wc_get_product( $variation_id );
        if ( ! $variation || ! $variation->is_type( 'variation' ) ) {
            return false;
        }
        
        $update_all = empty( $update_fields ) || in_array( 'all', $update_fields, true );
        
        // Update SKU
        if ( ( $update_all || in_array( 'sku', $update_fields, true ) ) && isset( $variation_data['sku'] ) ) {
            $variation->set_sku( sanitize_text_field( $variation_data['sku'] ) );
        }
        
        // Update prices
        if ( ( $update_all || in_array( 'price', $update_fields, true ) ) && isset( $variation_data['regular_price'] ) ) {
            $variation->set_regular_price( (string) $variation_data['regular_price'] );
        }
        if ( ( $update_all || in_array( 'price', $update_fields, true ) ) && isset( $variation_data['sale_price'] ) ) {
            $variation->set_sale_price( (string) $variation_data['sale_price'] );
        }
        
        // Update stock
        if ( ( $update_all || in_array( 'stock', $update_fields, true ) ) && isset( $variation_data['stock_quantity'] ) ) {
            $variation->set_manage_stock( true );
            $variation->set_stock_quantity( absint( $variation_data['stock_quantity'] ) );
        }
        if ( ( $update_all || in_array( 'stock', $update_fields, true ) ) && isset( $variation_data['stock_status'] ) ) {
            $variation->set_stock_status( sanitize_text_field( $variation_data['stock_status'] ) );
        }
        if ( ( $update_all || in_array( 'stock', $update_fields, true ) ) && isset( $variation_data['manage_stock'] ) ) {
            $variation->set_manage_stock( (bool) $variation_data['manage_stock'] );
        }
        
        // Update dimensions
        if ( ( $update_all || in_array( 'dimensions', $update_fields, true ) ) && isset( $variation_data['weight'] ) ) {
            $variation->set_weight( (string) $variation_data['weight'] );
        }
        if ( ( $update_all || in_array( 'dimensions', $update_fields, true ) ) && isset( $variation_data['length'] ) ) {
            $variation->set_length( (string) $variation_data['length'] );
        }
        if ( ( $update_all || in_array( 'dimensions', $update_fields, true ) ) && isset( $variation_data['width'] ) ) {
            $variation->set_width( (string) $variation_data['width'] );
        }
        if ( ( $update_all || in_array( 'dimensions', $update_fields, true ) ) && isset( $variation_data['height'] ) ) {
            $variation->set_height( (string) $variation_data['height'] );
        }
        
        // Update tax class
        if ( ( $update_all || in_array( 'tax_class', $update_fields, true ) ) && isset( $variation_data['tax_class'] ) ) {
            $variation->set_tax_class( sanitize_text_field( $variation_data['tax_class'] ) );
        }
        
        // Update backorders
        if ( ( $update_all || in_array( 'backorders', $update_fields, true ) ) && isset( $variation_data['backorders'] ) ) {
            $variation->set_backorders( sanitize_text_field( $variation_data['backorders'] ) );
        }
        
        // Update description
        if ( ( $update_all || in_array( 'description', $update_fields, true ) ) && isset( $variation_data['description'] ) ) {
            $variation->set_description( wp_kses_post( $variation_data['description'] ) );
        }
        
        // Update short description
        if ( ( $update_all || in_array( 'short_description', $update_fields, true ) ) && isset( $variation_data['short_description'] ) ) {
            $variation->set_short_description( wp_kses_post( $variation_data['short_description'] ) );
        }
        
        // Update image
        if ( ( $update_all || in_array( 'image', $update_fields, true ) ) && isset( $variation_data['image'] ) ) {
            $image_id = \PrimeLink\Modules\Imports\Service\ImportMapper::maybe_attach_image( $variation_data['image'], $variation_id );
            if ( $image_id ) {
                $variation->set_image_id( $image_id );
            }
        }
        
        // Update gallery
        if ( ( $update_all || in_array( 'gallery', $update_fields, true ) ) && isset( $variation_data['gallery'] ) ) {
            $gallery_ids = array();
            $urls = \PrimeLink\Modules\Imports\Service\ImportMapper::normalize_list( $variation_data['gallery'] );
            foreach ( $urls as $url ) {
                $img_id = \PrimeLink\Modules\Imports\Service\ImportMapper::maybe_attach_image( $url, $variation->get_parent_id() );
                if ( $img_id ) {
                    $gallery_ids[] = $img_id;
                }
            }
            if ( ! empty( $gallery_ids ) ) {
                update_post_meta( $variation_id, '_variation_gallery', implode( ',', $gallery_ids ) );
            }
        }
        
        // Update attributes
        if ( ( $update_all || in_array( 'attributes', $update_fields, true ) ) && isset( $variation_data['attributes'] ) ) {
            $attributes = $variation_data['attributes'];
            if ( is_string( $attributes ) ) {
                $attributes = json_decode( $attributes, true );
            }
            if ( is_array( $attributes ) ) {
                $variation->set_attributes( $attributes );
            }
        }
        
        // Update status
        if ( ( $update_all || in_array( 'status', $update_fields, true ) ) && isset( $variation_data['status'] ) ) {
            $variation->set_status( sanitize_text_field( $variation_data['status'] ) );
        }
        
        return $variation->save();
    }

    /**
     * Prepare batch lookups for variations
     */
    public static function prepare_batch_lookups( $rows, $headers, $mapping, $match_by ) {
        $lookups = array(
            'variations_by_sku' => array(),
            'variations_by_id' => array(),
        );
        
        if ( empty( $rows ) || empty( $mapping ) ) {
            return $lookups;
        }
        
        // Get all variation SKUs and IDs from the batch
        global $wpdb;
        
        // Extract SKUs from mapping
        $skus = array();
        foreach ( $rows as $row ) {
            $item = array();
            foreach ( $headers as $idx => $header ) {
                $item[ $header ] = $row[ $idx ] ?? '';
            }
            
            // Try to get SKU from mapped data
            foreach ( $mapping as $column_config ) {
                if ( is_string( $column_config ) ) {
                    $column_config = array( 'source' => $column_config );
                }
                $source = $column_config['source'] ?? '';
                if ( $source === 'sku' && ! empty( $item[ $source ] ) ) {
                    $skus[] = sanitize_text_field( $item[ $source ] );
                }
            }
        }
        
        if ( ! empty( $skus ) ) {
            $placeholders = implode( ',', array_fill( 0, count( $skus ), '%s' ) );
            $query = $wpdb->prepare(
                "SELECT post_id, meta_value FROM {$wpdb->postmeta} 
                WHERE meta_key = '_sku' AND meta_value IN ($placeholders)
                AND post_id IN (SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product_variation')",
                ...$skus
            );
            $results = $wpdb->get_results( $query );
            foreach ( $results as $result ) {
                $lookups['variations_by_sku'][ $result->meta_value ] = absint( $result->post_id );
            }
        }
        
        return $lookups;
    }
}


