<?php
/**
 * GGM Commerce Background Import Handler
 *
 * Handles large imports in the background using WP-Cron or Action Scheduler
 * Provides progress tracking and notification when complete
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

class GGM_Commerce_Background_Import {

    /**
     * Threshold for suggesting background processing
     */
    const BACKGROUND_THRESHOLD = 250;

    /**
     * Batch size for background processing
     */
    const BATCH_SIZE = 50;

    /**
     * Import job prefix for transients
     */
    const JOB_PREFIX = 'ggmc_bg_import_';

    /**
     * Cron hook name
     */
    const CRON_HOOK = 'ggmc_process_background_import';

    /**
     * Constructor - register hooks
     */
    public function __construct() {
        add_action(self::CRON_HOOK, [$this, 'process_background_batch'], 10, 1);
        add_action('admin_notices', [$this, 'show_import_notices']);
    }

    /**
     * Check if import should be run in background
     *
     * @param int $product_count Number of products to import
     * @return bool Whether to suggest background processing
     */
    public static function should_use_background($product_count) {
        return $product_count > self::BACKGROUND_THRESHOLD;
    }

    /**
     * Start a background import job
     *
     * @param string $file_path Path to JSON import file
     * @param array $options Import options
     * @return string|WP_Error Job ID or error
     */
    public function start_background_import($file_path, $options = []) {
        // Generate unique job ID
        $job_id = uniqid('import_', true);

        // Parse the JSON file to get summary
        require_once plugin_dir_path(__FILE__) . 'class-json-importer.php';
        $importer = new GGM_Commerce_JSON_Importer();

        $data = $importer->parse_file($file_path);
        if (is_wp_error($data)) {
            return $data;
        }

        $summary = $importer->get_summary($data);
        $product_count = $summary['counts']['products'] ?? 0;

        // Calculate total batches
        $total_batches = ceil($product_count / self::BATCH_SIZE);

        // Store job data
        $job_data = [
            'job_id' => $job_id,
            'file_path' => $file_path,
            'options' => $options,
            'status' => 'pending',
            'created_at' => current_time('mysql'),
            'user_id' => get_current_user_id(),
            'summary' => $summary,
            'progress' => [
                'current_batch' => 0,
                'total_batches' => $total_batches,
                'total_products' => $product_count,
                'processed_products' => 0,
                'stats' => [
                    'tax_rates' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'attribute_groups' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'attributes' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'variation_attribute_groups' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'variation_attributes' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'categories' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'tags' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'products' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                    'variations' => ['created' => 0, 'updated' => 0, 'skipped' => 0],
                ],
                'warnings' => [],
                'errors' => [],
                'placeholders' => [],
            ],
            'completed_at' => null,
        ];

        // Save job data
        set_transient(self::JOB_PREFIX . $job_id, $job_data, DAY_IN_SECONDS);

        // Schedule first batch processing
        $this->schedule_next_batch($job_id);

        return $job_id;
    }

    /**
     * Schedule next batch processing
     *
     * @param string $job_id Job ID
     */
    private function schedule_next_batch($job_id) {
        // Check if Action Scheduler is available (recommended)
        if (function_exists('as_schedule_single_action')) {
            as_schedule_single_action(
                time(),
                self::CRON_HOOK,
                [$job_id],
                'ggm-commerce'
            );
        } else {
            // Fall back to WP-Cron
            wp_schedule_single_event(time(), self::CRON_HOOK, [$job_id]);
        }
    }

    /**
     * Process a batch of the background import
     *
     * @param string $job_id Job ID
     */
    public function process_background_batch($job_id) {
        // Get job data
        $job_data = get_transient(self::JOB_PREFIX . $job_id);

        if (!$job_data) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for background import issues
                error_log("GGM Commerce: Background import job not found: $job_id");
            }
            return;
        }

        // Mark as running
        if ($job_data['status'] === 'pending') {
            $job_data['status'] = 'running';
            $job_data['started_at'] = current_time('mysql');
        }

        // Load importer
        require_once plugin_dir_path(__FILE__) . 'class-json-importer.php';
        $importer = new GGM_Commerce_JSON_Importer();

        // Set options
        $importer->set_options([
            'duplicate_handling' => $job_data['options']['duplicate_handling'] ?? 'update',
            'download_images' => !empty($job_data['options']['download_images']),
            'create_missing_entities' => true,
            'batch_size' => self::BATCH_SIZE,
        ]);

        // Parse file
        $data = $importer->parse_file($job_data['file_path']);

        if (is_wp_error($data)) {
            $job_data['status'] = 'failed';
            $job_data['progress']['errors'][] = [
                'type' => 'parse_error',
                'message' => $data->get_error_message(),
            ];
            $job_data['completed_at'] = current_time('mysql');
            set_transient(self::JOB_PREFIX . $job_id, $job_data, DAY_IN_SECONDS);
            $this->send_completion_notification($job_data);
            return;
        }

        $current_batch = $job_data['progress']['current_batch'];

        // First batch: Import supporting entities
        if ($current_batch === 0) {
            $this->import_supporting_entities($importer, $data, $job_data);
        }

        // Process product batch
        $products = $data['products'] ?? [];
        $start_index = $current_batch * self::BATCH_SIZE;
        $batch_products = array_slice($products, $start_index, self::BATCH_SIZE);

        if (!empty($batch_products)) {
            foreach ($batch_products as $product) {
                try {
                    $this->import_single_product_background($importer, $product, $job_data);
                    $job_data['progress']['processed_products']++;
                } catch (Exception $e) {
                    $job_data['progress']['errors'][] = [
                        'type' => 'product_error',
                        'sku' => $product['sku'] ?? 'unknown',
                        'message' => $e->getMessage(),
                    ];
                }
            }
        }

        $job_data['progress']['current_batch']++;

        // Check if complete
        $total_batches = $job_data['progress']['total_batches'];
        if ($job_data['progress']['current_batch'] >= $total_batches) {
            // Resolve kit placeholders
            $this->resolve_kit_placeholders_background($job_data);

            $job_data['status'] = 'complete';
            $job_data['completed_at'] = current_time('mysql');
            set_transient(self::JOB_PREFIX . $job_id, $job_data, DAY_IN_SECONDS);

            // Clean up file
            @unlink($job_data['file_path']);

            // Send notification
            $this->send_completion_notification($job_data);
        } else {
            // Save progress and schedule next batch
            set_transient(self::JOB_PREFIX . $job_id, $job_data, DAY_IN_SECONDS);
            $this->schedule_next_batch($job_id);
        }
    }

    /**
     * Import supporting entities (first batch only)
     *
     * @param GGM_Commerce_JSON_Importer $importer Importer instance
     * @param array $data Import data
     * @param array &$job_data Job data reference
     */
    private function import_supporting_entities($importer, $data, &$job_data) {
        // Use reflection to access private methods, or implement public wrappers
        // For now, we'll do a simplified version directly here
        global $wpdb;

        // Import tax rates
        foreach ($data['tax_rates'] ?? [] as $rate) {
            $this->import_entity_simple(
                $wpdb->prefix . 'ggmc_tax_rates',
                'name',
                $rate,
                $job_data['progress']['stats']['tax_rates'],
                $job_data['options']['duplicate_handling'] ?? 'update'
            );
        }

        // Import attribute groups
        foreach ($data['attribute_groups'] ?? [] as $group) {
            $this->import_entity_simple(
                $wpdb->prefix . 'ggmc_attribute_groups',
                'name',
                $group,
                $job_data['progress']['stats']['attribute_groups'],
                $job_data['options']['duplicate_handling'] ?? 'update'
            );
        }

        // Import attributes
        foreach ($data['attributes'] ?? [] as $attr) {
            $this->import_attribute_background($attr, $job_data);
        }

        // Import variation types
        foreach ($data['variation_attributes'] ?? [] as $attr) {
            $this->import_entity_simple(
                $wpdb->prefix . 'ggmc_variation_types',
                'name',
                [
                    'name' => $attr['name'],
                    'slug' => $attr['slug'] ?? sanitize_title($attr['name']),
                    'input_type' => $attr['input_type'] ?? $attr['attribute_type'] ?? 'select',
                    'options' => !empty($attr['options']) ? wp_json_encode($attr['options']) : null,
                    'display_order' => $attr['display_order'] ?? 0,
                    'status' => 'active',
                ],
                $job_data['progress']['stats']['variation_attributes'],
                $job_data['options']['duplicate_handling'] ?? 'update'
            );
        }

        // Import categories (recursive)
        $this->import_categories_background($data['categories'] ?? [], null, $job_data);

        // Import tags
        foreach ($data['tags'] ?? [] as $tag) {
            $this->import_entity_simple(
                $wpdb->prefix . 'ggmc_tags',
                'name',
                [
                    'name' => $tag['name'],
                    'slug' => $tag['slug'] ?? sanitize_title($tag['name']),
                    'description' => $tag['description'] ?? '',
                    'status' => 'active',
                ],
                $job_data['progress']['stats']['tags'],
                $job_data['options']['duplicate_handling'] ?? 'update'
            );
        }
    }

    /**
     * Simple entity import helper
     */
    private function import_entity_simple($table, $unique_field, $data, &$stats, $duplicate_handling) {
        global $wpdb;

        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$table} WHERE {$unique_field} = %s",
            $data[$unique_field]
        ));

        if ($existing) {
            if ($duplicate_handling === 'skip') {
                $stats['skipped']++;
                return $existing;
            }

            $data['updated_at'] = current_time('mysql');
            unset($data['created_at']);
            $wpdb->update($table, $data, ['id' => $existing]);
            $stats['updated']++;
            return $existing;
        }

        $data['created_at'] = current_time('mysql');
        $data['updated_at'] = current_time('mysql');
        $wpdb->insert($table, $data);
        $stats['created']++;
        return $wpdb->insert_id;
    }

    /**
     * Import attribute with group reference
     */
    private function import_attribute_background($attr, &$job_data) {
        global $wpdb;

        $group_id = null;
        if (!empty($attr['group'])) {
            $group_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_attribute_groups WHERE name = %s",
                $attr['group']
            ));
        }

        $data = [
            'name' => $attr['name'],
            'group_id' => $group_id,
            'attribute_type' => $attr['attribute_type'] ?? 'text',
            'options' => !empty($attr['options']) ? wp_json_encode($attr['options']) : null,
            'unit' => $attr['unit'] ?? '',
            'icon' => $attr['icon'] ?? '',
            'display_order' => $attr['display_order'] ?? 0,
            'status' => 'active',
        ];

        $this->import_entity_simple(
            $wpdb->prefix . 'ggmc_attributes',
            'name',
            $data,
            $job_data['progress']['stats']['attributes'],
            $job_data['options']['duplicate_handling'] ?? 'update'
        );
    }

    /**
     * Import categories recursively
     */
    private function import_categories_background($categories, $parent_id, &$job_data) {
        global $wpdb;

        foreach ($categories as $cat) {
            $data = [
                'name' => $cat['name'],
                'slug' => $cat['slug'] ?? sanitize_title($cat['name']),
                'description' => $cat['description'] ?? '',
                'parent_id' => $parent_id,
                'display_order' => $cat['display_order'] ?? 0,
                'status' => 'active',
            ];

            $cat_id = $this->import_entity_simple(
                $wpdb->prefix . 'ggmc_categories',
                'name',
                $data,
                $job_data['progress']['stats']['categories'],
                $job_data['options']['duplicate_handling'] ?? 'update'
            );

            // Recurse for children
            if (!empty($cat['children'])) {
                $this->import_categories_background($cat['children'], $cat_id, $job_data);
            }
        }
    }

    /**
     * Import a single product in background mode
     */
    private function import_single_product_background($importer, $product, &$job_data) {
        global $wpdb;

        $sku = $product['sku'];

        // Check if product exists
        $existing = $wpdb->get_row($wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}ggmc_products WHERE sku = %s AND status != 'deleted'",
            $sku
        ), ARRAY_A);

        $duplicate_handling = $job_data['options']['duplicate_handling'] ?? 'update';

        if ($existing && $duplicate_handling === 'skip') {
            $job_data['progress']['stats']['products']['skipped']++;
            return;
        }

        // Resolve tax rate
        $tax_rate_id = null;
        if (!empty($product['tax_rate'])) {
            $tax_rate_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_tax_rates WHERE name = %s",
                $product['tax_rate']
            ));
        }

        $product_data = [
            'name' => $product['name'],
            'slug' => $product['slug'] ?? sanitize_title($product['name']),
            'short_description' => $product['short_description'] ?? '',
            'description' => $product['description'] ?? '',
            'price' => $product['price'],
            'sale_price' => $product['sale_price'],
            'stock' => $product['stock'],
            'stock_status' => $product['stock_status'] ?? 'instock',
            'manage_stock' => ($product['manage_stock'] ?? false) ? 1 : 0,
            'weight' => $product['weight'],
            'length' => $product['length'],
            'width' => $product['width'],
            'height' => $product['height'],
            'featured' => ($product['featured'] ?? false) ? 1 : 0,
            'status' => $product['status'] ?? 'active',
            'product_type' => $product['product_type'] ?? 'simple',
            'tax_rate_id' => $tax_rate_id,
            'requires_shipping' => ($product['requires_shipping'] ?? true) ? 1 : 0,
            'is_virtual' => ($product['is_virtual'] ?? false) ? 1 : 0,
            'is_downloadable' => ($product['is_downloadable'] ?? false) ? 1 : 0,
            'has_variations' => ($product['has_variations'] ?? false) ? 1 : 0,
            'variation_mode' => $product['variation_mode'] ?? null,
            'variation_stock_mode' => $product['variation_stock_mode'] ?? null,
            'updated_at' => current_time('mysql'),
        ];

        if ($existing) {
            $wpdb->update($wpdb->prefix . 'ggmc_products', $product_data, ['id' => $existing['id']]);
            $product_id = $existing['id'];
            $job_data['progress']['stats']['products']['updated']++;
        } else {
            $product_data['sku'] = $sku;
            $product_data['created_at'] = current_time('mysql');
            $wpdb->insert($wpdb->prefix . 'ggmc_products', $product_data);
            $product_id = $wpdb->insert_id;
            $job_data['progress']['stats']['products']['created']++;
        }

        // Import relationships (simplified for background processing)
        $this->import_product_relationships_background($product_id, $product, $job_data);
    }

    /**
     * Import product relationships
     */
    private function import_product_relationships_background($product_id, $product, &$job_data) {
        global $wpdb;

        // Categories
        $wpdb->delete($wpdb->prefix . 'ggmc_product_categories', ['product_id' => $product_id]);
        foreach ($product['categories'] ?? [] as $cat_name) {
            $cat_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_categories WHERE name = %s",
                $cat_name
            ));
            if ($cat_id) {
                $wpdb->insert($wpdb->prefix . 'ggmc_product_categories', [
                    'product_id' => $product_id,
                    'category_id' => $cat_id,
                ]);
            }
        }

        // Tags
        $wpdb->delete($wpdb->prefix . 'ggmc_product_tags', ['product_id' => $product_id]);
        foreach ($product['tags'] ?? [] as $tag_name) {
            $tag_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_tags WHERE name = %s",
                $tag_name
            ));
            if ($tag_id) {
                $wpdb->insert($wpdb->prefix . 'ggmc_product_tags', [
                    'product_id' => $product_id,
                    'tag_id' => $tag_id,
                ]);
            }
        }

        // Attributes
        $wpdb->delete($wpdb->prefix . 'ggmc_product_attribute_values', ['product_id' => $product_id]);
        foreach ($product['attributes'] ?? [] as $attr_name => $attr_value) {
            $attr_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_attributes WHERE name = %s",
                $attr_name
            ));
            if ($attr_id) {
                $wpdb->insert($wpdb->prefix . 'ggmc_product_attribute_values', [
                    'product_id' => $product_id,
                    'attribute_id' => $attr_id,
                    'attribute_value' => $attr_value,
                ]);
            }
        }

        // Barcodes
        $wpdb->delete($wpdb->prefix . 'ggmc_product_barcodes', ['product_id' => $product_id]);
        foreach ($product['barcodes'] ?? [] as $barcode) {
            $wpdb->insert($wpdb->prefix . 'ggmc_product_barcodes', [
                'product_id' => $product_id,
                'barcode_value' => $barcode['value'],
                'barcode_type' => $barcode['type'] ?? 'EAN-13',
                'is_primary' => ($barcode['is_primary'] ?? false) ? 1 : 0,
                'created_at' => current_time('mysql'),
            ]);
        }

        // Store kit components for later resolution
        if (!empty($product['kit_components'])) {
            // Store in transient for later resolution
            $pending_kits = get_transient('ggmc_pending_kit_components') ?: [];
            $pending_kits[$product['sku']] = [
                'product_id' => $product_id,
                'kit_config' => $product['kit_config'] ?? [],
                'components' => $product['kit_components'],
            ];
            set_transient('ggmc_pending_kit_components', $pending_kits, DAY_IN_SECONDS);
        }
    }

    /**
     * Resolve kit placeholders after all products imported
     */
    private function resolve_kit_placeholders_background(&$job_data) {
        global $wpdb;

        $pending_kits = get_transient('ggmc_pending_kit_components') ?: [];

        foreach ($pending_kits as $kit_sku => $kit_data) {
            $product_id = $kit_data['product_id'];
            $kit_config = $kit_data['kit_config'];

            // Create/update kit record
            $existing_kit = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_product_kits WHERE product_id = %d",
                $product_id
            ));

            if ($existing_kit) {
                $wpdb->update(
                    $wpdb->prefix . 'ggmc_product_kits',
                    [
                        'kit_type' => $kit_config['kit_type'] ?? 'kit',
                        'auto_calculate_price' => ($kit_config['auto_calculate_price'] ?? false) ? 1 : 0,
                        'updated_at' => current_time('mysql'),
                    ],
                    ['id' => $existing_kit]
                );
                $kit_id = $existing_kit;
            } else {
                $wpdb->insert($wpdb->prefix . 'ggmc_product_kits', [
                    'product_id' => $product_id,
                    'kit_type' => $kit_config['kit_type'] ?? 'kit',
                    'auto_calculate_price' => ($kit_config['auto_calculate_price'] ?? false) ? 1 : 0,
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql'),
                ]);
                $kit_id = $wpdb->insert_id;
            }

            // Clear existing components
            $wpdb->delete($wpdb->prefix . 'ggmc_kit_components', ['kit_id' => $kit_id]);

            // Add components
            foreach ($kit_data['components'] as $component) {
                $component_sku = $component['component_sku'];
                $component_id = $wpdb->get_var($wpdb->prepare(
                    "SELECT id FROM {$wpdb->prefix}ggmc_products WHERE sku = %s AND status != 'deleted'",
                    $component_sku
                ));

                if (!$component_id) {
                    // Create placeholder
                    $wpdb->insert($wpdb->prefix . 'ggmc_products', [
                        'sku' => $component_sku,
                        'name' => '[Placeholder] ' . $component_sku,
                        'slug' => sanitize_title('placeholder-' . $component_sku),
                        'price' => 0,
                        'status' => 'draft',
                        'product_type' => 'simple',
                        'created_at' => current_time('mysql'),
                        'updated_at' => current_time('mysql'),
                    ]);
                    $component_id = $wpdb->insert_id;
                    $job_data['progress']['placeholders'][] = $component_sku;
                    $job_data['progress']['warnings'][] = [
                        'type' => 'kit_component_missing',
                        'kit_sku' => $kit_sku,
                        'component_sku' => $component_sku,
                        'message' => sprintf('Kit "%s" references component SKU "%s" which was not found.', $kit_sku, $component_sku),
                    ];
                }

                $wpdb->insert($wpdb->prefix . 'ggmc_kit_components', [
                    'kit_id' => $kit_id,
                    'component_product_id' => $component_id,
                    'quantity' => $component['quantity'] ?? 1,
                    'display_order' => $component['display_order'] ?? 0,
                ]);
            }
        }

        // Clear pending kits
        delete_transient('ggmc_pending_kit_components');
    }

    /**
     * Send completion notification
     *
     * @param array $job_data Job data
     */
    private function send_completion_notification($job_data) {
        $user = get_userdata($job_data['user_id']);
        if (!$user) {
            return;
        }

        // Store notification for admin notice display
        $notifications = get_transient('ggmc_import_notifications_' . $job_data['user_id']) ?: [];
        $notifications[] = [
            'job_id' => $job_data['job_id'],
            'status' => $job_data['status'],
            'stats' => $job_data['progress']['stats'],
            'warnings_count' => count($job_data['progress']['warnings']),
            'errors_count' => count($job_data['progress']['errors']),
            'completed_at' => $job_data['completed_at'],
        ];
        set_transient('ggmc_import_notifications_' . $job_data['user_id'], $notifications, HOUR_IN_SECONDS);

        // Optionally send email
        $admin_email = $user->user_email;
        $subject = sprintf(
            /* translators: 1: site name, 2: import status (Complete/Failed) */
            __('[%1$s] Product Import %2$s', 'ggm-commerce'),
            get_bloginfo('name'),
            $job_data['status'] === 'complete' ? 'Complete' : 'Failed'
        );

        $stats = $job_data['progress']['stats'];
        $total_created = array_sum(array_column($stats, 'created'));
        $total_updated = array_sum(array_column($stats, 'updated'));

        $message = sprintf(
            /* translators: 1: created count, 2: updated count, 3: warnings count, 4: errors count, 5: products page URL */
            __( "Your product import has completed.\n\nSummary:\n- Created: %1\$d\n- Updated: %2\$d\n- Warnings: %3\$d\n- Errors: %4\$d\n\nView your products at: %5\$s", 'ggm-commerce' ),
            $total_created,
            $total_updated,
            count($job_data['progress']['warnings']),
            count($job_data['progress']['errors']),
            admin_url('admin.php?page=ggm-commerce-products')
        );

        wp_mail($admin_email, $subject, $message);
    }

    /**
     * Show import completion notices in admin
     */
    public function show_import_notices() {
        $user_id = get_current_user_id();
        $notifications = get_transient('ggmc_import_notifications_' . $user_id);

        if (empty($notifications)) {
            return;
        }

        foreach ($notifications as $notification) {
            $stats = $notification['stats'];
            $total_created = array_sum(array_column($stats, 'created'));
            $total_updated = array_sum(array_column($stats, 'updated'));

            $class = $notification['status'] === 'complete' ? 'notice-success' : 'notice-error';

            printf(
                '<div class="notice %s is-dismissible"><p><strong>%s</strong> %s</p></div>',
                esc_attr($class),
                esc_html__('Product Import Complete:', 'ggm-commerce'),
                sprintf(
                    /* translators: 1: created count, 2: updated count, 3: warnings count, 4: errors count */
                    esc_html__('%1$d created, %2$d updated, %3$d warnings, %4$d errors', 'ggm-commerce'),
                    intval( $total_created ),
                    intval( $total_updated ),
                    intval( $notification['warnings_count'] ),
                    intval( $notification['errors_count'] )
                )
            );
        }

        // Clear notifications after displaying
        delete_transient('ggmc_import_notifications_' . $user_id);
    }

    /**
     * Get job status
     *
     * @param string $job_id Job ID
     * @return array|null Job data or null
     */
    public function get_job_status($job_id) {
        return get_transient(self::JOB_PREFIX . $job_id);
    }

    /**
     * Cancel a running job
     *
     * @param string $job_id Job ID
     * @return bool Success
     */
    public function cancel_job($job_id) {
        $job_data = get_transient(self::JOB_PREFIX . $job_id);

        if (!$job_data) {
            return false;
        }

        // Clear scheduled events
        if (function_exists('as_unschedule_all_actions')) {
            as_unschedule_all_actions(self::CRON_HOOK, [$job_id], 'ggm-commerce');
        } else {
            wp_clear_scheduled_hook(self::CRON_HOOK, [$job_id]);
        }

        // Update status
        $job_data['status'] = 'cancelled';
        $job_data['completed_at'] = current_time('mysql');
        set_transient(self::JOB_PREFIX . $job_id, $job_data, DAY_IN_SECONDS);

        // Clean up file
        if (!empty($job_data['file_path']) && file_exists($job_data['file_path'])) {
            @unlink($job_data['file_path']);
        }

        return true;
    }

    /**
     * Get all active jobs for current user
     *
     * @return array Active jobs
     */
    public function get_user_active_jobs() {
        global $wpdb;
        $user_id = get_current_user_id();

        // This is a bit hacky - we need to scan transients
        // In production, you'd want a custom table for job tracking
        $active_jobs = [];

        $transients = $wpdb->get_col(
            "SELECT option_name FROM {$wpdb->options}
             WHERE option_name LIKE '_transient_" . self::JOB_PREFIX . "%'"
        );

        foreach ($transients as $transient_name) {
            $job_id = str_replace('_transient_' . self::JOB_PREFIX, '', $transient_name);
            $job_data = get_transient(self::JOB_PREFIX . $job_id);

            if ($job_data && $job_data['user_id'] == $user_id && in_array($job_data['status'], ['pending', 'running'])) {
                $active_jobs[] = $job_data;
            }
        }

        return $active_jobs;
    }
}

// Initialize
new GGM_Commerce_Background_Import();
