<?php
/**
 * ================================================================
 * LASSO IMPORTER - AJAX HANDLERS
 * ================================================================
 */

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

class DripBox_Lasso_Importer_AJAX {
    
    private $api_url = 'https://getdripbox.com/wp-json/dripbox/v1/convert-lasso';
    
    public function __construct() {
        add_action('wp_ajax_dripbox_collect_lasso', [$this, 'collect_lasso']);
        add_action('wp_ajax_dripbox_convert_batch', [$this, 'convert_batch']);
        add_action('wp_ajax_dripbox_replace_shortcodes', [$this, 'replace_shortcodes']);
    }
    
    /**
     * Collect all Lasso products
     */
    public function collect_lasso() {
        check_ajax_referer('dripbox_importer', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $importer = DripBox_Lasso_Importer::get_instance();
        $products = $importer->collect_lasso_data();
        
        wp_send_json_success([
            'products' => $products,
            'count' => count($products)
        ]);
    }
    
    /**
     * Convert one batch via server
     */
    public function convert_batch() {
        check_ajax_referer('dripbox_importer', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $batch = json_decode(stripslashes($_POST['batch']), true);
        $batch_index = intval($_POST['batch_index']);
        $license_key = get_option('dripbox_license_key', '');
        
        if (empty($license_key)) {
            wp_send_json_error(['message' => 'License key required']);
        }
        
        // Send batch to server
        $response = wp_remote_post($this->api_url, [
            'timeout' => 30,
            'headers' => ['Content-Type' => 'application/json'],
            'body' => json_encode([
                'license_key' => $license_key,
                'lasso_data' => $batch,
                'site_url' => get_site_url(),
                'batch_index' => $batch_index
            ])
        ]);
        
        if (is_wp_error($response)) {
            wp_send_json_error(['message' => $response->get_error_message()]);
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (!isset($body['success']) || !$body['success']) {
            wp_send_json_error($body);
        }
        
        // Save products locally
        $map = [];
        foreach ($body['products'] as $product) {
            $lasso_id = $product['lasso_id'];
            
            // Check if already imported (prevent duplicates)
            $existing = get_posts([
                'post_type' => 'dripbox_product',
                'meta_key' => '_imported_from_lasso_id',
                'meta_value' => $lasso_id,
                'posts_per_page' => 1,
                'post_status' => 'any'
            ]);
            
            if (!empty($existing)) {
                // Already imported, update instead
                $post_id = $existing[0]->ID;
                
                foreach ($product['meta'] as $key => $value) {
                    // Handle image ID to URL conversion
                    if ($key === 'image_url' && is_numeric($value)) {
                        $image_url = wp_get_attachment_url($value);
                        if ($image_url) {
                            $value = $image_url;
                        }
                    }
                    update_post_meta($post_id, $key, $value);
                }
            } else {
                // Create new product
                $post_id = wp_insert_post([
                    'post_type' => 'dripbox_product',
                    'post_title' => $product['title'],
                    'post_status' => 'publish'
                ]);
                
                foreach ($product['meta'] as $key => $value) {
                    // Handle image ID to URL conversion
                    if ($key === 'image_url' && is_numeric($value)) {
                        $image_url = wp_get_attachment_url($value);
                        if ($image_url) {
                            $value = $image_url;
                        }
                    }
                    update_post_meta($post_id, $key, $value);
                }
                
                // Mark as imported from Lasso
                update_post_meta($post_id, '_imported_from_lasso_id', $lasso_id);
            }
            
            $map[$lasso_id] = $post_id;
        }
        
        wp_send_json_success([
            'map' => $map,
            'count' => count($map)
        ]);
    }
    
    /**
     * Replace Lasso shortcodes with DripBox
     */
    public function replace_shortcodes() {
        check_ajax_referer('dripbox_importer', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $map = json_decode(stripslashes($_POST['map']), true);
        
        global $wpdb;
        
        // Get ALL posts that contain Lasso shortcodes
        $posts = $wpdb->get_results("
            SELECT ID, post_content
            FROM {$wpdb->posts}
            WHERE post_content LIKE '%[lasso%'
            AND post_status IN ('publish', 'draft', 'pending')
        ");
        
        $updated = 0;
        $errors = [];
        
        foreach ($posts as $post) {
            $content = $post->post_content;
            $original = $content;
            $modified = false;
            
            foreach ($map as $lasso_id => $dripbox_id) {
                // Pattern 1: [lasso rel="..." id="X"]
                $pattern1 = '/\[lasso\s+rel="[^"]*"\s+id="' . preg_quote($lasso_id, '/') . '"\]/i';
                if (preg_match($pattern1, $content)) {
                    $content = preg_replace(
                        $pattern1,
                        '[dripbox id="' . $dripbox_id . '"]',
                        $content
                    );
                    $modified = true;
                }
                
                // Pattern 2: [lasso id="X" rel="..."]
                $pattern2 = '/\[lasso\s+id="' . preg_quote($lasso_id, '/') . '"\s+rel="[^"]*"\]/i';
                if (preg_match($pattern2, $content)) {
                    $content = preg_replace(
                        $pattern2,
                        '[dripbox id="' . $dripbox_id . '"]',
                        $content
                    );
                    $modified = true;
                }
                
                // Pattern 3: [lasso id="X"] (simple)
                $pattern3 = '/\[lasso\s+id="' . preg_quote($lasso_id, '/') . '"\]/i';
                if (preg_match($pattern3, $content)) {
                    $content = preg_replace(
                        $pattern3,
                        '[dripbox id="' . $dripbox_id . '"]',
                        $content
                    );
                    $modified = true;
                }
            }
            
            // Update post if modified
            if ($modified && $content !== $original) {
                $result = wp_update_post([
                    'ID' => $post->ID,
                    'post_content' => $content
                ], true);
                
                if (is_wp_error($result)) {
                    $errors[] = 'Post ' . $post->ID . ': ' . $result->get_error_message();
                } else {
                    $updated++;
                }
            }
        }
        
        wp_send_json_success([
            'products_count' => count($map),
            'posts_updated' => $updated,
            'errors' => $errors
        ]);
    }
}

new DripBox_Lasso_Importer_AJAX();