<?php

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

class AIEO_DMM_Supplier_Pods_Migrator {

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

    public static function source_taxonomy() {
        return (string) apply_filters('aieo_dmm_supplier_pods_migrator_taxonomy', 'supplier');
    }

    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_supplier_pods_migrate', 'nonce');
    }

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

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

    public static function run() {
        $out = array('processed' => 0, 'migrated' => 0, 'errors' => array());
        if (!self::has_pods_source()) {
            $out['errors'][] = __('Pods not active or supplier pod not found.', 'ai-eshop-optimizer');
            return $out;
        }
        $tax = self::source_taxonomy();
        $terms = get_terms(array('taxonomy' => $tax, 'hide_empty' => false, 'orderby' => 'term_id', 'order' => 'ASC'));
        if (is_wp_error($terms) || empty($terms)) { return $out; }

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

    public static function ajax_run() {
        self::gate();
        wp_send_json_success(self::run());
    }

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

        $patch = array(
            'email'                  => self::extract_text($pod->field('email')),
            
            
            'lead_time_days'         => self::extract_int($pod->field('lead_time')),
            'payment_terms_days'     => self::extract_int($pod->field('payment_type')),
            'special_discount_pct'   => (float) $pod->field('special_discount'),
            'supplier_owner_user_id' => self::extract_user_id($pod->field('supplier_owner')),
        );
        AIEO_DMM_Supplier_Extras_Data::save($taxonomy, $term_id, $patch);

        
        $brand_ids = self::extract_term_id_list($pod->field('related_brand'));
        AIEO_DMM_Term_Relations::set_targets(
            $taxonomy, $term_id, 'term', 'product_brand', $brand_ids
        );

        return true;
    }

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

    private static function extract_int($val) {
        if ($val === null || $val === '' || is_array($val)) { return null; }
        if (!is_numeric($val))                              { return null; }
        return (int) $val;
    }

    private static function extract_user_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], $val[0]['ID'])) { return (int) $val[0]['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))));
    }
}
