<?php

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

class FlowDino_WC_Sizes_Tab {
    
    private $api;
    private $database;
    
    public function __construct() {
        $this->api = new FlowDino_WC_API();
        $this->database = new FlowDino_WC_Database();
    }
    
    public function render() {
        // Handle form submission
        if (isset($_POST['submit']) && isset($_POST['flowdino_sizes_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_sizes_nonce'])), 'flowdino_sizes')) {
            try {
                // Save default size
                if (isset($_POST['default_size'])) {
                    update_option('flowdino_default_size', sanitize_text_field(wp_unslash($_POST['default_size'])));
                }
                
                // Save default size name
                if (isset($_POST['default_size_name'])) {
                    update_option('flowdino_default_size_name', sanitize_text_field(wp_unslash($_POST['default_size_name'])));
                }
                
                // Save size mappings for WooCommerce sizes
                foreach ($_POST as $key => $value) {
                    $key = sanitize_key($key);
                    if (strpos($key, 'flowdino_size_') === 0) {
                        $option_name = 'flowdino_size_mapping_' . str_replace('flowdino_size_', '', $key);
                        update_option($option_name, sanitize_text_field(wp_unslash($value)));
                    }
                }
                
                echo '<div class="notice notice-success"><p>' . esc_html__('Size mappings saved successfully.', 'flowdino') . '</p></div>';
                
            } catch (Exception $e) {
                // translators: %s is the error message
                echo '<div class="notice notice-error"><p>' . esc_html(sprintf(esc_html(__('Error saving size mappings: %s', 'flowdino')), esc_html($e->getMessage()))) . '</p></div>';
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino: Size mapping save error - ' . $e->getMessage());
            }
        }
        
        // Get WooCommerce sizes
        $wc_sizes = $this->get_wc_sizes();
        
        // Get FlowDino sizes
        $flowdino_sizes = $this->get_flowdino_sizes();
        
        // Get current default size
        $default_size = get_option('flowdino_default_size', '');
        $default_size_name = get_option('flowdino_default_size_name', '');

        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('Sizes Mapping', 'flowdino'); ?></h2>
            <p><?php esc_html_e('Map your WooCommerce size attributes to FlowDino sizes to enable product synchronization.', 'flowdino'); ?></p>
            
            <?php if (empty($wc_sizes)): ?>
                <div class="notice notice-info">
                    <p><?php esc_html_e('No size attributes found in WooCommerce. You can create size attributes in WooCommerce > Products > Attributes.', 'flowdino'); ?></p>
                    <p><?php esc_html_e('Common size attribute names: pa_size, pa_taille, size, taille.', 'flowdino'); ?></p>
                </div>
            <?php else: ?>
                
                <form method="post" action="">
                    <?php wp_nonce_field('flowdino_sizes', 'flowdino_sizes_nonce'); ?>
                    
                    <!-- Default Size Section -->
                    <div class="card" style="margin-bottom: 20px;">
                        <h3 style="margin: 15px;"><?php esc_html_e('Default Size Selection', 'flowdino'); ?></h3>
                        <div style="padding: 15px;">
                            <table class="form-table">
                                <tr>
                                    <th scope="row"><?php esc_html_e('Default Size', 'flowdino'); ?></th>
                                    <td>
                                        <?php if (empty($flowdino_sizes)): ?>
                                            <?php 
                                            $token = get_option('flowdino_token', '');
                                            $email = get_option('flowdino_email', '');
                                            ?>
                                            <div style="background: #ffeaa7; border: 1px solid #fdcb6e; padding: 10px; border-radius: 4px;">
                                                <p style="margin: 0; color: #2d3436;">
                                                    <strong><?php esc_html_e('Unable to retrieve FlowDino sizes', 'flowdino'); ?></strong><br>
                                                    <?php if (empty($token) || empty($email)): ?>
                                                        <?php esc_html_e('Please login to FlowDino API in the Settings tab first.', 'flowdino'); ?>
                                                    <?php else: ?>
                                                        <?php esc_html_e('Please check your API connection and credentials in the Settings tab.', 'flowdino'); ?>
                                                    <?php endif; ?>
                                                </p>
                                            </div>
                                        <?php else: ?>
                                            <select name="default_size" class="flowdino-select2">
                                                <option value=""><?php esc_html_e('-- Select a default FlowDino size --', 'flowdino'); ?></option>
                                                <?php foreach ($flowdino_sizes as $size): ?>
                                                    <option value="<?php echo esc_attr($size['id']); ?>" 
                                                            data-name="<?php echo esc_attr($size['name']); ?>"
                                                            <?php selected($default_size, $size['id']); ?>>
                                                        <?php echo esc_html($size['name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <input type="hidden" name="default_size_name" value="<?php echo esc_attr($default_size_name); ?>" />
                                        <?php endif; ?>
                                        <p class="description"><?php esc_html_e('This size will be used when no specific mapping is found for a product.', 'flowdino'); ?></p>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <?php if (!empty($wc_sizes)): ?>
                        <!-- Sizes Mapping Section -->
                        <div class="card">
                            <h3 style="margin: 15px;"><?php esc_html_e('Sizes Mapping', 'flowdino'); ?></h3>
                            <div style="padding: 15px;">
                                <div class="table-responsive">
                                    <table class="wp-list-table widefat fixed striped">
                                        <thead>
                                            <tr>
                                                <th style="width: 40%;"><?php esc_html_e('WooCommerce Size', 'flowdino'); ?></th>
                                                <th style="width: 60%;"><?php esc_html_e('FlowDino Size', 'flowdino'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($wc_sizes as $wc_size): ?>
                                                <?php 
                                                $size_id = isset($wc_size['id']) ? $wc_size['id'] : 0;
                                                $size_name = isset($wc_size['name']) ? $wc_size['name'] : '';
                                                $size_count = isset($wc_size['count']) ? $wc_size['count'] : 0;
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo esc_html($size_name); ?></strong>
                                                        <?php if ($size_count > 0): ?>
                                                            <span style="color: #666; font-size: 0.9em;">
                                                                (<?php echo esc_html($size_count); ?> <?php esc_html_e('products', 'flowdino'); ?>)
                                                            </span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if (empty($flowdino_sizes)): ?>
                                                            <p style="color: #d63638; font-style: italic; font-size: 0.9em;">
                                                                <?php esc_html_e('Unable to retrieve FlowDino sizes', 'flowdino'); ?>
                                                            </p>
                                                        <?php else: ?>
                                                            <?php $current_mapping = get_option('flowdino_size_mapping_' . $size_id, ''); ?>
                                                            <select name="flowdino_size_<?php echo esc_attr($size_id); ?>" class="flowdino-select2-mapping">
                                                                <option value=""><?php esc_html_e('-- Select a FlowDino size --', 'flowdino'); ?></option>
                                                                <?php foreach ($flowdino_sizes as $flowdino_size): ?>
                                                                    <option value="<?php echo esc_attr($flowdino_size['id']); ?>" 
                                                                            <?php selected($current_mapping, $flowdino_size['id']); ?>>
                                                                        <?php echo esc_html($flowdino_size['name']); ?>
                                                                    </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <p class="submit">
                        <input type="submit" name="submit" class="button button-primary" value="<?php esc_html_e('Save Size Mappings', 'flowdino'); ?>" />
                    </p>
                </form>
            <?php endif; ?>
        </div>
        
        <?php
    }
    
    /**
     * Get FlowDino sizes from API
     */
    private function get_flowdino_sizes() {
        try {
            $api_response = $this->api->get_sizes();
            
            // L'API sizes retourne directement un tableau, pas une structure avec 'member'
            if ($api_response && is_array($api_response)) {
                $sizes = array();
                
                foreach ($api_response as $size) {
                    if (isset($size['id']) && isset($size['name'])) {
                        $sizes[] = array(
                            'id' => $size['id'],
                            'name' => $size['name']
                        );
                    }
                }
                
                // Sort sizes by orderSize if available, otherwise by name
                usort($sizes, function($a, $b) use ($api_response) {
                    // Récupérer les données complètes pour le tri
                    $size_a = null;
                    $size_b = null;
                    
                    foreach ($api_response as $original_size) {
                        if ($original_size['id'] == $a['id']) {
                            $size_a = $original_size;
                        }
                        if ($original_size['id'] == $b['id']) {
                            $size_b = $original_size;
                        }
                    }
                    
                    // Trier par orderSize si disponible
                    if ($size_a && $size_b && isset($size_a['orderSize']) && isset($size_b['orderSize'])) {
                        return $size_a['orderSize'] - $size_b['orderSize'];
                    }
                    
                    // Sinon trier par nom
                    return strcasecmp($a['name'], $b['name']);
                });
                
                return $sizes;
            }
            
            return array();
            
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Error retrieving sizes - ' . $e->getMessage());
            return array();
        }
    }
    
    /**
     * Get WooCommerce size attributes from various sources
     * Returns standardized array format for consistent interface
     */
    private function get_wc_sizes() {
        $sizes = array();
        $found_taxonomy = '';
        
        // Method 1: Try product_attribute_size taxonomy (most common size attribute)
        if (taxonomy_exists('pa_size')) {
            $size_terms = get_terms(array(
                'taxonomy' => 'pa_size',
                'hide_empty' => false
            ));
            if (!is_wp_error($size_terms) && !empty($size_terms)) {
                $found_taxonomy = 'pa_size';
                foreach ($size_terms as $term) {
                    $sizes[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_size'
                    );
                }
            }
        }
        
        // Method 2: Try size taxonomy
        if (empty($sizes) && taxonomy_exists('size')) {
            $size_terms = get_terms(array(
                'taxonomy' => 'size',
                'hide_empty' => false
            ));
            if (!is_wp_error($size_terms) && !empty($size_terms)) {
                $found_taxonomy = 'size';
                foreach ($size_terms as $term) {
                    $sizes[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'size'
                    );
                }
            }
        }
        
        // Method 3: Try pa_taille (French alternative)
        if (empty($sizes) && taxonomy_exists('pa_taille')) {
            $size_terms = get_terms(array(
                'taxonomy' => 'pa_taille',
                'hide_empty' => false
            ));
            if (!is_wp_error($size_terms) && !empty($size_terms)) {
                $found_taxonomy = 'pa_taille';
                foreach ($size_terms as $term) {
                    $sizes[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_taille'
                    );
                }
            }
        }
        
        // Method 4: Try pa_sizes (plural form)
        if (empty($sizes) && taxonomy_exists('pa_sizes')) {
            $size_terms = get_terms(array(
                'taxonomy' => 'pa_sizes',
                'hide_empty' => false
            ));
            if (!is_wp_error($size_terms) && !empty($size_terms)) {
                $found_taxonomy = 'pa_sizes';
                foreach ($size_terms as $term) {
                    $sizes[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_sizes'
                    );
                }
            }
        }
        
        // Method 5: Search for any product attribute with size-related keywords
        if (empty($sizes)) {
            $all_attributes = wc_get_attribute_taxonomies();
            foreach ($all_attributes as $attribute) {
                $attribute_name = strtolower($attribute->attribute_name);
                if (strpos($attribute_name, 'size') !== false || 
                    strpos($attribute_name, 'taille') !== false ||
                    strpos($attribute_name, 'sizes') !== false ||
                    strpos($attribute_name, 'pointure') !== false) {
                    $taxonomy = 'pa_' . $attribute->attribute_name;
                    if (taxonomy_exists($taxonomy)) {
                        $size_terms = get_terms(array(
                            'taxonomy' => $taxonomy,
                            'hide_empty' => false
                        ));
                        if (!is_wp_error($size_terms) && !empty($size_terms)) {
                            $found_taxonomy = $taxonomy;
                            foreach ($size_terms as $term) {
                                $sizes[] = array(
                                    'id' => $term->term_id,
                                    'name' => $term->name,
                                    'count' => $term->count,
                                    'taxonomy' => $taxonomy
                                );
                            }
                            break; // Use the first size attribute found
                        }
                    }
                }
            }
        }
        
        // Log which taxonomy was found for debugging
        if (!empty($sizes)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Found WC sizes using taxonomy: ' . $found_taxonomy);
        } else {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: No WC size attributes found');
        }
        
        return $sizes;
    }
}
