<?php

namespace Meliconnect\Meliconnect\Core;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

use Meliconnect\Meliconnect\Core\Helpers\Helper;
use Meliconnect\Meliconnect\Core\Helpers\HubApi;
use Meliconnect\Meliconnect\Core\Models\Process;
use Meliconnect\Meliconnect\Core\Models\ProcessItems;
use Meliconnect\Meliconnect\Core\Models\Template;
use Meliconnect\Meliconnect\Core\Models\UserConnection;
use Meliconnect\Meliconnect\Modules\Exporter\Models\ProductToExport;
use Meliconnect\Meliconnect\Modules\Exporter\Services\MercadoLibreListingAdapter;
use Meliconnect\Meliconnect\Modules\Exporter\Services\ListingDataFacade;

use Meliconnect\Meliconnect\Modules\Importer\Models\UserListingToImport;
use Meliconnect\Meliconnect\Modules\Importer\Services\ProductDataFacade;
use Meliconnect\Meliconnect\Modules\Importer\Services\WooCommerceProductAdapter;
use Meliconnect\Meliconnect\Modules\Importer\Services\WooCommerceProductCreationService;

class CronManager
{


    private $last_export_import_timestamp_option = 'meliconnect_last_export_import_timestamp';
    private $last_sync_timestamp_option          = 'meliconnect_last_sync_timestamp';

    private $interval = 'every_minute';

    private $import_hook             = 'meliconnect_process_import_tasks_event';
    private $import_lock_option_name = 'meliconnect_import_lock';

    private $export_hook             = 'meliconnect_process_export_tasks_event';
    private $export_lock_option_name = 'meliconnect_export_lock';

    private $sync_hook             = 'meliconnect_process_sync_tasks_event';
    private $sync_lock_option_name = 'meliconnect_sync_lock';

    private $import_custom_hook             = 'meliconnect_process_user_custom_import';
    private $custom_import_lock_option_name = 'meliconnect_custom_import_lock';

    private $export_custom_hook             = 'meliconnect_process_user_custom_export';
    private $custom_export_lock_option_name = 'meliconnect_custom_export_lock';

    private $notifications_hook        = 'meliconnect_sync_notifications';
    private $notifications_lock_option = 'meliconnect_notifications_lock';



    private $settings;

    private static $batchProcessor;

    private static function getBatchProcessor()
    {

        if (!self::$batchProcessor) {
            self::$batchProcessor = new BatchProcessor();
        }

        return self::$batchProcessor;
    }

    public function __construct()
    {
        add_action('init', array($this, 'registerFiltersAndActions'));
        add_action('init', array($this, 'registerCrons'));

        $this->settings = Helper::getMeliconnectOptions('all');
    }



    public function registerFiltersAndActions()
    {
        add_filter(
            'cron_schedules',
            function ($schedules) {
                if (! isset($schedules[$this->interval])) {
                    $schedules[$this->interval] = array(
                        'interval' => 60,
                        'display'  => esc_html__('Every Minute', 'meliconnect'),
                    );
                }
                return $schedules;
            }
        );
    }

    public function registerCrons()
    {
        if (isset($this->settings['meliconnect_import_is_disabled']) && $this->settings['meliconnect_import_is_disabled'] === 'true') {
            Helper::logData('Import cron not registered because it is disabled.', 'cron_generals');
        } else {
            $this->scheduleCronEvent($this->import_hook, 'Import cron registered.');
        }

        if (isset($this->settings['meliconnect_export_is_disabled']) && $this->settings['meliconnect_export_is_disabled'] === 'true') {
            // Helper::logData('Export cron not registered because it is disabled.', 'cron_generals');
        } else {
            $this->scheduleCronEvent($this->export_hook, 'Export cron registered.');
        }

        $this->scheduleCronEvent( $this->sync_hook, 'Sync cron registered.' );
        // $this->scheduleCronEvent( $this->import_custom_hook, 'User custom Import cron registered.' );
        // $this->scheduleCronEvent( $this->export_custom_hook, 'User custom Export cron registered.' );

        $this->scheduleCronEvent($this->notifications_hook, 'Notifications sync cron registered.');

        // Reconciler (ej cada 1 hora)
        if (!wp_next_scheduled('meliconnect_reconcile_cron')) {
            wp_schedule_event(time(), 'hourly', 'meliconnect_reconcile_cron');
        }

        $this->cleanupOldCrons();
    }

    public function cleanupOldCrons()
    {
        if (get_option('meliconnect_crons_cleaned')) {
            return;
        }

        // wp_clear_scheduled_hook( $this->sync_hook );
        // wp_clear_scheduled_hook( $this->import_custom_hook );
        // wp_clear_scheduled_hook( $this->export_custom_hook );

        // melicon_process_user_custom_export
        wp_clear_scheduled_hook('melicon_process_user_custom_export');
        wp_clear_scheduled_hook('melicon_process_export_tasks_event');
        wp_clear_scheduled_hook('melicon_process_import_tasks_event');

        update_option('meliconnect_crons_cleaned', 1);
    }

    private function scheduleCronEvent($hook, $logMessage)
    {
        if (! wp_next_scheduled($hook)) {
            wp_schedule_event(time(), $this->interval, $hook);
            Helper::logData($logMessage, 'cron_generals');
        }
    }

    public function handleCronExecution()
    {
        if (wp_doing_cron()) {
            add_action($this->import_hook, array($this, 'processImportTasks'));
            add_action($this->export_hook, array($this, 'processExportTasks'));
            add_action( $this->sync_hook, array( $this, 'processSyncTasks' ) );
            add_action($this->import_custom_hook, array($this, 'processUserCustomImport'), 10, 1);
            add_action($this->export_custom_hook, array($this, 'processUserCustomExport'), 10, 1);
            add_action($this->notifications_hook, array($this, 'processNotificationsSync'));
            add_action('meliconnect_reconcile_cron', [$this, 'runReconcile']);

            add_action('meliconnect_process_delete_products_and_images', array($this, 'processDeleteWorker'));
        }
    }

    public static function processDeleteWorker($process_id)
    {
        self::getBatchProcessor()->run([
            'process_type' => 'delete-products-and-images',
            'cron_hook'    => 'meliconnect_process_delete_products_and_images',
            'lock_name'    => 'meliconnect_delete_worker_lock',
            'log_channel'  => 'delete-worker',
            'batch_size'   => 10,
            'process_id'   => $process_id,

            'process_item' => function ($item) {

                Helper::logData(
                    'Processing item: ' . json_encode($item),
                    'delete-worker'
                );

                // eliminar imágenes
                self::deleteProductImages($item->woo_product_id);

                // eliminar producto
                $deleted = wp_delete_post($item->woo_product_id, true);

                // actualizar tabla meliconnect_user_listings_to_import
                if ($deleted) {
                    UserListingToImport::mark_as_deleted($item->meli_listing_id);
                }

                return true;
            },
        ]);
    }

    private static function deleteProductImages($product_id)
    {
        // 1. Obtener TODAS las imágenes del producto (incluye variaciones)
        $image_ids = self::getAllProductImageIds($product_id);

        foreach ($image_ids as $image_id) {

            if (!self::isAttachmentUsedAnywhere($image_id, $product_id)) {

                Helper::logData(
                    "Deleting attachment {$image_id}",
                    'delete-worker'
                );

                wp_delete_attachment($image_id, true);
            } else {

                Helper::logData(
                    "Skipping attachment {$image_id} (used in another post)",
                    'delete-worker'
                );
            }
        }
    }

    private static function getAllProductImageIds($product_id)
    {
        $image_ids = [];

        // Imagen destacada
        $thumbnail_id = get_post_thumbnail_id($product_id);
        if ($thumbnail_id) {
            $image_ids[] = (int) $thumbnail_id;
        }

        // Galería
        $gallery = get_post_meta($product_id, '_product_image_gallery', true);
        if (!empty($gallery)) {
            $gallery_ids = array_map('intval', explode(',', $gallery));
            $image_ids = array_merge($image_ids, $gallery_ids);
        }

        // Variaciones
        $variations = get_posts([
            'post_type'   => 'product_variation',
            'post_parent' => $product_id,
            'numberposts' => -1,
            'fields'      => 'ids',
        ]);

        foreach ($variations as $variation_id) {
            $variation_image_id = get_post_thumbnail_id($variation_id);
            if ($variation_image_id) {
                $image_ids[] = (int) $variation_image_id;
            }
        }

        return array_unique($image_ids);
    }

    private static function isAttachmentUsedAnywhere($attachment_id, $current_product_id = null)
    {
        global $wpdb;

        $attachment_url = wp_get_attachment_url($attachment_id);
        if (!$attachment_url) {
            return false;
        }

        $current_ids = [];

        if (!empty($current_product_id)) {
            $current_ids[] = (int) $current_product_id;

            $children = get_posts([
                'post_type'   => 'product_variation',
                'post_parent' => $current_product_id,
                'fields'      => 'ids',
                'numberposts' => -1,
            ]);

            if ($children) {
                $current_ids = array_merge($current_ids, $children);
            }

            $parent_id = wp_get_post_parent_id($current_product_id);
            if ($parent_id) {
                $current_ids[] = $parent_id;
            }
        }

        $current_ids = array_unique(array_map('intval', $current_ids));

        $where_not_in = '';
        $params = [];

        if (!empty($current_ids)) {
            $placeholders = implode(',', array_fill(0, count($current_ids), '%d'));
            $where_not_in = "p.ID NOT IN ($placeholders) AND";
            $params = array_merge($params, $current_ids);
        }

        $query = "
            SELECT p.ID, p.post_type, pm.meta_key
            FROM {$wpdb->posts} p
            LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID
            WHERE {$where_not_in}
            (
                (pm.meta_key IN ('_thumbnail_id', '_variation_image_id') AND pm.meta_value = %d)
                OR
                (pm.meta_key = '_product_image_gallery' 
                    AND pm.meta_value REGEXP '(^|,)%d(,|$)')
                OR
                (p.post_content LIKE %s)
            )
            LIMIT 1
        ";

        $params = array_merge($params, [
            $attachment_id,
            $attachment_id,
            '%' . $wpdb->esc_like($attachment_url) . '%'
        ]);

        $used = $wpdb->get_row($wpdb->prepare($query, $params));

        if ($used) {
            Helper::logData(
                "Attachment {$attachment_id} used in post {$used->ID} (type: {$used->post_type}, meta: {$used->meta_key})",
                'delete-worker'
            );
        }

        return !empty($used);
    }

    public function processNotificationsSync()
    {
        global $wpdb;

        $lock = get_option($this->notifications_lock_option);
        if ($lock) {
            Helper::logData('Notifications sync already running. Aborting.', 'notifications');
            return;
        }

        // Set lock
        update_option($this->notifications_lock_option, time());

        try {
            $domain = get_site_url();

            // Get connected users
            $connected_users = UserConnection::getConnectedUsers();
            // Helper::logData( 'Connected users: ' . wp_json_encode( $connected_users ), 'notifications' );

            $table_name  = $wpdb->prefix . 'meliconnect_notifications';
            $total_count = 0;

            foreach ($connected_users as $user) {
                if (empty($user->api_token)) {
                    Helper::logData("User {$user->id} has no api_token. Only getting general notifiactions.", 'notifications');
                }

                $api_url = HubApi::get(
                    '/notifications',
                    array(
                        'domain'       => $domain,
                        'access_token' => $user->api_token,
                    )
                );

                Helper::logData("Fetching notifications for user {$user->nickname} with URL: $api_url", 'notifications');

                $response = wp_remote_get($api_url);

                if (is_wp_error($response)) {
                    Helper::logData(
                        "Error fetching notifications for user {$user->nickname}: " .
                            $response->get_error_message(),
                        'notifications'
                    );
                    continue;
                }

                $body = wp_remote_retrieve_body($response);
                $data = json_decode($body, true);

                if (empty($data['notifications'])) {
                    Helper::logData('No notifications found for this domain.', 'notifications');
                    continue;
                }

                $count = 0;

                foreach ($data['notifications'] as $notification) {
                    $exists = $wpdb->get_var(
                        $wpdb->prepare(
                            "SELECT id FROM {$table_name} WHERE unique_id = %s",
                            $notification['unique_id']
                        )
                    );

                    $row = array(
                        'unique_id'    => $notification['unique_id'],
                        'title_html'   => $notification['title_html'] ?? null,
                        'text_html'    => $notification['text_html'] ?? null,
                        'icon_html'    => $notification['icon_html'] ?? null,
                        'bt1_text'     => $notification['bt1_text'] ?? null,
                        'bt1_link'     => $notification['bt1_link'] ?? null,
                        'bt2_text'     => $notification['bt2_text'] ?? null,
                        'bt2_link'     => $notification['bt2_link'] ?? null,
                        'from_version' => $notification['from_version'] ?? null,
                        'to_version'   => $notification['to_version'] ?? null,
                        'type'         => $notification['type'] ?? null,
                        'priority'     => $notification['priority'] ?? 0,
                        'meta'         => ! empty($notification['meta']) ? maybe_serialize($notification['meta']) : null,
                        'date_from'    => $notification['date_from'] ?? current_time('mysql'),
                        'status'       => $notification['status'] ?? 'hide',
                        'is_dismissed' => $notification['is_dismissed'] ?? 0,
                        'is_made'      => $notification['is_made'] ?? 0,
                        'created_at'   => current_time('mysql'),
                        'updated_at'   => current_time('mysql'),
                    );

                    if ($exists) {
                        // not update created_at, is_dismissed, is_made
                        unset($row['created_at'], $row['is_dismissed'], $row['is_made']);

                        $wpdb->update($table_name, $row, array('id' => $exists));
                    } else {
                        $wpdb->insert($table_name, $row);
                    }

                    ++$count;
                    ++$total_count;
                }

                Helper::logData("Synced {$count} notifications for user {$user->nickname}.", 'notifications');
            }

            Helper::logData("Notifications sync completed. Total synced across all users: {$total_count}.", 'notifications');
        } catch (\Exception $e) {
            Helper::logData('Error during notifications sync: ' . $e->getMessage(), 'notifications');
        } finally {
            // Always release the lock
            delete_option($this->notifications_lock_option);
        }
    }

    public function processUserCustomImport($process_id)
    {
        Helper::logData('Iniciando proceso de importacion manual', 'custom-import');

        Helper::logData('Process ID: ' . $process_id, 'custom-import');

        $this->do_import('custom', 10, $process_id);
    }




    public function processUserCustomExport($process_id = null)
    {
        Helper::logData('Iniciando export manual', 'custom-export');

        $this->do_export('custom', 10, $process_id);
    }




    public function processImportTasks()
    {
        $this->processTasks('import', $this->last_export_import_timestamp_option, 'cron_import');
    }

    public function processExportTasks()
    {
        $this->processTasks('export', $this->last_export_import_timestamp_option, 'cron_export');
    }

    public function processSyncTasks()
    {
        $processor = new SyncProcessor();
    
        $processor->run();
    }

    public function runReconcile()
    {
        (new SyncReconciler())->run();
    }


    private function processTasks($taskType, $timestampOption, $logPrefix)
    {

        // Verificar el estado de habilitación de la sincronización general o específica
        $isActive = true;

        switch ($taskType) {
            case 'import':
            case 'export':
                $isActive = $this->settings['meliconnect_general_sync_type'] == $taskType && $this->settings['meliconnect_' . $taskType . '_is_disabled'] != 'true' && $this->settings['meliconnect_general_sync_method'] === 'WordPress';
                break;
            case 'sync':
                $isActive = $this->settings['meliconnect_sync_cron_status'] === 'active' && $this->settings['meliconnect_sync_cron_method'] === 'WordPress';
                break;
        }

        if ($isActive) {
            $last_export_timestamp   = get_option($timestampOption, 0);
            $current_time            = current_time('timestamp');
            $time_difference_minutes = ($current_time - $last_export_timestamp) / 60;

            if ($time_difference_minutes >= $this->settings['meliconnect_general_sync_frecuency_minutes'] || $last_export_timestamp == 0) {
                // Helper::logData( 'Last export timestamp: ' . $last_export_timestamp, $logPrefix );
                // Helper::logData( 'Current time: ' . $current_time, $logPrefix );
                // Helper::logData( 'Difference: ' . $time_difference_minutes, $logPrefix );
                // Helper::logData( 'Se ejecutó la función de ' . $taskType, $logPrefix );

                switch ($taskType) {
                    case 'import':
                        $this->do_import(
                            'automatic',
                            $this->settings['meliconnect_general_sync_items_batch']
                        );
                        break;
                    case 'export':
                        $this->do_export();
                        break;
                    case 'sync':
                        $this->do_sync();
                        break;
                }

                update_option($timestampOption, $current_time);
            } else {
                /*
				Helper::logData( 'xx Por diff time. NO se ejecutó la función de ' . $taskType, $logPrefix );

				Helper::logData( 'Last export timestamp: ' . $last_export_timestamp, $logPrefix );
				Helper::logData( 'Current time: ' . $current_time, $logPrefix );
				Helper::logData( 'Difference: ' . $time_difference_minutes, $logPrefix ); */
            }
        } else {
            // Helper::logData('La sincronización ' . $taskType . ' NO se encuentra activa.', $logPrefix);

            /*
			Helper::logData('Export/import options ', $logPrefix);
			Helper::logData('meliconnect_' . $taskType . '_is_disabled: ' . $this->settings['meliconnect_' . $taskType . '_is_disabled'], $logPrefix);
			Helper::logData('meliconnect_general_sync_type: ' . $this->settings['meliconnect_general_sync_type'], $logPrefix);
			Helper::logData('meliconnect_general_sync_method: ' . $this->settings['meliconnect_general_sync_method'], $logPrefix);

			Helper::logData('Sync options ', $logPrefix);
			Helper::logData('meliconnect_sync_cron_status: ' . $this->settings['meliconnect_sync_cron_status'], $logPrefix);
			Helper::logData('meliconnect_sync_cron_method: ' . $this->settings['meliconnect_sync_cron_method'], $logPrefix); */
        }
    }

    public function do_import($type = 'automatic', $batch_size = 10, $process_id = null)
    {
        $wooAdapter = new WooCommerceProductAdapter();
        $creator    = new WooCommerceProductCreationService();
        $facade     = new ProductDataFacade($wooAdapter, $creator);

        $processed_listing_ids = [];

        self::getBatchProcessor()->run([
            'process_type' => $type . '-import',
            'cron_hook'    => $type === 'custom' ? $this->import_custom_hook : null,
            'lock_name'    => "meliconnect_{$type}_import_lock",
            'log_channel'  => $type . '-import',
            'batch_size'   => $batch_size,
            'process_id'   => $process_id,
            'cancel_flag'  => 'meliconnect_import_cancel_requested',

            'before_loop' => function ($items) use (&$processed_listing_ids) {
                $processed_listing_ids = [];
            },

            'process_item' => function ($item) use ($facade, $type, &$processed_listing_ids) {

                Helper::logData('Processing listing ' . $item->meli_listing_id, $type . '-import');

                $result = $facade->importAndCreateProduct(
                    $item->meli_listing_id,
                    $item->meli_user_id,
                    $item->template_id,
                    $item->woo_product_id
                );

                if ($type === 'custom') {
                    if ($result !== false) {
                        UserListingToImport::update_user_listing_item_import_status(
                            [$item->meli_listing_id],
                            'finished'
                        );

                        $processed_listing_ids[] = $item->meli_listing_id;
                    } else {
                        UserListingToImport::update_user_listing_item_import_status(
                            [$item->meli_listing_id],
                            'failed'
                        );
                    }
                }

                return $result;
            },

            'after_loop' => function () use ($type, &$processed_listing_ids) {
                if ($type === 'custom' && !empty($processed_listing_ids)) {
                    UserListingToImport::update_vinculated_product_ids(
                        $processed_listing_ids
                    );
                }
            },
        ]);
    }



    public function do_export($type = 'automatic', $batch_size = 10, $process_id = null)
    {
        $meliListingAdapter = new MercadoLibreListingAdapter();
        $listingDataFacade  = new ListingDataFacade($meliListingAdapter);

        self::getBatchProcessor()->run([
            'process_type' => $type . '-export',
            'cron_hook'    => $type === 'custom' ? $this->export_custom_hook : null,
            'lock_name'    => "meliconnect_{$type}_export_lock",
            'log_channel'  => $type . '-export',
            'batch_size'   => $batch_size,
            'process_id'   => $process_id,
            'cancel_flag'  => 'meliconnect_export_cancel_requested',

            'process_item' => function ($item) use ($listingDataFacade, $type) {

                global $wpdb;

                Helper::logData(
                    'Processing woo product id: ' . $item->woo_product_id,
                    $type . '-export'
                );

                try {

                    /**
                     * 🔑 Obtener meli_user_id
                     */
                    if (!empty($item->meli_user_id)) {

                        $meli_user_id = $item->meli_user_id;
                    } else {

                        $custom_template_data = Template::selectCustomTemplateData(
                            $item->template_id,
                            ['seller_meli_id']
                        );

                        if (empty($custom_template_data['seller_meli_id'])) {

                            Helper::logData(
                                'User id not found in template: ' . $item->template_id,
                                $type . '-export'
                            );

                            return false;
                        }

                        $meli_user_id = $custom_template_data['seller_meli_id'];
                    }

                    /**
                     * ⚙️ SETTINGS + PRODUCT
                     */
                    $settings = Helper::getMeliconnectOptions('export');
                    $product  = wc_get_product($item->woo_product_id);

                    /**
                     * 🧠 RESOLVER MODO
                     */
                    $export_mode = $this->resolveExportMode(
                        $product,
                        $item->template_id,
                        $settings
                    );

                    Helper::logData(
                        'Resolved export mode: ' . $export_mode,
                        $type . '-export'
                    );

                    /**
                     * 🚨 SPLIT MODE
                     */
                    if ($export_mode === 'split') {

                        Helper::logData(
                            'Split mode active for product: ' . $item->woo_product_id,
                            $type . '-export'
                        );

                        $variation_ids = $product ? $product->get_children() : [];

                        if (!empty($variation_ids)) {

                            foreach ($variation_ids as $variation_id) {

                                Helper::logData(
                                    'Exporting variation: ' . $variation_id,
                                    $type . '-export'
                                );

                                $wpdb->query('START TRANSACTION');

                                try {

                                    $listingDataFacade->getAndExportListing(
                                        $meli_user_id,
                                        $variation_id,
                                        $item->template_id,
                                        null
                                    );

                                    $wpdb->query('COMMIT');
                                } catch (\Throwable $e) {

                                    $wpdb->query('ROLLBACK');

                                    Helper::logData(
                                        'Error exporting variation ' . $variation_id . ': ' . $e->getMessage(),
                                        $type . '-export'
                                    );
                                }
                            }

                            return true;
                        }
                    }

                    /**
                     * 🚀 SINGLE o VARIATIONS (flujo normal)
                     */
                    $wpdb->query('START TRANSACTION');

                    $listingDataFacade->getAndExportListing(
                        $meli_user_id,
                        $item->woo_product_id,
                        $item->template_id,
                        $item->meli_listing_id
                    );

                    $wpdb->query('COMMIT');

                    return true;
                } catch (\Throwable $e) {

                    $wpdb->query('ROLLBACK');

                    Helper::logData(
                        'Error processing item ' . $item->id . ': ' . $e->getMessage(),
                        $type . '-export'
                    );

                    return false;
                }
            },
        ]);
    }

    protected function resolveExportMode($product, $template_id, $settings)
    {
        $mode = $settings['meliconnect_export_invalid_variations_mode'] ?? 'single';

        if (!$product || !$product->is_type('variable')) {
            return 'single';
        }

        /**
         * 🔍 ML permite variaciones?
         */
        $allows_variations = Template::getTemplateMeta(
            $template_id,
            'meliconnect_allows_variations',
            null
        );

        // fallback seguro → si no existe el meta, asumimos que SÍ permite
        if ($allows_variations === null) {
            $allows_variations = 1;
        }

        /**
         * 🔍 Validación real de variaciones
         */
        $has_valid_variations = $this->hasValidVariationsForMeli($product, $template_id);

        /**
         * 🚨 ML NO permite variaciones
         */
        if (!$allows_variations) {
            return 'split';
        }

        /**
         * 🚨 Variaciones inválidas
         */
        if (!$has_valid_variations) {

            if ($mode === 'split') {
                return 'split';
            }

            return 'single';
        }

        /**
         * 🚀 Todo OK
         */
        return 'variations';
    }

    protected function hasValidVariationsForMeli($product, $template_id)
    {
        if (!$product || !$product->is_type('variable')) {
            return false;
        }

        $variation_ids = $product->get_children();

        if (empty($variation_ids)) {
            return false;
        }

        /**
         * 🔍 Atributos del template
         */
        $template_attrs = Template::getTemplateAttributes($template_id);

        $meli_variation_attrs = array_filter($template_attrs, function ($attr) {
            return !empty($attr['variation_attribute_tag']);
        });

        if (empty($meli_variation_attrs)) {
            //Helper::logData('No ML variation attributes defined in template', 'export-debug');
            return false;
        }

        /**
         * 🔍 Mapear atributos Woo esperados
         */
        $expected_woo_attrs = [];

        foreach ($meli_variation_attrs as $attr) {

            if (!empty($attr['woo_attribute_id'])) {
                $expected_woo_attrs[] = (int) $attr['woo_attribute_id'];
            }
        }

        if (empty($expected_woo_attrs)) {
            //Helper::logData('No Woo attributes mapped for ML variations', 'export-debug');
            return false;
        }

        /**
         * 🔍 Validar variaciones reales
         */
        $valid_variations = 0;

        foreach ($variation_ids as $variation_id) {

            $variation = wc_get_product($variation_id);

            if (!$variation) {
                continue;
            }

            /**
             * Validaciones básicas
             */
            if ($variation->get_price() === '' || $variation->get_price() === null) {
                continue;
            }

            if ($variation->get_stock_quantity() === null && !$variation->is_in_stock()) {
                continue;
            }

            $variation_attributes = $variation->get_attributes();

            if (empty($variation_attributes)) {
                continue;
            }

            /**
             * 🔍 Validar que tenga TODOS los atributos necesarios
             */
            $matched_attrs = 0;

            foreach ($expected_woo_attrs as $expected_attr_id) {

                $found = false;

                foreach ($variation_attributes as $attr_key => $attr_value) {

                    // attr_key suele ser algo como: attribute_pa_color
                    if (strpos($attr_key, (string)$expected_attr_id) !== false) {
                        $found = true;
                        break;
                    }
                }

                if ($found) {
                    $matched_attrs++;
                }
            }

            /**
             * ✔ Tiene todos los atributos requeridos
             */
            if ($matched_attrs === count($expected_woo_attrs)) {
                $valid_variations++;
            }
        }

        /* Helper::logData(
            "Valid variations found: {$valid_variations} / " . count($variation_ids),
            'export-debug'
        ); */

        return $valid_variations > 0;
    }

    public function do_sync() {}


    public static function deactivate()
    {
        $self = new self();
        wp_clear_scheduled_hook($self->import_hook);
        wp_clear_scheduled_hook($self->export_hook);
        wp_clear_scheduled_hook($self->sync_hook);
        wp_clear_scheduled_hook($self->import_custom_hook);
        wp_clear_scheduled_hook($self->export_custom_hook);
    }
}
