<?php
namespace PrimeLink\Modules\Attributes;

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

class AttributeImportService {
    /**
     * Find an existing attribute by a given field (slug, name, attribute_id)
     * 
     * @param array $attribute_data Attribute data
     * @param string $match_by Match by field
     * @param array $batch_lookups Optional batch lookup results (for optimization)
     * @return int Attribute ID or 0 if not found
     */
    public static function find_existing_attribute_id( $attribute_data, $match_by, $batch_lookups = null ) {
        $match_by = (string) $match_by;
        
        // Match by slug (most reliable)
        if ( $match_by === 'slug' && ! empty( $attribute_data['slug'] ) ) {
            $slug = sanitize_title( $attribute_data['slug'] );
            
            // Use batch lookup if available
            if ( $batch_lookups && isset( $batch_lookups['attributes_by_slug'][ $slug ] ) ) {
                return absint( $batch_lookups['attributes_by_slug'][ $slug ] );
            }
            
            // Fallback to individual lookup
            $attribute_id = wc_attribute_taxonomy_id_by_name( $slug );
            return $attribute_id > 0 ? $attribute_id : 0;
        }
        
        // Match by attribute_id
        if ( $match_by === 'attribute_id' && ! empty( $attribute_data['attribute_id'] ) ) {
            $attribute_id = absint( $attribute_data['attribute_id'] );
            $attribute = wc_get_attribute( $attribute_id );
            return $attribute ? absint( $attribute->id ) : 0;
        }
        
        // Match by name (fallback)
        if ( ! empty( $attribute_data['name'] ) ) {
            $name = sanitize_text_field( $attribute_data['name'] );
            
            // Use batch lookup if available
            if ( $batch_lookups && isset( $batch_lookups['attributes_by_name'][ $name ] ) ) {
                return absint( $batch_lookups['attributes_by_name'][ $name ] );
            }
            
            // Fallback to individual lookup
            $attribute_id = wc_attribute_taxonomy_id_by_name( $name );
            return $attribute_id > 0 ? $attribute_id : 0;
        }
        
        return 0;
    }

    /**
     * Create a new WooCommerce product attribute from mapped data
     */
    public static function create_attribute( $attribute_data, $import_id = 0 ) {
        // Name is required
        if ( empty( $attribute_data['name'] ) ) {
            return 0;
        }

        $name = sanitize_text_field( $attribute_data['name'] );
        
        // Generate slug if not provided
        $slug = ! empty( $attribute_data['slug'] ) 
            ? sanitize_title( $attribute_data['slug'] ) 
            : sanitize_title( $name );
        
        // Remove 'pa_' prefix if present (WooCommerce stores without it in database)
        if ( strpos( $slug, 'pa_' ) === 0 ) {
            $slug = substr( $slug, 3 );
        }
        
        // Check if attribute already exists by slug
        $existing_id = wc_attribute_taxonomy_id_by_name( $slug );
        if ( $existing_id > 0 ) {
            // Update existing attribute
            $attribute_id = $existing_id;
        } else {
            // Create new attribute
            // Note: WooCommerce stores slug without 'pa_' prefix in database
            $args = array(
                'name'         => $name,
                'slug'         => $slug, // Without 'pa_' prefix
                'type'         => ! empty( $attribute_data['type'] ) ? sanitize_text_field( $attribute_data['type'] ) : 'select',
                'order_by'     => ! empty( $attribute_data['order_by'] ) ? sanitize_text_field( $attribute_data['order_by'] ) : 'menu_order',
                'has_archives' => ! empty( $attribute_data['has_archives'] ) ? (bool) $attribute_data['has_archives'] : false,
            );
            
            $attribute_id = wc_create_attribute( $args );
            
            if ( is_wp_error( $attribute_id ) ) {
                \PrimeLink\Helpers\LoggerHelper::error(
                    'Attribute Import Error: ' . $attribute_id->get_error_message(),
                    array(
                        'name' => $name,
                        'slug' => $slug,
                    )
                );
                return 0;
            }
            
            $attribute_id = absint( $attribute_id );
        }
        
        // Import attribute terms if provided
        if ( ! empty( $attribute_data['terms'] ) && is_array( $attribute_data['terms'] ) ) {
            self::import_attribute_terms( $attribute_id, $attribute_data['terms'], $import_id );
        }
        
        // Store import tracking
        if ( $import_id > 0 ) {
            update_option( '_mt_primelink_attribute_import_' . $attribute_id, absint( $import_id ) );
        }
        
        return $attribute_id;
    }

    /**
     * Update an existing attribute
     */
    public static function update_attribute( $attribute_id, $attribute_data, $update_fields = array() ) {
        $attribute = wc_get_attribute( $attribute_id );
        if ( ! $attribute ) {
            return;
        }
        
        $args = array();
        
        // Update name
        if ( ( empty( $update_fields ) || in_array( 'name', $update_fields ) ) && ! empty( $attribute_data['name'] ) ) {
            $args['name'] = sanitize_text_field( $attribute_data['name'] );
        }
        
        // Update type
        if ( ( empty( $update_fields ) || in_array( 'type', $update_fields ) ) && ! empty( $attribute_data['type'] ) ) {
            $args['type'] = sanitize_text_field( $attribute_data['type'] );
        }
        
        // Update order_by
        if ( ( empty( $update_fields ) || in_array( 'order_by', $update_fields ) ) && isset( $attribute_data['order_by'] ) ) {
            $args['order_by'] = sanitize_text_field( $attribute_data['order_by'] );
        }
        
        // Update has_archives
        if ( ( empty( $update_fields ) || in_array( 'has_archives', $update_fields ) ) && isset( $attribute_data['has_archives'] ) ) {
            $args['has_archives'] = (bool) $attribute_data['has_archives'];
        }
        
        // Update attribute if we have changes
        if ( ! empty( $args ) ) {
            $result = wc_update_attribute( $attribute_id, $args );
            if ( is_wp_error( $result ) ) {
                \PrimeLink\Helpers\LoggerHelper::error(
                    'Attribute Update Error: ' . $result->get_error_message(),
                    array(
                        'attribute_id' => $attribute_id,
                        'update_args' => $args,
                    )
                );
                return;
            }
        }
        
        // Update terms
        if ( ( empty( $update_fields ) || in_array( 'terms', $update_fields ) ) && ! empty( $attribute_data['terms'] ) && is_array( $attribute_data['terms'] ) ) {
            self::import_attribute_terms( $attribute_id, $attribute_data['terms'], 0 );
        }
    }

    /**
     * Import attribute terms
     */
    private static function import_attribute_terms( $attribute_id, $terms, $import_id = 0 ) {
        $attribute = wc_get_attribute( $attribute_id );
        if ( ! $attribute ) {
            return;
        }
        
        // Get taxonomy name - WooCommerce uses 'pa_' prefix for taxonomy names
        $taxonomy = wc_attribute_taxonomy_name( $attribute->slug );
        
        foreach ( $terms as $term_data ) {
            if ( empty( $term_data['name'] ) ) {
                continue;
            }
            
            $term_name = sanitize_text_field( $term_data['name'] );
            $term_slug = ! empty( $term_data['slug'] ) 
                ? sanitize_title( $term_data['slug'] ) 
                : sanitize_title( $term_name );
            
            // Check if term exists
            $existing_term = get_term_by( 'slug', $term_slug, $taxonomy );
            
            if ( $existing_term ) {
                $term_id = $existing_term->term_id;
                
                // Update term if needed
                if ( ! empty( $term_data['description'] ) ) {
                    wp_update_term( $term_id, $taxonomy, array(
                        'description' => sanitize_textarea_field( $term_data['description'] ),
                    ) );
                }
            } else {
                // Create new term
                $result = wp_insert_term( $term_name, $taxonomy, array(
                    'slug'        => $term_slug,
                    'description' => ! empty( $term_data['description'] ) ? sanitize_textarea_field( $term_data['description'] ) : '',
                ) );
                
                if ( is_wp_error( $result ) ) {
                    \PrimeLink\Helpers\LoggerHelper::error(
                        'Attribute Term Import Error: ' . $result->get_error_message(),
                        array(
                            'attribute_id' => $attribute_id,
                            'term_name' => $term_name,
                        )
                    );
                    continue;
                }
                
                $term_id = absint( $result['term_id'] );
            }
            
            // Set term order if provided
            if ( isset( $term_data['order'] ) ) {
                update_term_meta( $term_id, 'order', absint( $term_data['order'] ) );
            }
            
            // Set term color/swatch if provided (for plugins like WooCommerce Color or Label Swatches)
            if ( ! empty( $term_data['color'] ) ) {
                update_term_meta( $term_id, 'product_attribute_color', sanitize_hex_color( $term_data['color'] ) );
            }
            
            // Store import tracking
            if ( $import_id > 0 ) {
                update_term_meta( $term_id, '_mt_primelink_import_id', absint( $import_id ) );
            }
        }
    }

    /**
     * Prepare batch lookups for attributes
     */
    public static function prepare_batch_lookups( $rows, $headers, $mapping, $match_by ) {
        $lookups = array(
            'attributes_by_slug' => array(),
            'attributes_by_name' => array(),
        );
        
        if ( empty( $rows ) || empty( $mapping ) ) {
            return $lookups;
        }
        
        // Get all existing attributes
        $attributes = wc_get_attribute_taxonomies();
        
        foreach ( $attributes as $attribute ) {
            $lookups['attributes_by_slug'][ $attribute->attribute_name ] = $attribute->attribute_id;
            $lookups['attributes_by_name'][ $attribute->attribute_label ] = $attribute->attribute_id;
        }
        
        return $lookups;
    }
}

