<?php

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

class AIEO_Catalog_Import_Runner {

    
    public static function exchanger_mode($ui_mode) {
        switch ($ui_mode) {
            case 'create_update': return 'overwrite';            
            case 'update_only':   return 'update_only';          
            case 'new_only':
            default:              return 'create_with_term_meta'; 
        }
    }

    
    private static function ensure_deps() {
        if (!defined('AIEO_DIR')) { return; }
        if (!class_exists('AIEO_Exchanger_Product_Importer')) {
            foreach (array(
                'includes/dmm/exchanger/class-aieo-exchanger-term-resolver.php',
                'includes/dmm/exchanger/class-aieo-exchanger-image-resolver.php',
                'includes/dmm/exchanger/class-aieo-exchanger-product-importer.php',
            ) as $rel) {
                $p = AIEO_DIR . $rel;
                if (file_exists($p)) { require_once $p; }
            }
        }
        if (!class_exists('AIEO_Option_Groups_Schema')) {
            $p = AIEO_DIR . 'includes/dmm/option-groups/class-aieo-option-groups-schema.php';
            if (file_exists($p)) { require_once $p; }
        }
        if (!class_exists('AIEO_Option_Groups_Store')) {
            $p = AIEO_DIR . 'includes/dmm/option-groups/class-aieo-option-groups-store.php';
            if (file_exists($p)) { require_once $p; }
        }
    }

    
    public static function run_batch(AIEO_Catalog_Source $source, array $creds, array $options, array $category_map, $page, $page_size) {
        self::ensure_deps();
        if (!class_exists('AIEO_Exchanger_Product_Importer')) {
            return new WP_Error('aieo_no_exchanger', __('The product import engine is unavailable.', 'ai-eshop-optimizer'));
        }

        $res = $source->fetch_page($creds, $page, $page_size);
        if (is_wp_error($res)) { return $res; }

        $products  = (array) ($res['products'] ?? array());
        $ctx     = array('categories' => $category_map, 'options' => $options);
        $ui_mode = isset($options['mode']) ? (string) $options['mode'] : 'new_only';

        $tally = array('processed' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'errors' => 0, 'error_samples' => array());

        foreach ($products as $raw) {
            if (!is_array($raw)) { continue; }
            $tally['processed']++;

            $mapped  = $source->map_product($raw, $ctx);
            $payload = isset($mapped['payload']) && is_array($mapped['payload']) ? $mapped['payload'] : null;
            if (!$payload || empty($payload['match']['sku'])) {
                $tally['skipped']++;
                continue;
            }

            
            if (empty($options['images']))     { unset($payload['images'], $payload['gallery']); }
            if (empty($options['categories'])) { unset($payload['category_terms']); }

            if ($ui_mode === 'enrich') {
                
                
                
                
                $existing = AIEO_Exchanger_Product_Importer::find_existing_product_id($payload, 'sku');
                $r = ($existing > 0)
                    ? self::enrich_existing($existing, $payload)
                    : AIEO_Exchanger_Product_Importer::apply($payload, 'sku', 'create_with_term_meta');
            } elseif ($ui_mode === 'new_only') {
                if (AIEO_Exchanger_Product_Importer::find_existing_product_id($payload, 'sku') > 0) {
                    $tally['skipped']++;
                    continue;
                }
                $r = AIEO_Exchanger_Product_Importer::apply($payload, 'sku', 'create_with_term_meta');
            } else {
                $r = AIEO_Exchanger_Product_Importer::apply($payload, 'sku', self::exchanger_mode($ui_mode));
            }

            switch ($r['outcome']) {
                case 'created': $tally['created']++; break;
                case 'updated': $tally['updated']++; break;
                case 'skipped': $tally['skipped']++; break;
                case 'error':
                    $tally['errors']++;
                    if (count($tally['error_samples']) < 50) {
                        $tally['error_samples'][] = array('sku' => (string) $payload['match']['sku'], 'error' => (string) ($r['error'] ?? 'unknown'));
                    }
                    break;
            }

            
            if (!empty($options['option_groups']) && !empty($mapped['option_groups']) && (int) ($r['product_id'] ?? 0) > 0) {
                self::apply_option_groups((int) $r['product_id'], (array) $mapped['option_groups']);
            }
        }

        return array(
            'tally'       => $tally,
            'page'        => (int) ($res['page'] ?? $page),
            'total_pages' => max(1, (int) ($res['total_pages'] ?? 1)),
            'total'       => (int) ($res['total'] ?? 0),
        );
    }

    
    private static function enrich_existing($product_id, array $payload) {
        $product_id = (int) $product_id;
        $prod = function_exists('wc_get_product') ? wc_get_product($product_id) : null;
        if (!$prod) { return array('outcome' => 'error', 'product_id' => 0, 'error' => 'product lookup failed'); }
        $changed = false;

        
        $barcode = (string) ($payload['match']['barcode'] ?? '');
        if ($barcode !== '' && (string) get_post_meta($product_id, '_global_unique_id', true) === '') {
            update_post_meta($product_id, '_global_unique_id', $barcode);
            $changed = true;
        }

        
        if (!empty($payload['images'][0]['src']) && (int) $prod->get_image_id() === 0 && class_exists('AIEO_Exchanger_Image_Resolver')) {
            $aid = (int) AIEO_Exchanger_Image_Resolver::resolve((string) $payload['images'][0]['src'], $product_id, 'thumbnail_id');
            if ($aid > 0) { set_post_thumbnail($product_id, $aid); $changed = true; }
        }

        
        if (!empty($payload['category_terms']) && class_exists('AIEO_Exchanger_Term_Resolver')) {
            $resolution = AIEO_Exchanger_Term_Resolver::resolve_terms((array) $payload['category_terms'], 'product_cat', 'create_with_term_meta');
            if (!empty($resolution['term_ids'])) {
                wp_set_object_terms($product_id, array_map('intval', $resolution['term_ids']), 'product_cat', true); 
                $changed = true;
            }
        }

        
        if (!empty($payload['description']) && trim((string) $prod->get_description()) === '') {
            $prod->set_description((string) $payload['description']);
            $prod->save();
            $changed = true;
        }

        return array('outcome' => $changed ? 'updated' : 'skipped', 'product_id' => $product_id);
    }

    
    private static function apply_option_groups($product_id, array $groups) {
        if (!class_exists('AIEO_Option_Groups_Store')) { return; }
        
        if (class_exists('AIEO_Option_Groups_Schema')
            && get_option(AIEO_Option_Groups_Schema::OPTION_VERSION) !== AIEO_Option_Groups_Schema::SCHEMA_VERSION) {
            AIEO_Option_Groups_Schema::install();
        }
        global $wpdb;
        $g_tbl = $wpdb->prefix . 'aieo_option_groups';
        $o_tbl = $wpdb->prefix . 'aieo_options';

        $sort = 0;
        foreach ($groups as $g) {
            if (!is_array($g) || empty($g['name'])) { continue; }
            $gslug = sanitize_title((string) (!empty($g['slug']) ? $g['slug'] : $g['name']));
            $existing_gid = (int) $wpdb->get_var($wpdb->prepare("SELECT id FROM {$g_tbl} WHERE slug = %s LIMIT 1", $gslug));
            $group_id = (int) AIEO_Option_Groups_Store::upsert_group(array(
                'id'          => $existing_gid ?: 0,
                'slug'        => $gslug,
                'name'        => (string) $g['name'],
                'select_type' => (isset($g['select_type']) && $g['select_type'] === 'radio') ? 'radio' : 'checkbox',
                'min_select'  => isset($g['min_select']) ? (int) $g['min_select'] : 0,
                'max_select'  => isset($g['max_select']) ? (int) $g['max_select'] : 0,
            ));
            if ($group_id <= 0) { continue; }

            $osort = 0;
            foreach ((array) ($g['options'] ?? array()) as $opt) {
                if (!is_array($opt) || (empty($opt['label']) && (!isset($opt['label']) || $opt['label'] !== '0'))) { continue; }
                $oslug = sanitize_title((string) (!empty($opt['slug']) ? $opt['slug'] : $opt['label']));
                $existing_oid = (int) $wpdb->get_var($wpdb->prepare("SELECT id FROM {$o_tbl} WHERE group_id = %d AND slug = %s LIMIT 1", $group_id, $oslug));
                AIEO_Option_Groups_Store::upsert_option(array(
                    'id'               => $existing_oid ?: 0,
                    'group_id'         => $group_id,
                    'slug'             => $oslug,
                    'label'            => (string) $opt['label'],
                    'price_delta'      => isset($opt['price_delta']) ? (float) $opt['price_delta'] : 0,
                    'default_selected' => !empty($opt['default_selected']),
                    'sort_order'       => $osort++,
                ));
            }
            AIEO_Option_Groups_Store::assign_group($product_id, $group_id, $sort++);
        }
    }
}
