<?php
namespace PrimeLink\Modules\Tags;

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

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

    /**
     * Create a new product tag
     * 
     * @param array $tag_data Tag data
     * @return array Result with 'success', 'term_id', 'message'
     */
    public static function create_tag( $tag_data ) {
        $name = isset( $tag_data['name'] ) ? sanitize_text_field( $tag_data['name'] ) : '';
        
        if ( empty( $name ) ) {
            return array(
                'success' => false,
                'term_id' => 0,
                'message' => 'Tag name is required'
            );
        }
        
        // Generate slug if not provided
        $slug = ! empty( $tag_data['slug'] ) 
            ? sanitize_title( $tag_data['slug'] ) 
            : sanitize_title( $name );
        
        // Check if tag with same slug already exists
        $existing = get_term_by( 'slug', $slug, 'product_tag' );
        if ( $existing ) {
            return array(
                'success' => false,
                'term_id' => absint( $existing->term_id ),
                'message' => 'Tag with this slug already exists'
            );
        }
        
        // Prepare term data
        $term_data = array(
            'slug' => $slug,
        );
        
        // Add description if provided
        if ( ! empty( $tag_data['description'] ) ) {
            $term_data['description'] = wp_kses_post( $tag_data['description'] );
        }
        
        // Insert term
        $result = wp_insert_term( $name, 'product_tag', $term_data );
        
        if ( is_wp_error( $result ) ) {
            return array(
                'success' => false,
                'term_id' => 0,
                'message' => $result->get_error_message()
            );
        }
        
        $term_id = absint( $result['term_id'] );
        
        // Set thumbnail if provided
        if ( ! empty( $tag_data['thumbnail'] ) ) {
            $thumbnail_id = self::parse_thumbnail_id( $tag_data['thumbnail'] );
            if ( $thumbnail_id ) {
                update_term_meta( $term_id, 'thumbnail_id', $thumbnail_id );
            }
        }
        
        return array(
            'success' => true,
            'term_id' => $term_id,
            'message' => 'Tag created successfully'
        );
    }

    /**
     * Update an existing product tag
     * 
     * @param int $term_id Tag term ID
     * @param array $tag_data Tag data
     * @return array Result with 'success', 'message'
     */
    public static function update_tag( $term_id, $tag_data ) {
        $term_id = absint( $term_id );
        
        if ( ! $term_id ) {
            return array(
                'success' => false,
                'message' => 'Invalid tag ID'
            );
        }
        
        // Verify term exists and is a product tag
        $term = get_term( $term_id, 'product_tag' );
        if ( ! $term || is_wp_error( $term ) ) {
            return array(
                'success' => false,
                'message' => 'Tag not found'
            );
        }
        
        // Prepare update data
        $update_data = array();
        
        // Update name if provided
        if ( ! empty( $tag_data['name'] ) ) {
            $update_data['name'] = sanitize_text_field( $tag_data['name'] );
        }
        
        // Update slug if provided
        if ( ! empty( $tag_data['slug'] ) ) {
            $update_data['slug'] = sanitize_title( $tag_data['slug'] );
        }
        
        // Update description if provided
        if ( isset( $tag_data['description'] ) ) {
            $update_data['description'] = wp_kses_post( $tag_data['description'] );
        }
        
        // Update term
        if ( ! empty( $update_data ) ) {
            $result = wp_update_term( $term_id, 'product_tag', $update_data );
            
            if ( is_wp_error( $result ) ) {
                return array(
                    'success' => false,
                    'message' => $result->get_error_message()
                );
            }
        }
        
        // Update thumbnail if provided
        if ( isset( $tag_data['thumbnail'] ) ) {
            $thumbnail_id = self::parse_thumbnail_id( $tag_data['thumbnail'] );
            if ( $thumbnail_id ) {
                update_term_meta( $term_id, 'thumbnail_id', $thumbnail_id );
            } elseif ( $tag_data['thumbnail'] === '' || $tag_data['thumbnail'] === null ) {
                // Clear thumbnail if empty
                delete_term_meta( $term_id, 'thumbnail_id' );
            }
        }
        
        return array(
            'success' => true,
            'message' => 'Tag updated successfully'
        );
    }

    /**
     * Parse thumbnail ID from various formats
     * 
     * @param mixed $thumbnail Thumbnail value (ID, URL, or array)
     * @return int|false Attachment ID or false
     */
    private static function parse_thumbnail_id( $thumbnail ) {
        if ( empty( $thumbnail ) ) {
            return false;
        }
        
        // If it's already an ID
        if ( is_numeric( $thumbnail ) ) {
            $id = absint( $thumbnail );
            if ( get_post( $id ) && get_post_type( $id ) === 'attachment' ) {
                return $id;
            }
        }
        
        // If it's a URL, try to find attachment by URL
        if ( is_string( $thumbnail ) && ( strpos( $thumbnail, 'http' ) === 0 || strpos( $thumbnail, '//' ) === 0 ) ) {
            $attachment_id = attachment_url_to_postid( $thumbnail );
            if ( $attachment_id ) {
                return $attachment_id;
            }
        }
        
        // If it's an array, try to get ID
        if ( is_array( $thumbnail ) && isset( $thumbnail['id'] ) ) {
            return absint( $thumbnail['id'] );
        }
        
        return false;
    }
}

