<?php

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

class AI_eShop_Chat_Content_Extractor {

    
    public static function extract_content($post_id, $post_type = null, $apply_deduplication = false) {
        
        if ($post_type && strpos($post_type, 'taxonomy:') === 0) {
            $taxonomy = str_replace('taxonomy:', '', $post_type);
            $content = self::extract_taxonomy_content($post_id, $taxonomy);
            
            return $apply_deduplication ? self::deduplicate_words($content) : $content;
        }

        $post = get_post($post_id);

        if (!$post) {
            return '';
        }

        if (!$post_type) {
            $post_type = $post->post_type;
        }

        
        $content = '';
        switch ($post_type) {
            case 'product':
            case 'product_variation':
                $content = self::extract_product_content($post);
                break;
            case 'post':
                $content = self::extract_post_content($post);
                break;
            case 'page':
                $content = self::extract_page_content($post);
                break;
            default:
                $content = self::extract_generic_content($post);
                break;
        }

        
        return $apply_deduplication ? self::deduplicate_words($content) : $content;
    }

    
    private static function extract_product_content($post) {
        $product = wc_get_product($post->ID);

        if (!$product) {
            return self::extract_generic_content($post);
        }

        $content_parts = array();

        
        $parent_id = $product->is_type('variation') ? $product->get_parent_id() : $post->ID;
        $is_variation = $product->is_type('variation');

        
        
        
        
        
        
        
        
        
        $vitals_helper = AI_eShop_Chat_Product_Vitals_Helper::get_instance();
        $vitals = null;
        if ($vitals_helper->is_vitals_table_available()) {
            $vitals_lookup_id = $is_variation ? $parent_id : $post->ID;
            $vitals = $vitals_helper->get_product_vitals($vitals_lookup_id);
        }

        
        $brand = null;
        if ($vitals && !empty($vitals->brand)) {
            $brand = $vitals->brand;
        } else {
            
            $brand_terms = wp_get_post_terms($parent_id, 'product_brand', array('fields' => 'names'));
            if (!empty($brand_terms) && !is_wp_error($brand_terms)) {
                $brand = $brand_terms[0];
            }
        }

        if ($brand) {
            $content_parts[] = '**BRAND: ' . strtoupper($brand) . '**';
        }

        
        $content_parts[] = '**PRODUCT: ' . strtoupper($product->get_name()) . '**';

        
        $short_description = null;
        if ($is_variation) {
            
            if ($vitals && !empty($vitals->short_description)) {
                $short_description = $vitals->short_description;
            } else {
                $parent_product = wc_get_product($parent_id);
                if ($parent_product) {
                    $short_description = $parent_product->get_short_description();
                }
            }
        } else {
            
            if ($vitals && !empty($vitals->short_description)) {
                $short_description = $vitals->short_description;
            } else {
                $short_description = $product->get_short_description();
            }
        }

        if ($short_description) {
            $content_parts[] = '**SUMMARY: ' . wp_strip_all_tags(strip_shortcodes($short_description)) . '**';
        }

        
        if ($vitals) {
            $needs_parts = array();

            if (!empty($vitals->primary_need)) {
                $needs_parts[] = '**PRIMARY NEED: ' . strtoupper($vitals->primary_need) . '**';
            }

            if (!empty($vitals->secondary_need)) {
                $needs_parts[] = '**SECONDARY NEED: ' . strtoupper($vitals->secondary_need) . '**';
            }

            if (!empty($vitals->other_needs)) {
                $needs_parts[] = '**OTHER NEEDS: ' . strtoupper($vitals->other_needs) . '**';
            }

            if (!empty($needs_parts)) {
                $content_parts = array_merge($content_parts, $needs_parts);
            }
        }

        
        if ($is_variation) {
            $variation_attributes = array();

            
            
            
            
            
            
            $attributes = $product->get_variation_attributes();
            foreach ($attributes as $attribute_name => $attribute_value) {
                if (empty($attribute_value)) {
                    continue;
                }

                $tax_candidate = preg_replace('/^attribute_/', '', $attribute_name);
                $display_name  = wc_attribute_label(preg_replace('/^pa_/', '', $tax_candidate));

                if (taxonomy_exists($tax_candidate)) {
                    $term = get_term_by('slug', $attribute_value, $tax_candidate);
                    if ($term) {
                        $attribute_value = $term->name;
                    }
                }
                $variation_attributes[] = $display_name . ': ' . $attribute_value;
            }

            if (!empty($variation_attributes)) {
                $content_parts[] = '**VARIATION: ' . strtoupper(implode(', ', $variation_attributes)) . '**';
            }
        }

        
        if ($vitals) {
            $category_parts = array();

            if (!empty($vitals->menu_category)) {
                $category_parts[] = 'Menu: ' . $vitals->menu_category;
            }

            if (!empty($vitals->head_category)) {
                $category_parts[] = 'Main Category: ' . $vitals->head_category;
            }

            if (!empty($vitals->sub_category)) {
                $category_parts[] = 'Sub-Category: ' . $vitals->sub_category;
            }

            if (!empty($category_parts)) {
                $content_parts[] = 'CATEGORIES: ' . implode(' > ', $category_parts);
            }
        }

        
        if ($product->get_sku()) {
            $content_parts[] = 'SKU: ' . $product->get_sku();
        }

        
        $categories = wp_get_post_terms($post->ID, 'product_cat', array('fields' => 'names'));
        if (!empty($categories) && !is_wp_error($categories)) {
            $content_parts[] = 'Categories: ' . implode(', ', $categories);
        }

        
        
        $primary_category = self::get_primary_category_name($parent_id);
        if ($primary_category) {
            $content_parts[] = 'Primary Category: ' . $primary_category;
        }

        
        $tags = wp_get_post_terms($post->ID, 'product_tag', array('fields' => 'names'));
        if (!empty($tags) && !is_wp_error($tags)) {
            $content_parts[] = 'Tags: ' . implode(', ', $tags);
        }

        
        if ($product->is_in_stock()) {
            $content_parts[] = 'In stock';

            $price = $product->get_price();
            if ($price) {
                $content_parts[] = 'Price: ' . wc_price($price);

                if ($product->is_on_sale()) {
                    $regular_price = $product->get_regular_price();
                    $content_parts[] = 'On sale! Regular price: ' . wc_price($regular_price);
                }
            }
        } else {
            $content_parts[] = 'Out of stock';
        }

        
        
        $description_post_id = $is_variation ? $parent_id : $post->ID;
        $description_post = get_post($description_post_id);

        if ($description_post && !empty($description_post->post_content)) {
            
            $full_description = wp_strip_all_tags(strip_shortcodes($description_post->post_content));
            if (!empty($full_description)) {
                $content_parts[] = 'FULL DESCRIPTION: ' . $full_description;
            }
        } else {
            
            if ($is_variation) {
                $parent_product = wc_get_product($parent_id);
                if ($parent_product) {
                    $parent_description = $parent_product->get_description();
                    if ($parent_description) {
                        $content_parts[] = 'Description: ' . wp_strip_all_tags(strip_shortcodes($parent_description));
                    }
                }
            } else {
                $description = $product->get_description();
                if ($description) {
                    $content_parts[] = 'Description: ' . wp_strip_all_tags(strip_shortcodes($description));
                }
            }
        }

        
        
        if ($product->is_type('variable') && !$is_variation) {
            
            $variation_count = 0;

            if ($vitals && isset($vitals->variation_count) && $vitals->variation_count > 0) {
                $variation_count = (int) $vitals->variation_count;
            } else {
                
                $variations = $product->get_children();
                $variation_count = count($variations);
            }

            if ($variation_count > 0) {
                
                $content_parts[] = '**AVAILABLE OPTIONS: ' . $variation_count . ' VARIATIONS**';

                
                $all_variation_terms = array();
                $attributes = $product->get_variation_attributes();

                foreach ($attributes as $attribute_name => $attribute_values) {
                    
                    $clean_name = str_replace('attribute_', '', $attribute_name);
                    $clean_name = str_replace('pa_', '', $clean_name);
                    $clean_name = wc_attribute_label($clean_name);

                    if (!empty($attribute_values) && is_array($attribute_values)) {
                        
                        if (taxonomy_exists($attribute_name)) {
                            $term_names = array();
                            foreach ($attribute_values as $slug) {
                                $term = get_term_by('slug', $slug, $attribute_name);
                                if ($term) {
                                    $term_names[] = $term->name;
                                }
                            }
                            if (!empty($term_names)) {
                                $all_variation_terms[] = $clean_name . ': ' . implode(', ', $term_names);
                            }
                        } else {
                            
                            $all_variation_terms[] = $clean_name . ': ' . implode(', ', $attribute_values);
                        }
                    }
                }

                if (!empty($all_variation_terms)) {
                    $content_parts[] = '**VARIATION OPTIONS: ' . implode(' | ', $all_variation_terms) . '**';
                }
            }
        }

        
        
        
        
        $attributes = $product->get_attributes();
        if (!empty($attributes)) {
            $attr_text = array();
            foreach ($attributes as $attribute) {
                if (!is_a($attribute, 'WC_Product_Attribute')) {
                    continue;
                }
                
                if ($product->is_type('variable') && $attribute->get_variation()) {
                    continue;
                }

                $values = array();
                if ($attribute->is_taxonomy()) {
                    $tax_name = $attribute->get_name();
                    $terms = wp_get_post_terms($post->ID, $tax_name, array('fields' => 'names'));
                    if (!is_wp_error($terms) && !empty($terms)) {
                        $values = $terms;
                    }
                } else {
                    $values = $attribute->get_options();
                }

                if (!empty($values)) {
                    $attr_text[] = wc_attribute_label($attribute->get_name()) . ': ' .
                                   implode(', ', $values);
                }
            }
            if (!empty($attr_text)) {
                $content_parts[] = 'Attributes: ' . implode('; ', $attr_text);
            }
        }

        
        
        $review_post_id = $is_variation ? $parent_id : $post->ID;
        $review_product = $is_variation ? wc_get_product($parent_id) : $product;

        if ($review_product) {
            $average_rating = $review_product->get_average_rating();
            $review_count = $review_product->get_review_count();

            if ($review_count > 0) {
                $content_parts[] = "Customer rating: {$average_rating}/5 based on {$review_count} reviews";

                
                $reviews = get_comments(array(
                    'post_id' => $review_post_id,
                    'status' => 'approve',
                    'number' => 5,
                    
                    'meta_query' => array(
                        array(
                            'key' => 'rating',
                            'value' => 4,
                            'compare' => '>=',
                            'type' => 'NUMERIC'
                        )
                    )
                ));

                if (!empty($reviews)) {
                    $review_texts = array();
                    foreach ($reviews as $review) {
                        $review_text = wp_strip_all_tags(strip_shortcodes($review->comment_content));
                        if (strlen($review_text) > 20) {
                            $review_texts[] = substr($review_text, 0, 200);
                        }
                    }
                    if (!empty($review_texts)) {
                        $content_parts[] = 'Customer reviews: ' . implode('. ', $review_texts);
                    }
                }
            }
        }

        
        $brand_terms = wp_get_post_terms($post->ID, 'product_brand', array('fields' => 'names'));
        if (!empty($brand_terms) && !is_wp_error($brand_terms)) {
            $content_parts[] = 'Brand: ' . implode(', ', $brand_terms);
        }

        
        
        
        
        
        
        $custom_taxonomies = get_object_taxonomies('product', 'objects');
        foreach ($custom_taxonomies as $tax) {
            if (in_array($tax->name, array('product_cat', 'product_tag', 'product_brand'), true)) {
                continue; 
            }
            if (strpos($tax->name, 'pa_') === 0) {
                continue; 
            }

            $terms = wp_get_post_terms($post->ID, $tax->name, array('fields' => 'names'));
            if (!empty($terms) && !is_wp_error($terms)) {
                $content_parts[] = $tax->label . ': ' . implode(', ', $terms);
            }
        }

        return implode('. ', $content_parts);
    }

    
    private static function extract_post_content($post) {
        $content_parts = array();

        
        $content_parts[] = 'Title: ' . $post->post_title;

        
        $categories = get_the_category($post->ID);
        if (!empty($categories)) {
            $cat_names = array_map(function($cat) {
                return $cat->name;
            }, $categories);
            $content_parts[] = 'Categories: ' . implode(', ', $cat_names);
        }

        
        $tags = get_the_tags($post->ID);
        if (!empty($tags)) {
            $tag_names = array_map(function($tag) {
                return $tag->name;
            }, $tags);
            $content_parts[] = 'Tags: ' . implode(', ', $tag_names);
        }

        
        if ($post->post_excerpt) {
            $content_parts[] = 'Excerpt: ' . wp_strip_all_tags(strip_shortcodes($post->post_excerpt));
        }

        
        $content = wp_strip_all_tags(strip_shortcodes($post->post_content));
        $content = preg_replace('/\s+/', ' ', $content);
        $words = explode(' ', $content);
        if (count($words) > 1000) {
            $content = implode(' ', array_slice($words, 0, 1000));
        }
        $content_parts[] = 'Content: ' . $content;

        return implode('. ', $content_parts);
    }

    
    private static function extract_page_content($post) {
        $content_parts = array();

        
        $content_parts[] = 'Page: ' . $post->post_title;

        
        $content = wp_strip_all_tags(strip_shortcodes($post->post_content));
        $content = preg_replace('/\s+/', ' ', $content);
        $words = explode(' ', $content);
        if (count($words) > 1500) {
            $content = implode(' ', array_slice($words, 0, 1500));
        }
        $content_parts[] = 'Content: ' . $content;

        return implode('. ', $content_parts);
    }

    
    private static function extract_generic_content($post) {
        $content_parts = array();

        
        $content_parts[] = $post->post_title;

        
        if ($post->post_excerpt) {
            $content_parts[] = wp_strip_all_tags(strip_shortcodes($post->post_excerpt));
        }

        
        $content = wp_strip_all_tags(strip_shortcodes($post->post_content));
        $content = preg_replace('/\s+/', ' ', $content);
        $content_parts[] = $content;

        
        $taxonomies = get_object_taxonomies($post->post_type);
        foreach ($taxonomies as $taxonomy) {
            $terms = wp_get_post_terms($post->ID, $taxonomy, array('fields' => 'names'));
            if (!empty($terms) && !is_wp_error($terms)) {
                $tax_obj = get_taxonomy($taxonomy);
                $content_parts[] = $tax_obj->label . ': ' . implode(', ', $terms);
            }
        }

        return implode('. ', $content_parts);
    }

    
    private static function get_primary_category_name($post_id) {
        $post_id = (int) $post_id;
        if ($post_id <= 0) {
            return null;
        }

        
        
        
        if (class_exists('AIEO_SEO_Store')) {
            $aieo_cat = (int) AIEO_SEO_Store::get_primary_cat_id('product', $post_id);
            if ($aieo_cat > 0) {
                $aieo_term = get_term($aieo_cat, 'product_cat');
                if ($aieo_term && !is_wp_error($aieo_term)) {
                    return $aieo_term->name;
                }
            }
        }

        
        global $wpdb;

        
        $table_name = $wpdb->prefix . 'aioseo_posts';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") !== $table_name) {
            return null;
        }

        
        $primary_term_json = $wpdb->get_var($wpdb->prepare(
            "SELECT primary_term FROM {$table_name} WHERE post_id = %d",
            $post_id
        ));

        if (!$primary_term_json) {
            return null;
        }

        
        $primary_term_data = json_decode($primary_term_json, true);
        if (!$primary_term_data || !isset($primary_term_data['product_cat'])) {
            return null;
        }

        $primary_term_id = $primary_term_data['product_cat'];

        
        $term = get_term($primary_term_id, 'product_cat');
        if (!$term || is_wp_error($term)) {
            return null;
        }

        return $term->name;
    }

    
    public static function extract_taxonomy_content($term_id, $taxonomy) {
        $term = get_term($term_id, $taxonomy);

        if (!$term || is_wp_error($term)) {
            return '';
        }

        $content_parts = array();

        
        $taxonomy_obj = get_taxonomy($taxonomy);
        if ($taxonomy_obj) {
            $content_parts[] = $taxonomy_obj->labels->singular_name . ': ' . $term->name;
        } else {
            $content_parts[] = 'Term: ' . $term->name;
        }

        
        if ($term->slug) {
            $content_parts[] = 'Slug: ' . $term->slug;
        }

        
        if ($term->description) {
            $content_parts[] = 'Description: ' . wp_strip_all_tags(strip_shortcodes($term->description));
        }

        
        if ($term->parent) {
            $parent = get_term($term->parent, $taxonomy);
            if ($parent && !is_wp_error($parent)) {
                $content_parts[] = 'Parent: ' . $parent->name;
            }
        }

        
        if ($taxonomy === 'product_cat' && function_exists('get_term_children')) {
            $children = get_term_children($term_id, $taxonomy);
            if (!empty($children) && !is_wp_error($children)) {
                $child_names = array();
                foreach ($children as $child_id) {
                    $child = get_term($child_id, $taxonomy);
                    if ($child && !is_wp_error($child)) {
                        $child_names[] = $child->name;
                    }
                }
                if (!empty($child_names)) {
                    $content_parts[] = 'Subcategories: ' . implode(', ', array_slice($child_names, 0, 10));
                }
            }
        }

        
        if (isset($term->count)) {
            $content_parts[] = 'Products: ' . $term->count;
        }

        
        if (strpos($taxonomy, 'pa_') === 0) {
            
            $attr_name = str_replace('pa_', '', $taxonomy);
            $content_parts[] = 'Attribute: ' . ucwords(str_replace('_', ' ', $attr_name));
        }

        return implode('. ', $content_parts);
    }

    
    public static function get_product_data($product_id) {
        $product = wc_get_product($product_id);

        if (!$product) {
            return null;
        }

        
        
        $is_variation = $product->is_type('variation');
        $parent_id = $is_variation ? $product->get_parent_id() : 0;
        $permalink_id = $is_variation ? $parent_id : $product_id;

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        $image_url = '';
        if ($is_variation) {
            global $wpdb;
            $vitals_helper = AI_eShop_Chat_Product_Vitals_Helper::get_instance();
            if ($vitals_helper->is_vitals_table_available()) {
                $vitals = $vitals_helper->get_product_vitals($product_id);
                if ($vitals && !empty($vitals->variation_swatch)) {
                    $image_url = $vitals->variation_swatch;
                }
            }

            if (!$image_url) {
                
                $variation_attrs = $product->get_variation_attributes();
                foreach ($variation_attrs as $attr_name => $attr_value) {
                    if (empty($attr_value)) {
                        continue;
                    }
                    $tax = preg_replace('/^attribute_/', '', $attr_name);
                    if (!taxonomy_exists($tax)) {
                        continue;
                    }
                    $term = get_term_by('slug', $attr_value, $tax);
                    if ($term) {
                        $att_id = get_term_meta($term->term_id, 'product_attribute_image', true);
                        if ($att_id) {
                            $url = wp_get_attachment_image_url($att_id, 'medium');
                            if ($url) {
                                $image_url = $url;
                                break;
                            }
                        }
                    }
                }
            }
        }

        if (!$image_url) {
            $image_url = get_the_post_thumbnail_url($product_id, 'medium');
        }
        if (!$image_url && $is_variation && $parent_id) {
            $image_url = get_the_post_thumbnail_url($parent_id, 'medium');
        }

        $data = array(
            'id' => $product_id,
            'title' => $product->get_name(),
            'type' => 'product',
            'url' => get_permalink($permalink_id),  
            'price' => $product->get_price(),
            'price_html' => $product->get_price_html(),
            'image' => $image_url,
            'in_stock' => $product->is_in_stock(),
            'on_sale' => $product->is_on_sale(),
            'rating' => $product->get_average_rating(),
            'review_count' => $product->get_review_count(),
            'short_description' => wp_trim_words($product->get_short_description(), 30),
            'categories' => wp_get_post_terms($product_id, 'product_cat', array('fields' => 'names')),
            'add_to_cart_url' => $product->add_to_cart_url(),
            'sku' => $product->get_sku()
        );

        
        if ($is_variation) {
            $variation_attributes = array();

            
            $attributes = $product->get_variation_attributes();
            foreach ($attributes as $attribute_name => $attribute_value) {
                $clean_name = str_replace(array('attribute_', 'pa_'), '', $attribute_name);
                $clean_name = wc_attribute_label($clean_name);

                if (!empty($attribute_value)) {
                    
                    if (taxonomy_exists($attribute_name)) {
                        $term = get_term_by('slug', $attribute_value, $attribute_name);
                        if ($term) {
                            $attribute_value = $term->name;
                        }
                    }
                    $variation_attributes[$clean_name] = $attribute_value;
                }
            }

            $data['variation_attributes'] = $variation_attributes;
            $data['is_variation'] = true;
            $data['parent_id'] = $parent_id;
        } else {
            $data['is_variation'] = false;
        }

        return $data;
    }

    
    public static function get_products_data($product_ids) {
        $products = array();

        foreach ($product_ids as $product_id) {
            $product_data = self::get_product_data($product_id);
            if ($product_data) {
                $products[] = $product_data;
            }
        }

        return $products;
    }

    
    public static function get_post_data($post_id) {
        $post = get_post($post_id);

        if (!$post || $post->post_status !== 'publish') {
            return false;
        }

        
        if ($post->post_type === 'product' || $post->post_type === 'product_variation') {
            return self::get_product_data($post_id);
        }

        
        $data = array(
            'id' => $post->ID,
            'title' => get_the_title($post->ID),
            'type' => $post->post_type,
            'url' => get_permalink($post->ID),
            'excerpt' => $post->post_excerpt ? wp_strip_all_tags(strip_shortcodes($post->post_excerpt)) : '',
            'content' => wp_trim_words(wp_strip_all_tags(strip_shortcodes($post->post_content)), 100, '...'),
            'date' => get_the_date('', $post->ID)
        );

        
        if ($post->post_type === 'post') {
            $categories = get_the_category($post->ID);
            if (!empty($categories)) {
                $data['categories'] = array_map(function($cat) {
                    return $cat->name;
                }, $categories);
            }

            
            $tags = get_the_tags($post->ID);
            if (!empty($tags)) {
                $data['tags'] = array_map(function($tag) {
                    return $tag->name;
                }, $tags);
            }
        }

        return $data;
    }

    
    public static function get_posts_data($post_ids) {
        $posts = array();

        foreach ($post_ids as $post_id) {
            $post_data = self::get_post_data($post_id);
            if ($post_data) {
                $posts[] = $post_data;
            }
        }

        return $posts;
    }

    
    private static function deduplicate_words($text) {
        
        $text = wp_strip_all_tags(strip_shortcodes($text));

        
        $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');

        
        $text = preg_replace('/\s+/u', ' ', trim($text));

        
        
        $text_lower = mb_strtolower($text, 'UTF-8');

        
        
        
        $words = preg_split('/\s+/u', $text_lower, -1, PREG_SPLIT_NO_EMPTY);

        
        $seen = array();
        $unique_words = array();

        foreach ($words as $word) {
            
            
            
            
            $clean_word = preg_replace('/[^\p{L}\p{N}]/u', '', $word);

            
            
            
            if (!empty($clean_word) && !isset($seen[$clean_word])) {
                $seen[$clean_word] = true;
                $unique_words[] = $word; 
            }
        }

        
        return implode(' ', $unique_words);
    }
}
