<?php

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

class AIEO_DMM_Brand_Pods_Migrator {

    public static function register() {
        add_action('wp_ajax_aieo_brand_pods_migrate_audit', array(__CLASS__, 'ajax_audit'));
        add_action('wp_ajax_aieo_brand_pods_migrate_run',   array(__CLASS__, 'ajax_run'));
    }

    public static function source_taxonomy() {
        return (string) apply_filters('aieo_dmm_brand_pods_migrator_taxonomy', 'product_brand');
    }

    
    public static function has_pods_source() {
        if (!function_exists('pods')) { return false; }
        $pod = pods(self::source_taxonomy());
        return ($pod && $pod->valid());
    }

    private static function gate() {
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => 'permission_denied'), 403);
        }
        check_ajax_referer('aieo_brand_pods_migrate', 'nonce');
    }

    
    public static function audit() {
        global $wpdb;
        $tax = self::source_taxonomy();
        $term_count = (int) wp_count_terms(array('taxonomy' => $tax, 'hide_empty' => false));
        $migrated   = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM " . AIEO_DMM_Brand_Extras_Data::table() . "
              WHERE taxonomy = %s",
            $tax
        ));
        return array(
            'pods_active'    => self::has_pods_source(),
            'taxonomy'       => $tax,
            'brand_terms'    => $term_count,
            'already_migrated' => $migrated,
        );
    }

    public static function ajax_audit() {
        self::gate();
        wp_send_json_success(self::audit());
    }

    
    public static function run($batch_size = 50, $cursor = 0) {
        $batch_size = max(20, min(500, (int) $batch_size));
        $cursor     = max(0, (int) $cursor);

        $out = array(
            'processed' => 0, 'migrated' => 0, 'errors' => array(),
            'next_cursor' => null, 'done' => true,
        );

        if (!self::has_pods_source()) {
            $out['errors'][] = __('Pods not active or product_brand pod not found.', 'ai-eshop-optimizer');
            return $out;
        }

        $tax = self::source_taxonomy();
        $terms = get_terms(array(
            'taxonomy'   => $tax,
            'hide_empty' => false,
            'number'     => $batch_size,
            'orderby'    => 'term_id',
            'order'      => 'ASC',
            'meta_query' => array(),
            'fields'     => 'all',
            'exclude_tree' => array(),
            'include'    => array(),
            
            'meta_key'   => '',
        ));
        if (is_wp_error($terms) || empty($terms)) { return $out; }

        
        
        $batch = array();
        foreach ($terms as $t) {
            if ((int) $t->term_id <= $cursor) { continue; }
            $batch[] = $t;
            if (count($batch) >= $batch_size) { break; }
        }
        
        
        
        
        if (empty($batch)) {
            
            global $wpdb;
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT t.term_id FROM {$wpdb->terms} t
                  INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
                  WHERE tt.taxonomy = %s AND t.term_id > %d
                  ORDER BY t.term_id ASC
                  LIMIT %d",
                $tax, $cursor, $batch_size
            ));
            if (is_array($rows) && !empty($rows)) {
                foreach ($rows as $r) {
                    $term = get_term((int) $r->term_id, $tax);
                    if ($term && !is_wp_error($term)) { $batch[] = $term; }
                }
            }
        }
        if (empty($batch)) { return $out; }

        $next_cursor = $cursor;
        foreach ($batch as $term) {
            $out['processed']++;
            $next_cursor = max($next_cursor, (int) $term->term_id);

            try {
                if (self::migrate_one((int) $term->term_id, $tax)) {
                    $out['migrated']++;
                }
            } catch (\Throwable $e) {
                $out['errors'][] = sprintf(
                    
                    __('Brand #%1$d failed: %2$s', 'ai-eshop-optimizer'),
                    (int) $term->term_id, $e->getMessage()
                );
            }
        }

        $done = count($batch) < $batch_size;
        $out['done']        = $done;
        $out['next_cursor'] = $done ? null : $next_cursor;
        return $out;
    }

    public static function ajax_run() {
        self::gate();
        $batch_size = (int) (sanitize_text_field( wp_unslash( $_POST['batch_size'] ) ) ?? 50);
        $cursor     = (int) (sanitize_text_field( wp_unslash( $_POST['cursor'] ) )     ?? 0);
        wp_send_json_success(self::run($batch_size, $cursor));
    }

    
    private static function migrate_one($term_id, $taxonomy) {
        $pod = pods($taxonomy, $term_id);
        if (!$pod || !$pod->valid() || !$pod->exists()) { return false; }

        
        $patch = array();

        $patch['logo_image_id']    = self::extract_image_id($pod->field('brand_logo'));
        $patch['hero_image_id']    = null; 
        $patch['headline']         = ''; 
        $patch['history_text']     = self::extract_text($pod->field('brand_history'));
        $patch['ambassadors_text'] = self::extract_text($pod->field('brand_ambassadors'));
        $patch['importer_text']    = self::extract_text($pod->field('brand_importer'));
        $patch['website_url']      = self::extract_text($pod->field('brand_website'));
        $patch['promo']            = self::extract_bool($pod->field('promo'));
        $patch['priority']         = (int) $pod->field('brand_priority');
        $patch['bias']             = (float) $pod->field('brand_bias');
        $patch['footer_text']      = self::extract_text($pod->field('pods_footer_text'));
        $patch['supplier_term_id'] = self::extract_term_id($pod->field('supplier'));
        $patch['gallery_image_ids']= self::extract_image_id_list($pod->field('brand_multimedia_gallery'));

        
        
        
        AIEO_DMM_Brand_Extras_Data::save($taxonomy, $term_id, $patch);

        
        $cat_ids = self::extract_term_id_list($pod->field('related_categories'));
        AIEO_DMM_Term_Relations::set_targets(
            $taxonomy, $term_id, 'term', 'product_cat', $cat_ids
        );

        $post_ids = self::extract_post_id_list($pod->field('related_blog_posts'));
        AIEO_DMM_Term_Relations::set_targets(
            $taxonomy, $term_id, 'post', 'post', $post_ids
        );

        $campaign_ids = self::extract_post_id_list($pod->field('related_campaigns'));
        AIEO_DMM_Term_Relations::set_targets(
            $taxonomy, $term_id, 'post', 'campaign', $campaign_ids
        );

        return true;
    }

    
    private static function extract_image_id($val) {
        if (empty($val))                                         { return null; }
        if (is_numeric($val))                                    { return (int) $val; }
        if (is_array($val) && isset($val['ID']))                 { return (int) $val['ID']; }
        if (is_array($val) && isset($val[0]) && is_array($val[0]) && isset($val[0]['ID'])) {
            return (int) $val[0]['ID'];
        }
        return null;
    }

    
    private static function extract_image_id_list($val) {
        if (empty($val) || !is_array($val)) { return array(); }
        $out = array();
        
        if (isset($val['ID'])) { $val = array($val); }
        foreach ($val as $item) {
            if (is_numeric($item)) { $out[] = (int) $item; continue; }
            if (is_array($item) && isset($item['ID'])) { $out[] = (int) $item['ID']; }
        }
        return array_values(array_unique(array_filter(array_map('intval', $out))));
    }

    
    private static function extract_term_id($val) {
        if (empty($val))                                          { return null; }
        if (is_numeric($val))                                     { return (int) $val; }
        if (is_array($val) && isset($val['term_id']))             { return (int) $val['term_id']; }
        if (is_array($val) && isset($val[0]) && is_array($val[0]) && isset($val[0]['term_id'])) {
            return (int) $val[0]['term_id'];
        }
        return null;
    }

    private static function extract_term_id_list($val) {
        if (empty($val) || !is_array($val)) { return array(); }
        
        if (isset($val['term_id'])) { $val = array($val); }
        $out = array();
        foreach ($val as $item) {
            if (is_numeric($item)) { $out[] = (int) $item; continue; }
            if (is_array($item) && isset($item['term_id'])) { $out[] = (int) $item['term_id']; }
        }
        return array_values(array_unique(array_filter(array_map('intval', $out))));
    }

    private static function extract_post_id_list($val) {
        if (empty($val) || !is_array($val)) { return array(); }
        if (isset($val['ID']))     { $val = array($val); }
        $out = array();
        foreach ($val as $item) {
            if (is_numeric($item)) { $out[] = (int) $item; continue; }
            if (is_array($item) && isset($item['ID'])) { $out[] = (int) $item['ID']; }
        }
        return array_values(array_unique(array_filter(array_map('intval', $out))));
    }

    private static function extract_text($val) {
        if (is_array($val))  { return ''; }
        return (string) $val;
    }

    private static function extract_bool($val) {
        if (empty($val))                                  { return 0; }
        if (is_numeric($val))                             { return ((int) $val === 1) ? 1 : 0; }
        $s = strtolower(trim((string) $val));
        return in_array($s, array('1', 'yes', 'true', 'on'), true) ? 1 : 0;
    }
}
