<?php

namespace AIPT\Api\BulkGenerator\Common;

use AIPT\Utils\VariableConverter;

class ProductDataFormatter {
    public static function getFormattedProductData($product) {
        $data = [
            'name' => $product->get_name(),
            'sku' => $product->get_sku(),
            'price' => $product->get_price() ? $product->get_price() . ' ' . get_woocommerce_currency() : '',
            'regular_price' => $product->get_regular_price() ? $product->get_regular_price() . ' ' . get_woocommerce_currency() : '',
            'sale_price' => $product->get_sale_price() ? $product->get_sale_price() . ' ' . get_woocommerce_currency() : '',
            'categories' => '',
            'tags' => '',
            'attributes' => [],
            'formatted_attributes' => '',
            'custom_variables' => []
        ];

        $product_categories = wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names']);
        if (!empty($product_categories) && !is_wp_error($product_categories)) {
            $product_categories = array_map(function($category) {
                return html_entity_decode($category, ENT_QUOTES, 'UTF-8');
            }, $product_categories);
            $data['categories'] = implode(', ', $product_categories);
        }

        $product_tags = wp_get_post_terms($product->get_id(), 'product_tag', ['fields' => 'names']);
        if (!empty($product_tags) && !is_wp_error($product_tags)) {
            $data['tags'] = implode(', ', $product_tags);
        }

        $product_attributes = $product->get_attributes();
        $attribute_texts = [];
        
        if (!empty($product_attributes)) {
            foreach ($product_attributes as $attribute) {
                if ($attribute->get_visible()) {
                    $name = wc_attribute_label($attribute->get_name());
                    $values = [];
                    if ($attribute->is_taxonomy()) {
                        $terms = wp_get_post_terms($product->get_id(), $attribute->get_name(), ['fields' => 'names']);
                        if (!is_wp_error($terms)) {
                            $values = $terms;
                        }
                    } else {
                        $values = $attribute->get_options();
                    }
                    if (!empty($values)) {
                        $attribute_texts[] = $name . ": " . implode(', ', $values);
                        $data['attributes'][$name] = implode(', ', $values);
                    }
                }
            }
        }

        $default_fields = [
            'weight' => $product->get_weight(),
            'length' => $product->get_length(),
            'width' => $product->get_width(),
            'height' => $product->get_height()
        ];

        foreach ($default_fields as $field => $value) {
            if (!empty($value)) {
                $attribute_texts[] = ucfirst($field) . ": " . $value;
                $data['attributes'][$field] = $value;
            }
        }

        $data['formatted_attributes'] = !empty($attribute_texts) ? implode('; ', $attribute_texts) : '';

        $custom_variables = get_option('aipt_custom_variables', array());
        if (!empty($custom_variables)) {
            foreach ($custom_variables as $variable) {

                $field_value = self::getCustomFieldValue($product, $variable['field']);
                if ($field_value !== null) {
                    $data['custom_variables'][$variable['name']] = $field_value;

                    $attribute_texts[] = $variable['name'] . ": " . $field_value;
                    $data['attributes'][$variable['name']] = $field_value;
                    

                } 

            }

            if (!empty($attribute_texts)) {
                $data['formatted_attributes'] = implode('; ', $attribute_texts);
            }
        }

        return $data;
    }

    /**
     * Get custom field value from product
     *
     * @param \WC_Product $product Product object
     * @param string $field_key Field key
     * @return string|null Field value or null if not found
     */
    private static function getCustomFieldValue($product, $field_key) {

        try {

            $wc_fields = [
                'weight' => 'get_weight',
                'length' => 'get_length',
                'width' => 'get_width',
                'height' => 'get_height',
                'description' => 'get_description',
                'short_description' => 'get_short_description',
                'name' => 'get_name',
                'sku' => 'get_sku',
                'price' => 'get_price',
                'regular_price' => 'get_regular_price',
                'sale_price' => 'get_sale_price',
                'stock_status' => 'get_stock_status',
                'stock_quantity' => 'get_stock_quantity'
            ];

            if (isset($wc_fields[$field_key]) && method_exists($product, $wc_fields[$field_key])) {
                $value = $product->{$wc_fields[$field_key]}();
                if (!empty($value)) {

                    if ($field_key === 'description' || $field_key === 'short_description') {
                        $value = wp_strip_all_tags($value);
                    }
                    return VariableConverter::toString($value);
                }
            }

            if (function_exists('get_field')) {
                $acf_value = get_field($field_key, $product->get_id());
                if ($acf_value !== null && $acf_value !== false) {
                    return VariableConverter::formatCustomField($acf_value);
                }
            }

            $attribute = $product->get_attribute($field_key);
            if (!empty($attribute)) {
                return VariableConverter::toString($attribute);
            }

            $meta_value = get_post_meta($product->get_id(), $field_key, true);
            if (!empty($meta_value)) {
                return VariableConverter::toString($meta_value);
            }

            return null;

        } catch (\Exception $e) {

            return null;
        }
    }

    public static function getExistingDescriptions($product, $options) {
        $descriptions = [
            'short' => '',
            'full' => '',
            'tags' => ''
        ];

        if (isset($options['improveExistingDescription']) && $options['improveExistingDescription']) {
            $existing_short = $product->get_short_description();
            $existing_full = $product->get_description();

            if (!empty($existing_short)) {
                $descriptions['short'] = "\n\nYOU MUST CONSIDER THE EXISTING PRODUCT DESCRIPTION: " . wp_strip_all_tags($existing_short);
            }
            if (!empty($existing_full)) {
                $descriptions['full'] = "\n\nYOU MUST CONSIDER THE EXISTING PRODUCT DESCRIPTION: " . wp_strip_all_tags($existing_full);
            }
        }
        

        if (isset($options['keepExistingDescription']) && $options['keepExistingDescription'] && 
            isset($options['generateTags']) && $options['generateTags']) {
            

            $product_tags = wp_get_post_terms($product->get_id(), 'product_tag', ['fields' => 'names']);
            
            if (!empty($product_tags) && !is_wp_error($product_tags)) {
                $existing_tags = implode(', ', $product_tags);
                

                $additional_count = isset($options['additionalTagsCount']) ? intval($options['additionalTagsCount']) : 2;
                
                $descriptions['tags'] = "\n\nEXISTING TAGS: " . $existing_tags . 
                                      "\n\nYOU MUST GENERATE EXACTLY {$additional_count} NEW TAGS while considering existing tags for context.";
            }
        }

        return $descriptions;
    }

    public static function appendExistingDescription($product, $new_description, $type, $options) {
        if (isset($options['keepExistingDescription']) && $options['keepExistingDescription']) {
            $existing_description = $type === 'short' ? 
                $product->get_short_description() : 
                $product->get_description();

            if (!empty($existing_description)) {
                $position = isset($options['existingDescriptionPosition']) ? $options['existingDescriptionPosition'] : 'after';
                $before = isset($options['beforeContentText']) ? sanitize_text_field((string) $options['beforeContentText']) : '';
                $after  = isset($options['afterContentText'])  ? sanitize_text_field((string) $options['afterContentText'])  : '';
                $wrapped_new = $before . $new_description . $after;
                return $position === 'before' ?
                    $wrapped_new . "\n\n" . $existing_description :
                    $existing_description . "\n\n" . $wrapped_new;
            }
        }
        return $new_description;
    }
} 