<?php
namespace PrimeLink\Modules\Categories;

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

class CategoryImportService {
    /**
     * Find an existing category by a given field (slug, name, category_id)
     * 
     * @param array $category_data Category data
     * @param string $match_by Match by field
     * @param array $batch_lookups Optional batch lookup results (for optimization)
     * @return int Category term ID or 0 if not found
     */
    public static function find_existing_category_id( $category_data, $match_by, $batch_lookups = null ) {
        $match_by = (string) $match_by;
        
        // Match by slug (most reliable)
        if ( $match_by === 'slug' && ! empty( $category_data['slug'] ) ) {
            $slug = sanitize_title( $category_data['slug'] );
            
            // Use batch lookup if available
            if ( $batch_lookups && isset( $batch_lookups['categories_by_slug'][ $slug ] ) ) {
                return absint( $batch_lookups['categories_by_slug'][ $slug ] );
            }
            
            // Fallback to individual lookup
            $term = get_term_by( 'slug', $slug, 'product_cat' );
            return $term ? absint( $term->term_id ) : 0;
        }
        
        // Match by category_id
        if ( $match_by === 'category_id' && ! empty( $category_data['category_id'] ) ) {
            $term_id = absint( $category_data['category_id'] );
            $term = get_term( $term_id, 'product_cat' );
            return $term && ! is_wp_error( $term ) ? absint( $term->term_id ) : 0;
        }
        
        // Match by name (fallback)
        if ( ! empty( $category_data['name'] ) ) {
            $name = sanitize_text_field( $category_data['name'] );
            
            // Use batch lookup if available
            if ( $batch_lookups && isset( $batch_lookups['categories_by_name'][ $name ] ) ) {
                return absint( $batch_lookups['categories_by_name'][ $name ] );
            }
            
            // Fallback to individual lookup
            $term = get_term_by( 'name', $name, 'product_cat' );
            return $term ? absint( $term->term_id ) : 0;
        }
        
        return 0;
    }

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

        $name = sanitize_text_field( $category_data['name'] );
        
        // Generate slug if not provided
        $slug = ! empty( $category_data['slug'] ) 
            ? sanitize_title( $category_data['slug'] ) 
            : sanitize_title( $name );
        
        // Ensure slug is unique
        $slug = self::ensure_unique_slug( $slug );
        
        // Parent category
        $parent = 0;
        if ( ! empty( $category_data['parent'] ) ) {
            $parent = self::resolve_parent_category( $category_data['parent'] );
        }
        
        // Description
        $description = ! empty( $category_data['description'] ) 
            ? sanitize_textarea_field( $category_data['description'] ) 
            : '';
        
        // Check if category already exists by slug
        $existing_term = get_term_by( 'slug', $slug, 'product_cat' );
        if ( $existing_term ) {
            // Update existing category
            $term_id = $existing_term->term_id;
        } else {
            // Create new category
            $result = wp_insert_term( $name, 'product_cat', array(
                'slug'        => $slug,
                'parent'      => $parent,
                'description' => $description,
            ) );
            
            if ( is_wp_error( $result ) ) {
                \PrimeLink\Helpers\LoggerHelper::error(
                    'Category Import Error: ' . $result->get_error_message(),
                    array(
                        'name' => $name,
                        'slug' => $slug,
                    )
                );
                return 0;
            }
            
            $term_id = absint( $result['term_id'] );
        }
        
        // Set thumbnail image
        if ( ! empty( $category_data['thumbnail'] ) ) {
            $thumbnail_id = self::process_thumbnail( $category_data['thumbnail'], $term_id );
            if ( $thumbnail_id > 0 ) {
                update_term_meta( $term_id, 'thumbnail_id', $thumbnail_id );
            }
        }
        
        // Set display type
        if ( ! empty( $category_data['display_type'] ) ) {
            $display_type = sanitize_text_field( $category_data['display_type'] );
            $valid_types = array( 'default', 'products', 'subcategories', 'both' );
            if ( in_array( $display_type, $valid_types, true ) ) {
                update_term_meta( $term_id, 'display_type', $display_type );
            }
        }
        
        // Custom meta fields
        if ( ! empty( $category_data['meta'] ) && is_array( $category_data['meta'] ) ) {
            foreach ( $category_data['meta'] as $key => $value ) {
                update_term_meta( $term_id, sanitize_key( $key ), $value );
            }
        }
        
        // Store import tracking
        if ( $import_id > 0 ) {
            update_term_meta( $term_id, '_mt_primelink_import_id', absint( $import_id ) );
        }
        
        return $term_id;
    }

    /**
     * Update an existing category
     */
    public static function update_category( $term_id, $category_data, $update_fields = array() ) {
        $term = get_term( $term_id, 'product_cat' );
        if ( ! $term || is_wp_error( $term ) ) {
            return;
        }
        
        $update_args = array();
        
        // Update name
        if ( ( empty( $update_fields ) || in_array( 'name', $update_fields ) ) && ! empty( $category_data['name'] ) ) {
            $update_args['name'] = sanitize_text_field( $category_data['name'] );
        }
        
        // Update slug
        if ( ( empty( $update_fields ) || in_array( 'slug', $update_fields ) ) && ! empty( $category_data['slug'] ) ) {
            $slug = sanitize_title( $category_data['slug'] );
            $slug = self::ensure_unique_slug( $slug, $term_id );
            $update_args['slug'] = $slug;
        }
        
        // Update parent
        if ( ( empty( $update_fields ) || in_array( 'parent', $update_fields ) ) && isset( $category_data['parent'] ) ) {
            $parent = self::resolve_parent_category( $category_data['parent'] );
            $update_args['parent'] = $parent;
        }
        
        // Update description
        if ( ( empty( $update_fields ) || in_array( 'description', $update_fields ) ) && isset( $category_data['description'] ) ) {
            $update_args['description'] = sanitize_textarea_field( $category_data['description'] );
        }
        
        // Update term if we have changes
        if ( ! empty( $update_args ) ) {
            $result = wp_update_term( $term_id, 'product_cat', $update_args );
            if ( is_wp_error( $result ) ) {
                \PrimeLink\Helpers\LoggerHelper::error(
                    'Category Update Error: ' . $result->get_error_message(),
                    array(
                        'term_id' => $term_id,
                        'update_args' => $update_args,
                    )
                );
                return;
            }
        }
        
        // Update thumbnail
        if ( ( empty( $update_fields ) || in_array( 'thumbnail', $update_fields ) ) && isset( $category_data['thumbnail'] ) ) {
            if ( ! empty( $category_data['thumbnail'] ) ) {
                $thumbnail_id = self::process_thumbnail( $category_data['thumbnail'], $term_id );
                if ( $thumbnail_id > 0 ) {
                    update_term_meta( $term_id, 'thumbnail_id', $thumbnail_id );
                }
            } else {
                // Remove thumbnail if empty
                delete_term_meta( $term_id, 'thumbnail_id' );
            }
        }
        
        // Update display type
        if ( ( empty( $update_fields ) || in_array( 'display_type', $update_fields ) ) && isset( $category_data['display_type'] ) ) {
            if ( ! empty( $category_data['display_type'] ) ) {
                $display_type = sanitize_text_field( $category_data['display_type'] );
                $valid_types = array( 'default', 'products', 'subcategories', 'both' );
                if ( in_array( $display_type, $valid_types, true ) ) {
                    update_term_meta( $term_id, 'display_type', $display_type );
                }
            } else {
                delete_term_meta( $term_id, 'display_type' );
            }
        }
        
        // Update custom meta fields
        if ( ( empty( $update_fields ) || in_array( 'custom_fields', $update_fields ) ) && ! empty( $category_data['meta'] ) && is_array( $category_data['meta'] ) ) {
            foreach ( $category_data['meta'] as $key => $value ) {
                update_term_meta( $term_id, sanitize_key( $key ), $value );
            }
        }
    }

    /**
     * Resolve parent category from various formats (ID, slug, name)
     */
    private static function resolve_parent_category( $parent_value ) {
        if ( empty( $parent_value ) ) {
            return 0;
        }
        
        // If it's already a numeric ID
        if ( is_numeric( $parent_value ) ) {
            $term = get_term( absint( $parent_value ), 'product_cat' );
            return $term && ! is_wp_error( $term ) ? absint( $term->term_id ) : 0;
        }
        
        // Try by slug
        $term = get_term_by( 'slug', sanitize_title( $parent_value ), 'product_cat' );
        if ( $term ) {
            return absint( $term->term_id );
        }
        
        // Try by name
        $term = get_term_by( 'name', sanitize_text_field( $parent_value ), 'product_cat' );
        return $term ? absint( $term->term_id ) : 0;
    }

    /**
     * Ensure slug is unique
     */
    private static function ensure_unique_slug( $slug, $exclude_term_id = 0 ) {
        $original_slug = $slug;
        $counter = 1;
        
        while ( true ) {
            $term = get_term_by( 'slug', $slug, 'product_cat' );
            if ( ! $term || ( $exclude_term_id > 0 && $term->term_id === $exclude_term_id ) ) {
                break;
            }
            $slug = $original_slug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }

    /**
     * Process thumbnail image (URL or attachment ID)
     */
    private static function process_thumbnail( $thumbnail_value, $term_id ) {
        if ( empty( $thumbnail_value ) ) {
            return 0;
        }
        
        // If it's already an attachment ID
        if ( is_numeric( $thumbnail_value ) ) {
            $attachment_id = absint( $thumbnail_value );
            if ( get_post( $attachment_id ) && get_post_type( $attachment_id ) === 'attachment' ) {
                return $attachment_id;
            }
        }
        
        // If it's a URL, try to import it
        if ( filter_var( $thumbnail_value, FILTER_VALIDATE_URL ) ) {
            // Use the same image import logic as products
            $attachment_id = \PrimeLink\Helpers\ImageHelper::import_from_url( $thumbnail_value );
            return $attachment_id > 0 ? $attachment_id : 0;
        }
        
        return 0;
    }
}

