<?php

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

class FlowDino_WC_Colors_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_colors_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_colors_nonce'])), 'flowdino_colors')) {
            try {
                // Save default color
                if (isset($_POST['default_color'])) {
                    update_option('flowdino_default_color', sanitize_text_field(wp_unslash($_POST['default_color'])));
                }
                
                // Save default color name
                if (isset($_POST['default_color_name'])) {
                    update_option('flowdino_default_color_name', sanitize_text_field(wp_unslash($_POST['default_color_name'])));
                }
                
                // Save color mappings for WooCommerce colors
                foreach ($_POST as $key => $value) {
                    $key = sanitize_key($key);
                    if (strpos($key, 'flowdino_color_') === 0) {
                        $option_name = 'flowdino_color_mapping_' . str_replace('flowdino_color_', '', $key);
                        update_option($option_name, sanitize_text_field(wp_unslash($value)));
                    }
                }
                
            echo '<div class="notice notice-success"><p>' . esc_html__('Color mappings saved successfully.', 'flowdino') . '</p></div>';
                
            } catch (Exception $e) {
                // translators: %s is the error message
                echo '<div class="notice notice-error"><p>' . sprintf(esc_html(__('Error saving color 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: Color mapping save error - ' . $e->getMessage());
            }
        }
        
        // Get WooCommerce colors
        $wc_colors = $this->get_wc_colors();
        
        // Get FlowDino colors
        $flowdino_colors = $this->get_flowdino_colors();
        
        // Get current default color
        $default_color = get_option('flowdino_default_color', '');
        $default_color_name = get_option('flowdino_default_color_name', '');

        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('Colors Mapping', 'flowdino'); ?></h2>
            <p><?php esc_html_e('Map your WooCommerce color attributes to FlowDino colors to enable product synchronization.', 'flowdino'); ?></p>
            
            <?php if (empty($wc_colors)): ?>
                <div class="notice notice-info">
                        <p><?php esc_html_e('No color attributes found in WooCommerce. You can create color attributes in WooCommerce > Products > Attributes.', 'flowdino'); ?></p>
                        <p><?php esc_html_e('Common color attribute names: pa_color, pa_colour, pa_couleur, color, colour, couleur.', 'flowdino'); ?></p>
                </div>
            <?php else: ?>
                
                <form method="post" action="">
                    <?php wp_nonce_field('flowdino_colors', 'flowdino_colors_nonce'); ?>
                    
                    <!-- Default Color Section -->
                    <div class="card" style="margin-bottom: 20px;">
                        <h3 style="margin: 15px;"><?php esc_html_e('Default Color Selection', 'flowdino'); ?></h3>
                        <div style="padding: 15px;">
                            <table class="form-table">
                                <tr>
                                    <th scope="row"><?php esc_html_e('Default Color', 'flowdino'); ?></th>
                                    <td>
                                        <?php if (empty($flowdino_colors)): ?>
                                            <?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 colors', '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_color" class="flowdino-select2">
                                                <option value=""><?php esc_html_e('-- Select a default FlowDino color --', 'flowdino'); ?></option>
                                                <?php foreach ($flowdino_colors as $color): ?>
                                                    <option value="<?php echo esc_attr($color['id']); ?>" 
                                                            data-name="<?php echo esc_attr($color['name']); ?>"
                                                            <?php selected($default_color, $color['id']); ?>>
                                                        <?php echo esc_html($color['name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <input type="hidden" name="default_color_name" value="<?php echo esc_attr($default_color_name); ?>" />
                                        <?php endif; ?>
                                        <p class="description"><?php esc_html_e('This color will be used when no specific mapping is found for a product.', 'flowdino'); ?></p>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <?php if (!empty($wc_colors)): ?>
                        <!-- Colors Mapping Section -->
                        <div class="card">
                            <h3 style="margin: 15px;"><?php esc_html_e('Colors 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 Color', 'flowdino'); ?></th>
                                                <th style="width: 60%;"><?php esc_html_e('FlowDino Color', 'flowdino'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($wc_colors as $wc_color): ?>
                                                <?php 
                                                $color_id = isset($wc_color['id']) ? $wc_color['id'] : 0;
                                                $color_name = isset($wc_color['name']) ? $wc_color['name'] : '';
                                                $color_count = isset($wc_color['count']) ? $wc_color['count'] : 0;
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo esc_html($color_name); ?></strong>
                                                        <?php if ($color_count > 0): ?>
                                                            <span style="color: #666; font-size: 0.9em;">
                                                                (<?php echo esc_html($color_count); ?> <?php esc_html_e('products', 'flowdino'); ?>)
                                                            </span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if (empty($flowdino_colors)): ?>
                                                            <p style="color: #d63638; font-style: italic; font-size: 0.9em;">
                                                                <?php esc_html_e('Unable to retrieve FlowDino colors', 'flowdino'); ?>
                                                            </p>
                                                        <?php else: ?>
                                                            <?php $current_mapping = get_option('flowdino_color_mapping_' . $color_id, ''); ?>
                                                            <select name="flowdino_color_<?php echo esc_attr($color_id); ?>" class="flowdino-select2-mapping">
                                                                <option value=""><?php esc_html_e('-- Select a FlowDino color --', 'flowdino'); ?></option>
                                                                <?php foreach ($flowdino_colors as $flowdino_color): ?>
                                                                    <option value="<?php echo esc_attr($flowdino_color['id']); ?>" 
                                                                            <?php selected($current_mapping, $flowdino_color['id']); ?>>
                                                                        <?php echo esc_html($flowdino_color['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 Color Mappings', 'flowdino'); ?>" />
                    </p>
                </form>
            <?php endif; ?>
        </div>
        
        <?php
    }
    
    /**
     * Get FlowDino colors from API
     */
    private function get_flowdino_colors() {
        try {
            $api_response = $this->api->get_colors();
            
            if ($api_response && isset($api_response['member']) && is_array($api_response['member'])) {
                $colors = array();
                
                foreach ($api_response['member'] as $color) {
                    if (isset($color['id']) && isset($color['colorName'])) {
                        $colors[] = array(
                            'id' => $color['id'],
                            'name' => $color['colorName']
                        );
                    }
                }
                
                // Sort colors by name for better UX
                usort($colors, function($a, $b) {
                    return strcasecmp($a['name'], $b['name']);
                });
                
                return $colors;
            }
            
            return array();
            
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Error retrieving colors - ' . $e->getMessage());
            return array();
        }
    }
    
    /**
     * Get WooCommerce color attributes from various sources
     * Returns standardized array format for consistent interface
     */
    private function get_wc_colors() {
        $colors = array();
        $found_taxonomy = '';
        
        // Method 1: Try product_attribute_color taxonomy (most common color attribute)
        if (taxonomy_exists('pa_color')) {
            $color_terms = get_terms(array(
                'taxonomy' => 'pa_color',
                'hide_empty' => false
            ));
            if (!is_wp_error($color_terms) && !empty($color_terms)) {
                $found_taxonomy = 'pa_color';
                foreach ($color_terms as $term) {
                    $colors[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_color'
                    );
                }
            }
        }
        
        // Method 2: Try color taxonomy
        if (empty($colors) && taxonomy_exists('color')) {
            $color_terms = get_terms(array(
                'taxonomy' => 'color',
                'hide_empty' => false
            ));
            if (!is_wp_error($color_terms) && !empty($color_terms)) {
                $found_taxonomy = 'color';
                foreach ($color_terms as $term) {
                    $colors[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'color'
                    );
                }
            }
        }
        
        // Method 3: Try pa_colour (alternative spelling)
        if (empty($colors) && taxonomy_exists('pa_colour')) {
            $color_terms = get_terms(array(
                'taxonomy' => 'pa_colour',
                'hide_empty' => false
            ));
            if (!is_wp_error($color_terms) && !empty($color_terms)) {
                $found_taxonomy = 'pa_colour';
                foreach ($color_terms as $term) {
                    $colors[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_colour'
                    );
                }
            }
        }

        // Method 4: Try pa_couleur (French alternative)
        if (empty($colors) && taxonomy_exists('pa_couleur')) {
            $color_terms = get_terms(array(
                'taxonomy' => 'pa_couleur',
                'hide_empty' => false
            ));
            if (!is_wp_error($color_terms) && !empty($color_terms)) {
                $found_taxonomy = 'pa_couleur';
                foreach ($color_terms as $term) {
                    $colors[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_couleur'
                    );
                }
            }
        }

        // Method 5: Try couleur taxonomy
        if (empty($colors) && taxonomy_exists('couleur')) {
            $color_terms = get_terms(array(
                'taxonomy' => 'couleur',
                'hide_empty' => false
            ));
            if (!is_wp_error($color_terms) && !empty($color_terms)) {
                $found_taxonomy = 'couleur';
                foreach ($color_terms as $term) {
                    $colors[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'couleur'
                    );
                }
            }
        }
        
        // Method 6: Search for any product attribute with "color", "colour" or "couleur" in the name
        if (empty($colors)) {
            $all_attributes = wc_get_attribute_taxonomies();
            foreach ($all_attributes as $attribute) {
                $attribute_name = strtolower($attribute->attribute_name);
                if (strpos($attribute_name, 'color') !== false || strpos($attribute_name, 'colour') !== false || strpos($attribute_name, 'couleur') !== false) {
                    $taxonomy = 'pa_' . $attribute->attribute_name;
                    if (taxonomy_exists($taxonomy)) {
                        $color_terms = get_terms(array(
                            'taxonomy' => $taxonomy,
                            'hide_empty' => false
                        ));
                        if (!is_wp_error($color_terms) && !empty($color_terms)) {
                            $found_taxonomy = $taxonomy;
                            foreach ($color_terms as $term) {
                                $colors[] = array(
                                    'id' => $term->term_id,
                                    'name' => $term->name,
                                    'count' => $term->count,
                                    'taxonomy' => $taxonomy
                                );
                            }
                            break; // Use the first color attribute found
                        }
                    }
                }
            }
        }
        
        // Log which taxonomy was found for debugging
        if (!empty($colors)) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Found WC colors using taxonomy: ' . $found_taxonomy);
        } else {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: No WC color attributes found');
        }
        
        return $colors;
    }
}
