<?php

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

class AIEO_MOI_Legacy_Skroutz_Migrator {

    
    const LEGACY_MARKER_KEY = 'wpslash_skroutz_smart_cart_order';

    
    const SKIP_MARKER_KEY = '_aieo_moi_legacy_migration_skipped';

    
    const FIELD_MAP = array(
        'wpslash_skroutz_smart_cart_order_code'                    => '_aieo_moi_remote_order_id',
        'wpslash_skroutz_smart_cart_order_state'                   => '_aieo_moi_state',
        'wpslash_skroutz_smart_cart_order_courier'                 => '_aieo_moi_courier',
        'wpslash_skroutz_smart_cart_order_courier_voucher'         => '_aieo_moi_voucher_url',
        'wpslash_skroutz_smart_cart_order_courier_tracking_codes'  => '_aieo_moi_tracking_codes',
    );

    
    public static function count_candidates($exclude_vendor_id = 0) {
        return (int) self::run_candidate_query((int) $exclude_vendor_id, 0, 0, true);
    }

    
    public static function find_candidate_ids($exclude_vendor_id, $offset = 0, $limit = 50) {
        return (array) self::run_candidate_query((int) $exclude_vendor_id, (int) $offset, (int) $limit, false);
    }

    
    private static function run_candidate_query($exclude_vendor_id, $offset, $limit, $count_only) {
        global $wpdb;

        $links_tbl = AIEO_MOI_Schema::tables()['order_links'];

        
        
        
        $hpos = false;
        if (class_exists('Automattic\\WooCommerce\\Utilities\\OrderUtil')
            && method_exists('Automattic\\WooCommerce\\Utilities\\OrderUtil', 'custom_orders_table_usage_is_enabled')) {
            $hpos = (bool) \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
        }
        if (!$hpos) {
            $hpos_tbl = $wpdb->prefix . 'wc_orders_meta';
            $hpos = (string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $hpos_tbl)) === $hpos_tbl
                && get_option('woocommerce_custom_orders_table_enabled') === 'yes';
        }

        $select_col = $count_only ? 'COUNT(DISTINCT o.id)' : 'DISTINCT o.id';

        
        
        $link_exclusion = '';
        $params         = array(self::LEGACY_MARKER_KEY, self::SKIP_MARKER_KEY);
        if ($exclude_vendor_id > 0) {
            $link_exclusion = "AND o.id NOT IN (
                SELECT wc_order_id FROM {$links_tbl} WHERE vendor_id = %d
            )";
            $params[] = $exclude_vendor_id;
        }

        if ($hpos) {
            $orders_tbl     = $wpdb->prefix . 'wc_orders';
            $orders_meta    = $wpdb->prefix . 'wc_orders_meta';
            $order_clause   = $count_only ? '' : 'ORDER BY o.date_created_gmt ASC, o.id ASC';
            $limit_clause   = '';
            if (!$count_only && $limit > 0) {
                $limit_clause = $wpdb->prepare('LIMIT %d OFFSET %d', (int) $limit, max(0, (int) $offset));
            } elseif (!$count_only && $limit === -1) {
                
                
            }

            $sql = "SELECT {$select_col}
                    FROM {$orders_tbl} o
                    INNER JOIN {$orders_meta} m_marker
                        ON m_marker.order_id = o.id
                       AND m_marker.meta_key = %s
                       AND m_marker.meta_value = 'yes'
                    LEFT JOIN {$orders_meta} m_skip
                        ON m_skip.order_id = o.id
                       AND m_skip.meta_key = %s
                    WHERE m_skip.id IS NULL
                      AND o.type = 'shop_order'
                      AND o.status NOT IN ('trash', 'auto-draft')
                      {$link_exclusion}
                    {$order_clause}
                    {$limit_clause}";
        } else {
            
            $order_clause = $count_only ? '' : 'ORDER BY o.post_date ASC, o.ID ASC';
            $limit_clause = '';
            if (!$count_only && $limit > 0) {
                $limit_clause = $wpdb->prepare('LIMIT %d OFFSET %d', (int) $limit, max(0, (int) $offset));
            }
            
            
            $select_col = $count_only ? 'COUNT(DISTINCT o.ID)' : 'DISTINCT o.ID AS id';

            $sql = "SELECT {$select_col}
                    FROM {$wpdb->posts} o
                    INNER JOIN {$wpdb->postmeta} m_marker
                        ON m_marker.post_id = o.ID
                       AND m_marker.meta_key = %s
                       AND m_marker.meta_value = 'yes'
                    LEFT JOIN {$wpdb->postmeta} m_skip
                        ON m_skip.post_id = o.ID
                       AND m_skip.meta_key = %s
                    WHERE m_skip.meta_id IS NULL
                      AND o.post_type = 'shop_order'
                      AND o.post_status NOT IN ('trash', 'auto-draft')
                      " . str_replace('o.id', 'o.ID', $link_exclusion) . "
                    {$order_clause}
                    {$limit_clause}";
        }

        
        $prepared = $wpdb->prepare($sql, $params);
        if ($count_only) {
            return (int) $wpdb->get_var($prepared);
        }
        $col = $wpdb->get_col($prepared);
        return is_array($col) ? array_map('intval', $col) : array();
    }

    
    public static function migrate_one($wc_order_id, array $vendor) {
        $wc_order_id = (int) $wc_order_id;
        $order = wc_get_order($wc_order_id);
        if (!$order) {
            self::log_failure($vendor, $wc_order_id, '', __('Order not found.', 'ai-eshop-optimizer'));
            return array('status' => 'failed', 'wc_order_id' => $wc_order_id, 'remote_code' => '', 'error' => 'order_not_found');
        }

        $remote_code = (string) $order->get_meta('wpslash_skroutz_smart_cart_order_code');
        if ($remote_code === '') {
            self::log_failure($vendor, $wc_order_id, '', __('Legacy order has no `wpslash_skroutz_smart_cart_order_code` — skipped.', 'ai-eshop-optimizer'));
            
            
            $order->update_meta_data(self::SKIP_MARKER_KEY, current_time('mysql', true));
            $order->save();
            return array('status' => 'skipped_no_code', 'wc_order_id' => $wc_order_id, 'remote_code' => '');
        }

        global $wpdb;
        $links_tbl = AIEO_MOI_Schema::tables()['order_links'];

        
        $existing_link_id = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$links_tbl}
             WHERE vendor_id = %d AND remote_order_id = %s LIMIT 1",
            (int) $vendor['id'], $remote_code
        ));

        try {
            self::apply_meta($order, $vendor, $remote_code);
        } catch (\Throwable $e) {
            self::log_failure($vendor, $wc_order_id, $remote_code, $e->getMessage());
            return array('status' => 'failed', 'wc_order_id' => $wc_order_id, 'remote_code' => $remote_code, 'error' => $e->getMessage());
        }

        if ($existing_link_id > 0) {
            
            
            $wpdb->update($links_tbl, array(
                'remote_state' => substr((string) $order->get_meta('_aieo_moi_state'), 0, 40),
                'updated_at'   => current_time('mysql', true),
            ), array('id' => $existing_link_id));
            return array('status' => 'skipped_already_linked', 'wc_order_id' => $wc_order_id, 'remote_code' => $remote_code);
        }

        $ok = $wpdb->insert($links_tbl, array(
            'vendor_id'       => (int) $vendor['id'],
            'remote_order_id' => $remote_code,
            'wc_order_id'     => $wc_order_id,
            'remote_state'    => substr((string) $order->get_meta('_aieo_moi_state'), 0, 40),
        ));
        if (!$ok) {
            self::log_failure($vendor, $wc_order_id, $remote_code, __('Failed to insert order_links row.', 'ai-eshop-optimizer'));
            return array('status' => 'failed', 'wc_order_id' => $wc_order_id, 'remote_code' => $remote_code, 'error' => 'links_insert_failed');
        }

        AIEO_MOI_Inbound_Log::record(array(
            'vendor_id'       => (int) $vendor['id'],
            'event_type'      => 'legacy_migrate',
            'remote_order_id' => $remote_code,
            'status'          => 'processed',
            'wc_order_id'     => $wc_order_id,
        ));

        return array('status' => 'migrated', 'wc_order_id' => $wc_order_id, 'remote_code' => $remote_code);
    }

    
    private static function apply_meta(WC_Order $order, array $vendor, $remote_code) {
        
        $order->update_meta_data('_aieo_moi_vendor_id',       (int)    $vendor['id']);
        $order->update_meta_data('_aieo_moi_vendor_slug',     (string) $vendor['slug']);
        $order->update_meta_data('_aieo_moi_provider',        (string) $vendor['provider']);
        $order->update_meta_data('_aieo_moi_remote_order_id', (string) $remote_code);
        $order->update_meta_data('_aieo_moi_remote_code',     (string) $remote_code);

        
        
        
        $order->update_meta_data('_aieo_moi_imported_via', 'legacy');
        if ((string) $order->get_meta('_aieo_moi_imported_at') === '') {
            
            
            
            $created = $order->get_date_created();
            $stamp   = $created ? $created->format('Y-m-d H:i:s') : current_time('mysql', true);
            $order->update_meta_data('_aieo_moi_imported_at', $stamp);
        }

        
        $state = (string) $order->get_meta('wpslash_skroutz_smart_cart_order_state');
        if ($state !== '') {
            $order->update_meta_data('_aieo_moi_state', $state);
        }

        
        $courier = (string) $order->get_meta('wpslash_skroutz_smart_cart_order_courier');
        if ($courier !== '') {
            $order->update_meta_data('_aieo_moi_courier', $courier);
        }
        $voucher = (string) $order->get_meta('wpslash_skroutz_smart_cart_order_courier_voucher');
        if ($voucher !== '') {
            $order->update_meta_data('_aieo_moi_voucher_url', $voucher);
        }

        
        
        
        
        $tracking_raw = $order->get_meta('wpslash_skroutz_smart_cart_order_courier_tracking_codes');
        $tracking_arr = array();
        if (is_array($tracking_raw)) {
            $tracking_arr = array_values(array_map('strval', $tracking_raw));
        } elseif (is_string($tracking_raw) && $tracking_raw !== '') {
            $decoded = json_decode($tracking_raw, true);
            if (is_array($decoded)) {
                $tracking_arr = array_values(array_map('strval', $decoded));
            } else {
                $imploded = (string) $order->get_meta('wpslash_skroutz_smart_cart_order_courier_tracking_codes_imploded');
                $src = $imploded !== '' ? $imploded : $tracking_raw;
                $tracking_arr = array_values(array_filter(array_map('trim', explode(',', $src))));
            }
        }
        if (!empty($tracking_arr)) {
            $order->update_meta_data('_aieo_moi_tracking_codes', wp_json_encode($tracking_arr));
        }

        
        if ((string) $order->get_meta('wpslash_skroutz_smart_cart_order_gift_wrap') === 'yes') {
            $order->update_meta_data('_aieo_moi_gift_wrap', 'yes');
        }

        
        
        if ((string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice') === 'yes') {
            $invoice = array(
                'company'    => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_company'),
                'profession' => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_profession'),
                'vat'        => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_vat'),
                'doy'        => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_doy'),
                'address_1'  => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_address'),
                'postcode'   => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_zip'),
                'city'       => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_city'),
                'region'     => (string) $order->get_meta('wpslash_skroutz_smart_cart_order_invoice_region'),
                'document'   => 'invoice',
            );
            $order->update_meta_data('_aieo_moi_invoice_data', wp_json_encode($invoice));
            
            
            
            if ($invoice['vat']  !== '' && (string) $order->get_meta('_billing_vat')  === '') { $order->update_meta_data('_billing_vat',   $invoice['vat']); }
            if ($invoice['doy']  !== '' && (string) $order->get_meta('_billing_irs')  === '') { $order->update_meta_data('_billing_irs',   $invoice['doy']); }
            if ($invoice['profession'] !== '' && (string) $order->get_meta('_billing_store') === '') { $order->update_meta_data('_billing_store', $invoice['profession']); }
            if ($invoice['company'] !== '' && $order->get_billing_company() === '') {
                $order->set_billing_company($invoice['company']);
            }
            if ((string) $order->get_meta('_billing_timologio') === '') {
                $order->update_meta_data('_billing_timologio', 'YES');
            }
        }

        
        
        
        $expires_at = (string) $order->get_meta('wpslash_skroutz_smart_cart_order_expires_at');
        if ($expires_at !== '') {
            $order->update_meta_data('_aieo_moi_skroutz_expires_at', $expires_at);
        }

        
        
        if ((string) $order->get_meta('_wc_order_attribution_origin') === '') {
            $order->update_meta_data('_wc_order_attribution_source_type', 'utm');
            $order->update_meta_data('_wc_order_attribution_utm_source',  (string) $vendor['provider']);
            $order->update_meta_data('_wc_order_attribution_utm_medium',  'marketplace');
            $order->update_meta_data('_wc_order_attribution_utm_campaign', (string) $vendor['slug']);
            $order->update_meta_data('_wc_order_attribution_origin',      (string) $vendor['label']);
            $order->update_meta_data('_wc_order_attribution_referrer',    '(none)');
        }

        $order->save();
    }

    private static function log_failure(array $vendor, $wc_order_id, $remote_code, $error_text) {
        AIEO_MOI_Inbound_Log::record(array(
            'vendor_id'       => isset($vendor['id']) ? (int) $vendor['id'] : null,
            'event_type'      => 'legacy_migrate',
            'remote_order_id' => (string) $remote_code,
            'status'          => 'skipped',
            'error_text'      => (string) $error_text,
            'wc_order_id'     => (int) $wc_order_id,
        ));
    }
}
