<?php
/**
 * GGM Commerce Field Mapper
 *
 * Handles field mapping for CSV imports
 *
 * @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_Field_Mapper {

    /**
     * Option name for saved mappings
     * @var string
     */
    const SAVED_MAPPINGS_OPTION = 'ggm_commerce_csv_mappings';

    /**
     * Get all available fields for mapping
     *
     * @return array Available fields with metadata
     */
    public function get_available_fields() {
        global $wpdb;

        $fields = [
            // Core product fields
            'core' => [
                'label' => __('Core Fields', 'ggm-commerce'),
                'fields' => [
                    'id' => [
                        'label' => __('Product ID', 'ggm-commerce'),
                        'description' => __('Leave empty for new products', 'ggm-commerce'),
                        'type' => 'int'
                    ],
                    'name' => [
                        'label' => __('Product Name', 'ggm-commerce'),
                        'description' => __('Required for new products', 'ggm-commerce'),
                        'type' => 'string',
                        'required' => true
                    ],
                    'slug' => [
                        'label' => __('URL Slug', 'ggm-commerce'),
                        'description' => __('Auto-generated if empty', 'ggm-commerce'),
                        'type' => 'string'
                    ],
                    'sku' => [
                        'label' => __('SKU', 'ggm-commerce'),
                        'description' => __('Stock Keeping Unit', 'ggm-commerce'),
                        'type' => 'string'
                    ],
                    'description' => [
                        'label' => __('Description', 'ggm-commerce'),
                        'description' => __('Full product description', 'ggm-commerce'),
                        'type' => 'text'
                    ],
                    'short_description' => [
                        'label' => __('Short Description', 'ggm-commerce'),
                        'description' => __('Brief product summary', 'ggm-commerce'),
                        'type' => 'text'
                    ],
                ]
            ],

            // Pricing fields
            'pricing' => [
                'label' => __('Pricing', 'ggm-commerce'),
                'fields' => [
                    'price' => [
                        'label' => __('Regular Price', 'ggm-commerce'),
                        'description' => __('Standard selling price', 'ggm-commerce'),
                        'type' => 'decimal'
                    ],
                    'sale_price' => [
                        'label' => __('Sale Price', 'ggm-commerce'),
                        'description' => __('Discounted price', 'ggm-commerce'),
                        'type' => 'decimal'
                    ],
                ]
            ],

            // Inventory fields
            'inventory' => [
                'label' => __('Inventory', 'ggm-commerce'),
                'fields' => [
                    'stock' => [
                        'label' => __('Stock Quantity', 'ggm-commerce'),
                        'description' => __('Available stock count', 'ggm-commerce'),
                        'type' => 'int'
                    ],
                    'stock_status' => [
                        'label' => __('Stock Status', 'ggm-commerce'),
                        'description' => __('instock, outofstock, backorder', 'ggm-commerce'),
                        'type' => 'select',
                        'options' => ['instock', 'outofstock', 'backorder']
                    ],
                    'manage_stock' => [
                        'label' => __('Manage Stock', 'ggm-commerce'),
                        'description' => __('1 = yes, 0 = no', 'ggm-commerce'),
                        'type' => 'boolean'
                    ],
                ]
            ],

            // Shipping fields
            'shipping' => [
                'label' => __('Shipping', 'ggm-commerce'),
                'fields' => [
                    'weight' => [
                        'label' => __('Weight', 'ggm-commerce'),
                        'description' => __('Product weight', 'ggm-commerce'),
                        'type' => 'decimal'
                    ],
                    'length' => [
                        'label' => __('Length', 'ggm-commerce'),
                        'description' => __('Product length', 'ggm-commerce'),
                        'type' => 'decimal'
                    ],
                    'width' => [
                        'label' => __('Width', 'ggm-commerce'),
                        'description' => __('Product width', 'ggm-commerce'),
                        'type' => 'decimal'
                    ],
                    'height' => [
                        'label' => __('Height', 'ggm-commerce'),
                        'description' => __('Product height', 'ggm-commerce'),
                        'type' => 'decimal'
                    ],
                    'requires_shipping' => [
                        'label' => __('Requires Shipping', 'ggm-commerce'),
                        'description' => __('1 = yes, 0 = no', 'ggm-commerce'),
                        'type' => 'boolean'
                    ],
                ]
            ],

            // Status fields
            'status' => [
                'label' => __('Status & Type', 'ggm-commerce'),
                'fields' => [
                    'status' => [
                        'label' => __('Status', 'ggm-commerce'),
                        'description' => __('active, draft, archived', 'ggm-commerce'),
                        'type' => 'select',
                        'options' => ['active', 'draft', 'archived']
                    ],
                    'featured' => [
                        'label' => __('Featured', 'ggm-commerce'),
                        'description' => __('1 = featured, 0 = not featured', 'ggm-commerce'),
                        'type' => 'boolean'
                    ],
                    'product_type' => [
                        'label' => __('Product Type', 'ggm-commerce'),
                        'description' => __('simple, variable, kit, etc.', 'ggm-commerce'),
                        'type' => 'select',
                        'options' => ['simple', 'variable', 'kit', 'build']
                    ],
                    'is_virtual' => [
                        'label' => __('Virtual Product', 'ggm-commerce'),
                        'description' => __('1 = virtual, 0 = physical', 'ggm-commerce'),
                        'type' => 'boolean'
                    ],
                    'is_downloadable' => [
                        'label' => __('Downloadable', 'ggm-commerce'),
                        'description' => __('1 = downloadable, 0 = not', 'ggm-commerce'),
                        'type' => 'boolean'
                    ],
                ]
            ],

            // Taxonomy fields
            'taxonomy' => [
                'label' => __('Categories & Tags', 'ggm-commerce'),
                'fields' => [
                    'categories' => [
                        'label' => __('Categories', 'ggm-commerce'),
                        'description' => __('Comma-separated category names', 'ggm-commerce'),
                        'type' => 'taxonomy'
                    ],
                    'tags' => [
                        'label' => __('Tags', 'ggm-commerce'),
                        'description' => __('Comma-separated tag names', 'ggm-commerce'),
                        'type' => 'taxonomy'
                    ],
                ]
            ],

            // Media fields
            'media' => [
                'label' => __('Images', 'ggm-commerce'),
                'fields' => [
                    'image' => [
                        'label' => __('Main Image', 'ggm-commerce'),
                        'description' => __('URL or media ID', 'ggm-commerce'),
                        'type' => 'image'
                    ],
                    'gallery_images' => [
                        'label' => __('Gallery Images', 'ggm-commerce'),
                        'description' => __('Comma-separated URLs or IDs', 'ggm-commerce'),
                        'type' => 'images'
                    ],
                ]
            ],

            // Variation fields
            'variations' => [
                'label' => __('Variations', 'ggm-commerce'),
                'fields' => [
                    'has_variations' => [
                        'label' => __('Has Variations', 'ggm-commerce'),
                        'description' => __('1 = yes, 0 = no', 'ggm-commerce'),
                        'type' => 'boolean'
                    ],
                    'variation_mode' => [
                        'label' => __('Variation Mode', 'ggm-commerce'),
                        'description' => __('combined or independent', 'ggm-commerce'),
                        'type' => 'select',
                        'options' => ['combined', 'independent']
                    ],
                    'variations' => [
                        'label' => __('Variations Data', 'ggm-commerce'),
                        'description' => __('JSON array of variations', 'ggm-commerce'),
                        'type' => 'json'
                    ],
                ]
            ],

            // Premium fields - Barcodes
            'barcodes' => [
                'label' => __('Barcodes', 'ggm-commerce'),
                'fields' => [
                    'barcode_primary' => [
                        'label' => __('Primary Barcode', 'ggm-commerce'),
                        'description' => __('Main barcode value', 'ggm-commerce'),
                        'type' => 'string'
                    ],
                    'barcode_type' => [
                        'label' => __('Barcode Type', 'ggm-commerce'),
                        'description' => __('EAN-13, UPC-A, etc.', 'ggm-commerce'),
                        'type' => 'select',
                        'options' => ['EAN-13', 'UPC-A', 'EAN-8', 'Code128', 'QR']
                    ],
                    'barcodes_additional' => [
                        'label' => __('Additional Barcodes', 'ggm-commerce'),
                        'description' => __('JSON array of extra barcodes', 'ggm-commerce'),
                        'type' => 'json'
                    ],
                ]
            ],

            // Premium fields - Kits
            'kits' => [
                'label' => __('Kits & Builds', 'ggm-commerce'),
                'fields' => [
                    'kit_type' => [
                        'label' => __('Kit Type', 'ggm-commerce'),
                        'description' => __('kit or build', 'ggm-commerce'),
                        'type' => 'select',
                        'options' => ['kit', 'build']
                    ],
                    'kit_auto_price' => [
                        'label' => __('Auto Calculate Price', 'ggm-commerce'),
                        'description' => __('1 = auto, 0 = manual', 'ggm-commerce'),
                        'type' => 'boolean'
                    ],
                    'kit_components' => [
                        'label' => __('Kit Components', 'ggm-commerce'),
                        'description' => __('JSON: [{"sku":"ABC","qty":2}]', 'ggm-commerce'),
                        'type' => 'json'
                    ],
                ]
            ],

            // Premium fields - Downloads
            'downloads' => [
                'label' => __('Downloads', 'ggm-commerce'),
                'fields' => [
                    'downloads' => [
                        'label' => __('Download Files', 'ggm-commerce'),
                        'description' => __('JSON array of download files', 'ggm-commerce'),
                        'type' => 'json'
                    ],
                ]
            ],

            // Tax
            'tax' => [
                'label' => __('Tax', 'ggm-commerce'),
                'fields' => [
                    'tax_rate_id' => [
                        'label' => __('Tax Rate ID', 'ggm-commerce'),
                        'description' => __('ID of tax rate to apply', 'ggm-commerce'),
                        'type' => 'int'
                    ],
                ]
            ],
        ];

        // Add custom attributes dynamically
        $attributes = $wpdb->get_results(
            "SELECT id, name FROM {$wpdb->prefix}ggmc_attributes WHERE status = 'active' ORDER BY name"
        );

        if (!empty($attributes)) {
            $fields['attributes'] = [
                'label' => __('Custom Attributes', 'ggm-commerce'),
                'fields' => []
            ];

            foreach ($attributes as $attr) {
                $fields['attributes']['fields']['attr:' . $attr->name] = [
                    'label' => $attr->name,
                    'description' => sprintf(
                        /* translators: %s: attribute name */
                        __('Custom attribute: %s', 'ggm-commerce'),
                        $attr->name
                    ),
                    'type' => 'attribute',
                    'attribute_id' => $attr->id
                ];
            }
        }

        return $fields;
    }

    /**
     * Get flat list of all field keys for dropdown
     *
     * @return array Flat field list
     */
    public function get_flat_field_list() {
        $groups = $this->get_available_fields();
        $flat = [
            '' => __('-- Skip this column --', 'ggm-commerce')
        ];

        foreach ($groups as $group_key => $group) {
            foreach ($group['fields'] as $field_key => $field_data) {
                $flat[$field_key] = $group['label'] . ' → ' . $field_data['label'];
            }
        }

        return $flat;
    }

    /**
     * Auto-map CSV headers to product fields
     *
     * @param array $csv_headers Headers from CSV file
     * @return array Suggested mapping
     */
    public function auto_map($csv_headers) {
        $mapping = [];
        $available_fields = $this->get_flat_field_list();

        // Direct matches (case-insensitive)
        $direct_map = [
            // Core fields
            'id' => 'id',
            'product id' => 'id',
            'name' => 'name',
            'product name' => 'name',
            'title' => 'name',
            'product title' => 'name',
            'slug' => 'slug',
            'url slug' => 'slug',
            'sku' => 'sku',
            'product sku' => 'sku',
            'description' => 'description',
            'product description' => 'description',
            'content' => 'description',
            'short description' => 'short_description',
            'short_description' => 'short_description',
            'excerpt' => 'short_description',

            // Pricing
            'price' => 'price',
            'regular price' => 'price',
            'regular_price' => 'price',
            'sale price' => 'sale_price',
            'sale_price' => 'sale_price',
            'discounted price' => 'sale_price',

            // Inventory
            'stock' => 'stock',
            'stock quantity' => 'stock',
            'stock_quantity' => 'stock',
            'quantity' => 'stock',
            'inventory' => 'stock',
            'stock status' => 'stock_status',
            'stock_status' => 'stock_status',
            'manage stock' => 'manage_stock',
            'manage_stock' => 'manage_stock',

            // Shipping
            'weight' => 'weight',
            'length' => 'length',
            'width' => 'width',
            'height' => 'height',
            'requires shipping' => 'requires_shipping',
            'requires_shipping' => 'requires_shipping',

            // Status
            'status' => 'status',
            'product status' => 'status',
            'featured' => 'featured',
            'is featured' => 'featured',
            'product type' => 'product_type',
            'product_type' => 'product_type',
            'type' => 'product_type',
            'virtual' => 'is_virtual',
            'is virtual' => 'is_virtual',
            'is_virtual' => 'is_virtual',
            'downloadable' => 'is_downloadable',
            'is downloadable' => 'is_downloadable',
            'is_downloadable' => 'is_downloadable',

            // Taxonomy
            'categories' => 'categories',
            'category' => 'categories',
            'product categories' => 'categories',
            'product_categories' => 'categories',
            'tags' => 'tags',
            'tag' => 'tags',
            'product tags' => 'tags',
            'product_tags' => 'tags',

            // Images
            'image' => 'image',
            'main image' => 'image',
            'product image' => 'image',
            'thumbnail' => 'image',
            'featured image' => 'image',
            'gallery' => 'gallery_images',
            'gallery images' => 'gallery_images',
            'gallery_images' => 'gallery_images',
            'additional images' => 'gallery_images',

            // Variations
            'has variations' => 'has_variations',
            'has_variations' => 'has_variations',
            'variation mode' => 'variation_mode',
            'variation_mode' => 'variation_mode',
            'variations' => 'variations',

            // Barcodes
            'barcode' => 'barcode_primary',
            'barcode primary' => 'barcode_primary',
            'barcode_primary' => 'barcode_primary',
            'primary barcode' => 'barcode_primary',
            'ean' => 'barcode_primary',
            'upc' => 'barcode_primary',
            'barcode type' => 'barcode_type',
            'barcode_type' => 'barcode_type',

            // Kits
            'kit type' => 'kit_type',
            'kit_type' => 'kit_type',
            'kit auto price' => 'kit_auto_price',
            'kit_auto_price' => 'kit_auto_price',
            'kit components' => 'kit_components',
            'kit_components' => 'kit_components',
            'components' => 'kit_components',

            // Downloads
            'downloads' => 'downloads',
            'download files' => 'downloads',

            // Tax
            'tax rate' => 'tax_rate_id',
            'tax rate id' => 'tax_rate_id',
            'tax_rate_id' => 'tax_rate_id',
        ];

        // WooCommerce specific mappings
        $woo_map = [
            'post_title' => 'name',
            'post_content' => 'description',
            'post_excerpt' => 'short_description',
            'post_name' => 'slug',
            '_regular_price' => 'price',
            '_sale_price' => 'sale_price',
            '_sku' => 'sku',
            '_stock' => 'stock',
            '_stock_status' => 'stock_status',
            '_manage_stock' => 'manage_stock',
            '_weight' => 'weight',
            '_length' => 'length',
            '_width' => 'width',
            '_height' => 'height',
            'product_cat' => 'categories',
            'product_tag' => 'tags',
            '_thumbnail_id' => 'image',
            '_product_image_gallery' => 'gallery_images',
            '_virtual' => 'is_virtual',
            '_downloadable' => 'is_downloadable',
        ];

        // Merge WooCommerce mappings
        $direct_map = array_merge($direct_map, $woo_map);

        foreach ($csv_headers as $header) {
            $normalized = strtolower(trim($header));

            // Check direct mapping
            if (isset($direct_map[$normalized])) {
                $mapping[$header] = $direct_map[$normalized];
                continue;
            }

            // Check for attribute prefix (attr:, attribute:)
            if (preg_match('/^(attr:|attribute:)\s*(.+)$/i', $header, $matches)) {
                $attr_name = trim($matches[2]);
                $mapping[$header] = 'attr:' . $attr_name;
                continue;
            }

            // Try fuzzy matching for attributes
            foreach ($available_fields as $field_key => $field_label) {
                if (strpos($field_key, 'attr:') === 0) {
                    $attr_name = substr($field_key, 5);
                    if (strcasecmp($normalized, $attr_name) === 0) {
                        $mapping[$header] = $field_key;
                        break;
                    }
                }
            }

            // Default to skip
            if (!isset($mapping[$header])) {
                $mapping[$header] = '';
            }
        }

        return $mapping;
    }

    /**
     * Get saved mapping presets
     *
     * @return array Saved mappings
     */
    public function get_saved_mappings() {
        return get_option(self::SAVED_MAPPINGS_OPTION, []);
    }

    /**
     * Save a mapping preset
     *
     * @param string $name Preset name
     * @param array $mapping The mapping configuration
     * @return bool Success status
     */
    public function save_mapping($name, $mapping) {
        $saved = $this->get_saved_mappings();

        $saved[sanitize_title($name)] = [
            'name' => sanitize_text_field($name),
            'mapping' => $mapping,
            'created' => time()
        ];

        return update_option(self::SAVED_MAPPINGS_OPTION, $saved);
    }

    /**
     * Delete a saved mapping preset
     *
     * @param string $preset_key Preset key
     * @return bool Success status
     */
    public function delete_mapping($preset_key) {
        $saved = $this->get_saved_mappings();

        if (isset($saved[$preset_key])) {
            unset($saved[$preset_key]);
            return update_option(self::SAVED_MAPPINGS_OPTION, $saved);
        }

        return false;
    }

    /**
     * Load a saved mapping preset
     *
     * @param string $preset_key Preset key
     * @return array|null Mapping or null if not found
     */
    public function load_mapping($preset_key) {
        $saved = $this->get_saved_mappings();

        if (isset($saved[$preset_key])) {
            return $saved[$preset_key]['mapping'];
        }

        return null;
    }

    /**
     * Validate a mapping configuration
     *
     * @param array $mapping Mapping to validate
     * @return array Validation result with 'valid' boolean and 'errors' array
     */
    public function validate_mapping($mapping) {
        $errors = [];
        $has_name = false;

        foreach ($mapping as $csv_column => $field) {
            if ($field === 'name') {
                $has_name = true;
                break;
            }
        }

        if (!$has_name) {
            $errors[] = __('Product Name field must be mapped', 'ggm-commerce');
        }

        return [
            'valid' => empty($errors),
            'errors' => $errors
        ];
    }

    /**
     * Get mapping statistics for UI display
     *
     * @param array $mapping Current mapping
     * @param array $csv_headers CSV headers
     * @return array Statistics
     */
    public function get_mapping_stats($mapping, $csv_headers) {
        $total = count($csv_headers);
        $mapped = 0;
        $auto_matched = 0;
        $skipped = 0;

        foreach ($mapping as $csv_column => $field) {
            if (!empty($field)) {
                $mapped++;
            } else {
                $skipped++;
            }
        }

        return [
            'total_columns' => $total,
            'mapped' => $mapped,
            'skipped' => $skipped,
            'percentage' => $total > 0 ? round(($mapped / $total) * 100) : 0
        ];
    }
}
