<?php

/**
 * AI Magic WooCommerce Integration
 *
 * Provides AI-powered content generation for WooCommerce products
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.8
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */

/**
 * WooCommerce Integration Class
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 * @author     AI Magic <info@insya.com>
 */
class AI_Magic_WooCommerce
{
    /**
     * AI Provider instance
     *
     * @var object
     */
    private $ai_provider;

    /**
     * Constructor
     *
     * @since    1.0.8
     */
    public function __construct()
    {
        // Only initialize if WooCommerce is active
        if (!$this->is_woocommerce_active()) {
            return;
        }

        // Initialize hooks
        add_action('add_meta_boxes', array($this, 'add_product_metabox'));
        add_action('wp_ajax_ai_magic_generate_product_description', array($this, 'ajax_generate_description'));
        add_action('wp_ajax_ai_magic_generate_short_description', array($this, 'ajax_generate_short_description'));
        add_action('wp_ajax_ai_magic_generate_product_meta', array($this, 'ajax_generate_product_meta'));
        add_action('wp_ajax_ai_magic_bulk_generate_descriptions', array($this, 'ajax_bulk_generate'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    /**
     * Check if WooCommerce is active
     *
     * @since    1.0.8
     * @return   bool    True if WooCommerce is active
     */
    public function is_woocommerce_active()
    {
        return class_exists('WooCommerce') || in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')));
    }

    /**
     * Get AI provider instance
     *
     * @since    1.0.8
     * @return   object    AI provider instance
     */
    private function get_ai_provider()
    {
        if (!$this->ai_provider) {
            // Get the active provider
            $active_providers = array('openai', 'anthropic', 'google', 'openrouter');
            $provider = 'openai';

            foreach ($active_providers as $p) {
                if (get_option("ai_magic_{$p}_active", 'no') === 'yes') {
                    $provider = $p;
                    break;
                }
            }

            switch ($provider) {
                case 'anthropic':
                    require_once plugin_dir_path(__FILE__) . 'class-ai-magic-anthropic.php';
                    $this->ai_provider = new AI_Magic_Anthropic();
                    break;
                case 'google':
                    require_once plugin_dir_path(__FILE__) . 'class-ai-magic-google.php';
                    $this->ai_provider = new AI_Magic_Google();
                    break;
                case 'openrouter':
                    require_once plugin_dir_path(__FILE__) . 'class-ai-magic-openrouter.php';
                    $this->ai_provider = new AI_Magic_OpenRouter();
                    break;
                default:
                    require_once plugin_dir_path(__FILE__) . 'class-ai-magic-openai.php';
                    $this->ai_provider = new AI_Magic_OpenAI();
                    break;
            }
        }

        return $this->ai_provider;
    }

    /**
     * Add metabox to WooCommerce product edit page
     *
     * @since    1.0.8
     */
    public function add_product_metabox()
    {
        add_meta_box(
            'ai-magic-woocommerce',
            '✨ AI Magic - Product Content',
            array($this, 'render_metabox'),
            'product',
            'normal',
            'high'
        );
    }

    /**
     * Render product metabox
     *
     * @since    1.0.8
     * @param    WP_Post    $post    Current post object
     */
    public function render_metabox($post)
    {
        wp_nonce_field('ai_magic_woo_nonce', 'ai_magic_woo_nonce');

        $product = wc_get_product($post->ID);
        if (!$product) {
            echo '<p>' . esc_html__('Product not found.', 'ai_magic') . '</p>';
            return;
        }

        ?>
        <div class="ai-magic-woo-container">
            <style>
                .ai-magic-woo-container {
                    padding: 15px 0;
                }

                .ai-magic-woo-actions {
                    display: flex;
                    gap: 10px;
                    flex-wrap: wrap;
                    margin-bottom: 15px;
                }

                .ai-magic-woo-btn {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: #fff;
                    border: none;
                    padding: 10px 16px;
                    border-radius: 6px;
                    font-size: 13px;
                    font-weight: 600;
                    cursor: pointer;
                    display: inline-flex;
                    align-items: center;
                    gap: 6px;
                    transition: all 0.2s;
                }

                .ai-magic-woo-btn:hover {
                    transform: translateY(-1px);
                    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
                }

                .ai-magic-woo-btn:disabled {
                    opacity: 0.6;
                    cursor: not-allowed;
                    transform: none;
                }

                .ai-magic-woo-btn.secondary {
                    background: #f0f0f0;
                    color: #333;
                }

                .ai-magic-woo-options {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                    gap: 15px;
                    margin-bottom: 15px;
                    padding: 15px;
                    background: #f9f9f9;
                    border-radius: 6px;
                }

                .ai-magic-woo-option label {
                    display: block;
                    font-weight: 600;
                    margin-bottom: 5px;
                    font-size: 12px;
                    color: #555;
                }

                .ai-magic-woo-option select,
                .ai-magic-woo-option input {
                    width: 100%;
                    padding: 8px 10px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    font-size: 13px;
                }

                .ai-magic-woo-result {
                    display: none;
                    margin-top: 15px;
                    padding: 15px;
                    background: #fff;
                    border: 1px solid #ddd;
                    border-radius: 6px;
                }

                .ai-magic-woo-result.active {
                    display: block;
                }

                .ai-magic-woo-result-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 10px;
                }

                .ai-magic-woo-result-content {
                    max-height: 300px;
                    overflow-y: auto;
                    padding: 10px;
                    background: #f9f9f9;
                    border-radius: 4px;
                }

                .ai-magic-woo-loading {
                    display: none;
                    text-align: center;
                    padding: 20px;
                    color: #666;
                }

                .ai-magic-woo-loading.active {
                    display: block;
                }
            </style>

            <div class="ai-magic-woo-options">
                <div class="ai-magic-woo-option">
                    <label><?php esc_html_e('Language', 'ai_magic'); ?></label>
                    <select id="ai-magic-woo-language">
                        <option value="en">English</option>
                        <option value="tr">Turkish</option>
                        <option value="es">Spanish</option>
                        <option value="fr">French</option>
                        <option value="de">German</option>
                    </select>
                </div>
                <div class="ai-magic-woo-option">
                    <label><?php esc_html_e('Tone', 'ai_magic'); ?></label>
                    <select id="ai-magic-woo-tone">
                        <option value="professional">Professional</option>
                        <option value="casual">Casual</option>
                        <option value="persuasive">Persuasive</option>
                        <option value="enthusiastic">Enthusiastic</option>
                    </select>
                </div>
                <div class="ai-magic-woo-option">
                    <label><?php esc_html_e('Description Length', 'ai_magic'); ?></label>
                    <select id="ai-magic-woo-length">
                        <option value="short">Short (~100 words)</option>
                        <option value="medium" selected>Medium (~200 words)</option>
                        <option value="long">Long (~400 words)</option>
                    </select>
                </div>
                <div class="ai-magic-woo-option">
                    <label><?php esc_html_e('Focus Keywords', 'ai_magic'); ?></label>
                    <input type="text" id="ai-magic-woo-keywords" placeholder="keyword1, keyword2">
                </div>
            </div>

            <div class="ai-magic-woo-actions">
                <button type="button" class="ai-magic-woo-btn" id="ai-magic-generate-description">
                    📝 <?php esc_html_e('Generate Description', 'ai_magic'); ?>
                </button>
                <button type="button" class="ai-magic-woo-btn" id="ai-magic-generate-short-description">
                    📋 <?php esc_html_e('Generate Short Description', 'ai_magic'); ?>
                </button>
                <button type="button" class="ai-magic-woo-btn secondary" id="ai-magic-generate-seo">
                    🔍 <?php esc_html_e('Generate SEO Meta', 'ai_magic'); ?>
                </button>
            </div>

            <div class="ai-magic-woo-loading" id="ai-magic-woo-loading">
                <span class="spinner is-active" style="float: none; margin: 0 10px 0 0;"></span>
                <?php esc_html_e('Generating content...', 'ai_magic'); ?>
            </div>

            <div class="ai-magic-woo-result" id="ai-magic-woo-result">
                <div class="ai-magic-woo-result-header">
                    <strong id="ai-magic-woo-result-title"></strong>
                    <div>
                        <button type="button" class="button"
                            id="ai-magic-woo-insert"><?php esc_html_e('Insert', 'ai_magic'); ?></button>
                        <button type="button" class="button"
                            id="ai-magic-woo-copy"><?php esc_html_e('Copy', 'ai_magic'); ?></button>
                    </div>
                </div>
                <div class="ai-magic-woo-result-content" id="ai-magic-woo-result-content"></div>
            </div>

            <input type="hidden" id="ai-magic-woo-product-id" value="<?php echo esc_attr($post->ID); ?>">
            <input type="hidden" id="ai-magic-woo-product-title" value="<?php echo esc_attr($product->get_name()); ?>">
            <input type="hidden" id="ai-magic-woo-result-type" value="">
        </div>

        <script>
            jQuery(document).ready(function ($) {
                const productId = $('#ai-magic-woo-product-id').val();
                const productTitle = $('#ai-magic-woo-product-title').val();

                function getOptions() {
                    return {
                        language: $('#ai-magic-woo-language').val(),
                        tone: $('#ai-magic-woo-tone').val(),
                        length: $('#ai-magic-woo-length').val(),
                        keywords: $('#ai-magic-woo-keywords').val()
                    };
                }

                function showLoading() {
                    $('#ai-magic-woo-loading').addClass('active');
                    $('#ai-magic-woo-result').removeClass('active');
                    $('.ai-magic-woo-btn').prop('disabled', true);
                }

                function hideLoading() {
                    $('#ai-magic-woo-loading').removeClass('active');
                    $('.ai-magic-woo-btn').prop('disabled', false);
                }

                function showResult(title, content, type) {
                    $('#ai-magic-woo-result-title').text(title);
                    $('#ai-magic-woo-result-content').html(content);
                    $('#ai-magic-woo-result-type').val(type);
                    $('#ai-magic-woo-result').addClass('active');
                }

                // Generate Description
                $('#ai-magic-generate-description').on('click', function () {
                    showLoading();
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'ai_magic_generate_product_description',
                            product_id: productId,
                            title: productTitle,
                            options: getOptions(),
                            nonce: '<?php echo wp_create_nonce('ai_magic_woo_nonce'); ?>'
                        },
                        success: function (response) {
                            hideLoading();
                            if (response.success) {
                                showResult('Generated Description', response.data.content, 'description');
                            } else {
                                alert('Error: ' + response.data);
                            }
                        },
                        error: function () {
                            hideLoading();
                            alert('An error occurred');
                        }
                    });
                });

                // Generate Short Description
                $('#ai-magic-generate-short-description').on('click', function () {
                    showLoading();
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'ai_magic_generate_short_description',
                            product_id: productId,
                            title: productTitle,
                            options: getOptions(),
                            nonce: '<?php echo wp_create_nonce('ai_magic_woo_nonce'); ?>'
                        },
                        success: function (response) {
                            hideLoading();
                            if (response.success) {
                                showResult('Generated Short Description', response.data.content, 'short_description');
                            } else {
                                alert('Error: ' + response.data);
                            }
                        },
                        error: function () {
                            hideLoading();
                            alert('An error occurred');
                        }
                    });
                });

                // Generate SEO Meta
                $('#ai-magic-generate-seo').on('click', function () {
                    showLoading();
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'ai_magic_generate_product_meta',
                            product_id: productId,
                            title: productTitle,
                            options: getOptions(),
                            nonce: '<?php echo wp_create_nonce('ai_magic_woo_nonce'); ?>'
                        },
                        success: function (response) {
                            hideLoading();
                            if (response.success) {
                                const content = '<p><strong>Meta Title:</strong><br>' + response.data.meta_title + '</p>' +
                                    '<p><strong>Meta Description:</strong><br>' + response.data.meta_description + '</p>' +
                                    '<p><strong>Focus Keywords:</strong><br>' + response.data.keywords + '</p>';
                                showResult('Generated SEO Meta', content, 'seo');
                            } else {
                                alert('Error: ' + response.data);
                            }
                        },
                        error: function () {
                            hideLoading();
                            alert('An error occurred');
                        }
                    });
                });

                // Insert content
                $('#ai-magic-woo-insert').on('click', function () {
                    const type = $('#ai-magic-woo-result-type').val();
                    const content = $('#ai-magic-woo-result-content').html();

                    if (type === 'description') {
                        // Insert into main description (TinyMCE)
                        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                            tinyMCE.get('content').setContent(content);
                        }
                    } else if (type === 'short_description') {
                        // Insert into short description
                        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                            tinyMCE.get('excerpt').setContent(content);
                        } else {
                            $('#excerpt').val(content.replace(/<[^>]*>/g, ''));
                        }
                    }

                    alert('Content inserted!');
                });

                // Copy content
                $('#ai-magic-woo-copy').on('click', function () {
                    const content = $('#ai-magic-woo-result-content').text();
                    navigator.clipboard.writeText(content).then(function () {
                        alert('Copied to clipboard!');
                    });
                });
            });
        </script>
        <?php
    }

    /**
     * Enqueue scripts for WooCommerce pages
     *
     * @since    1.0.8
     * @param    string    $hook    Current admin page
     */
    public function enqueue_scripts($hook)
    {
        if (!in_array($hook, array('post.php', 'post-new.php'))) {
            return;
        }

        global $post;
        if (!$post || $post->post_type !== 'product') {
            return;
        }

        // Scripts are inline in metabox for simplicity
    }

    /**
     * Generate product description via AJAX
     *
     * @since    1.0.8
     */
    public function ajax_generate_description()
    {
        check_ajax_referer('ai_magic_woo_nonce', 'nonce');

        if (!current_user_can('edit_products')) {
            wp_send_json_error(__('Insufficient permissions', 'ai_magic'));
        }

        $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
        $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
        $options = isset($_POST['options']) ? array_map('sanitize_text_field', $_POST['options']) : array();

        if (empty($title)) {
            wp_send_json_error(__('Product title is required', 'ai_magic'));
        }

        $result = $this->generateProductDescription($title, array(), '', $options);

        if ($result['type'] === 'success') {
            wp_send_json_success(array('content' => $result['data']));
        } else {
            wp_send_json_error($result['message']);
        }
    }

    /**
     * Generate short description via AJAX
     *
     * @since    1.0.8
     */
    public function ajax_generate_short_description()
    {
        check_ajax_referer('ai_magic_woo_nonce', 'nonce');

        if (!current_user_can('edit_products')) {
            wp_send_json_error(__('Insufficient permissions', 'ai_magic'));
        }

        $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
        $options = isset($_POST['options']) ? array_map('sanitize_text_field', $_POST['options']) : array();

        if (empty($title)) {
            wp_send_json_error(__('Product title is required', 'ai_magic'));
        }

        $result = $this->generateShortDescription($title, $options);

        if ($result['type'] === 'success') {
            wp_send_json_success(array('content' => $result['data']));
        } else {
            wp_send_json_error($result['message']);
        }
    }

    /**
     * Generate product meta via AJAX
     *
     * @since    1.0.8
     */
    public function ajax_generate_product_meta()
    {
        check_ajax_referer('ai_magic_woo_nonce', 'nonce');

        if (!current_user_can('edit_products')) {
            wp_send_json_error(__('Insufficient permissions', 'ai_magic'));
        }

        $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
        $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
        $options = isset($_POST['options']) ? array_map('sanitize_text_field', $_POST['options']) : array();

        if (empty($title)) {
            wp_send_json_error(__('Product title is required', 'ai_magic'));
        }

        $result = $this->generateProductMeta($product_id, $title, $options);

        if ($result['type'] === 'success') {
            wp_send_json_success($result['data']);
        } else {
            wp_send_json_error($result['message']);
        }
    }

    /**
     * Generate product description
     *
     * @since    1.0.8
     * @param    string    $title       Product title
     * @param    array     $features    Product features
     * @param    string    $category    Product category
     * @param    array     $options     Generation options
     * @return   array                  Response array
     */
    public function generateProductDescription($title, $features = array(), $category = '', $options = array())
    {
        $language = isset($options['language']) ? $options['language'] : 'en';
        $tone = isset($options['tone']) ? $options['tone'] : 'professional';
        $length = isset($options['length']) ? $options['length'] : 'medium';
        $keywords = isset($options['keywords']) ? $options['keywords'] : '';

        $word_count = array(
            'short' => 100,
            'medium' => 200,
            'long' => 400
        );

        $prompt = sprintf(
            'Write a compelling e-commerce product description for "%s" in %s.

Requirements:
- Tone: %s
- Length: approximately %d words
- Focus on benefits, not just features
- Include a call-to-action
- Format with HTML paragraphs and lists where appropriate
%s%s

Make it persuasive and SEO-friendly.',
            $title,
            $language === 'en' ? 'English' : $language,
            $tone,
            $word_count[$length],
            !empty($features) ? "\n- Features to highlight: " . implode(', ', $features) : '',
            !empty($keywords) ? "\n- SEO Keywords: " . $keywords : ''
        );

        $ai = $this->get_ai_provider();
        $response = $ai->generateText($prompt);

        if ($response['type'] === 'success') {
            $content = isset($response['data']['post_content']) ? $response['data']['post_content'] : '';
            if (empty($content) && isset($response['data']['text'])) {
                $content = $response['data']['text'];
            }

            return array(
                'type' => 'success',
                'data' => $content
            );
        }

        return $response;
    }

    /**
     * Generate short description
     *
     * @since    1.0.8
     * @param    string    $title      Product title
     * @param    array     $options    Generation options
     * @return   array                 Response array
     */
    public function generateShortDescription($title, $options = array())
    {
        $language = isset($options['language']) ? $options['language'] : 'en';
        $tone = isset($options['tone']) ? $options['tone'] : 'professional';

        $prompt = sprintf(
            'Write a brief, compelling product excerpt for "%s" in %s.

Requirements:
- Maximum 2-3 sentences (50-80 words)
- Tone: %s
- Highlight the main benefit
- Create urgency or interest
- No HTML formatting

Return only the excerpt text.',
            $title,
            $language === 'en' ? 'English' : $language,
            $tone
        );

        $ai = $this->get_ai_provider();
        $response = $ai->generateText($prompt);

        if ($response['type'] === 'success') {
            $content = isset($response['data']['post_content']) ? $response['data']['post_content'] : '';
            if (empty($content) && isset($response['data']['text'])) {
                $content = $response['data']['text'];
            }

            // Strip any HTML
            $content = wp_strip_all_tags($content);

            return array(
                'type' => 'success',
                'data' => $content
            );
        }

        return $response;
    }

    /**
     * Generate product SEO meta
     *
     * @since    1.0.8
     * @param    int       $product_id    Product ID
     * @param    string    $title         Product title
     * @param    array     $options       Generation options
     * @return   array                    Response array
     */
    public function generateProductMeta($product_id, $title = '', $options = array())
    {
        if (empty($title) && $product_id) {
            $product = wc_get_product($product_id);
            if ($product) {
                $title = $product->get_name();
            }
        }

        if (empty($title)) {
            return array(
                'type' => 'error',
                'message' => __('Product title is required', 'ai_magic')
            );
        }

        $language = isset($options['language']) ? $options['language'] : 'en';

        $prompt = sprintf(
            'Generate SEO metadata for an e-commerce product titled "%s" in %s.

Return in this exact format:
META_TITLE: [60 characters max, include brand if relevant]
META_DESCRIPTION: [155 characters max, compelling and action-oriented]
KEYWORDS: [5 focus keywords, comma separated]

Only return the metadata, no additional text.',
            $title,
            $language === 'en' ? 'English' : $language
        );

        $ai = $this->get_ai_provider();
        $response = $ai->generateText($prompt);

        if ($response['type'] === 'success') {
            $content = isset($response['data']['post_content']) ? $response['data']['post_content'] : '';
            if (empty($content) && isset($response['data']['text'])) {
                $content = $response['data']['text'];
            }

            // Parse the response
            $meta_title = '';
            $meta_description = '';
            $keywords = '';

            if (preg_match('/META_TITLE:\s*(.+?)(?:\n|$)/i', $content, $matches)) {
                $meta_title = trim($matches[1]);
            }
            if (preg_match('/META_DESCRIPTION:\s*(.+?)(?:\n|$)/i', $content, $matches)) {
                $meta_description = trim($matches[1]);
            }
            if (preg_match('/KEYWORDS:\s*(.+?)(?:\n|$)/i', $content, $matches)) {
                $keywords = trim($matches[1]);
            }

            return array(
                'type' => 'success',
                'data' => array(
                    'meta_title' => $meta_title,
                    'meta_description' => $meta_description,
                    'keywords' => $keywords
                )
            );
        }

        return $response;
    }

    /**
     * Generate product attributes suggestions
     *
     * @since    1.0.8
     * @param    string    $title       Product title
     * @param    string    $category    Product category
     * @return   array                  Response array
     */
    public function generateProductAttributes($title, $category = '')
    {
        $prompt = sprintf(
            'Suggest product attributes for an e-commerce product titled "%s"%s.

Return 5-8 relevant product attributes in this format:
ATTRIBUTE_NAME: Suggested values (comma separated)

Example:
Color: Red, Blue, Green, Black
Size: S, M, L, XL

Only return attributes relevant to this type of product.',
            $title,
            !empty($category) ? " in the category \"$category\"" : ''
        );

        $ai = $this->get_ai_provider();
        $response = $ai->generateText($prompt);

        if ($response['type'] === 'success') {
            $content = isset($response['data']['post_content']) ? $response['data']['post_content'] : '';
            if (empty($content) && isset($response['data']['text'])) {
                $content = $response['data']['text'];
            }

            // Parse attributes
            $attributes = array();
            $lines = explode("\n", $content);

            foreach ($lines as $line) {
                if (preg_match('/^([^:]+):\s*(.+)$/i', trim($line), $matches)) {
                    $attr_name = trim($matches[1]);
                    $attr_values = array_map('trim', explode(',', $matches[2]));
                    $attributes[$attr_name] = $attr_values;
                }
            }

            return array(
                'type' => 'success',
                'data' => $attributes
            );
        }

        return $response;
    }

    /**
     * Bulk generate descriptions for multiple products
     *
     * @since    1.0.8
     * @param    array     $product_ids    Array of product IDs
     * @param    array     $options        Generation options
     * @return   array                     Results array
     */
    public function bulkGenerateDescriptions($product_ids, $options = array())
    {
        $results = array();

        foreach ($product_ids as $product_id) {
            $product = wc_get_product($product_id);
            if (!$product) {
                $results[$product_id] = array(
                    'type' => 'error',
                    'message' => __('Product not found', 'ai_magic')
                );
                continue;
            }

            $title = $product->get_name();
            $result = $this->generateProductDescription($title, array(), '', $options);

            if ($result['type'] === 'success') {
                // Update product description
                $product->set_description($result['data']);
                $product->save();
            }

            $results[$product_id] = $result;

            // Rate limiting
            sleep(1);
        }

        return $results;
    }
}

// Initialize if WooCommerce is active
add_action('plugins_loaded', function () {
    new AI_Magic_WooCommerce();
});
