<?php

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

class FlowDino_WC_Materials_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_materials_nonce']) &&
            wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_materials_nonce'])), 'flowdino_materials')
        ) {
            try {
                // Save default material
                if (isset($_POST['default_material'])) {
                    update_option('flowdino_default_material', sanitize_text_field(wp_unslash($_POST['default_material'])));
                }
                
                // Save default material name
                if (isset($_POST['default_material_name'])) {
                    update_option('flowdino_default_material_name', sanitize_text_field(wp_unslash($_POST['default_material_name'])));
                }
                
                // Save material mappings for WooCommerce materials
                foreach ($_POST as $key => $value) {
                    $key = sanitize_key($key);
                    if (strpos($key, 'flowdino_material_') === 0) {
                        $option_name = 'flowdino_material_mapping_' . str_replace('flowdino_material_', '', $key);
                        update_option($option_name, sanitize_text_field(wp_unslash($value)));
                    }
                }
                
                echo '<div class="notice notice-success"><p>' . esc_html(__('Material 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 material mappings: %s', 'flowdino')), esc_html($e->getMessage())) . '</p></div>';
                // error_log('FlowDino: Material mapping save error - ' . $e->getMessage());
            }
        }
        
        // Get WooCommerce materials
        $wc_materials = $this->get_wc_materials();
        
        // Get FlowDino materials
        $flowdino_materials = $this->get_flowdino_materials();
        
        // Get current default material
        $default_material = get_option('flowdino_default_material', '');
        $default_material_name = get_option('flowdino_default_material_name', '');
        
        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('Materials Mapping', 'flowdino'); ?></h2>
            <p><?php esc_html_e('Map your WooCommerce material attributes to FlowDino materials to enable product synchronization.', 'flowdino'); ?></p>
            
            <?php if (empty($wc_materials)): ?>
                <div class="notice notice-info">
                    <p><?php esc_html_e('No material attributes found in WooCommerce. You can create material attributes in WooCommerce > Products > Attributes.', 'flowdino'); ?></p>
                    <p><?php esc_html_e('Common material attribute names: pa_material, pa_matiere, material, matiere, composition.', 'flowdino'); ?></p>
                </div>
            <?php else: ?>
                
                <form method="post" action="">
                    <?php wp_nonce_field('flowdino_materials', 'flowdino_materials_nonce'); ?>
                    
                    <!-- Default Material Section -->
                    <div class="card" style="margin-bottom: 20px;">
                        <h3 style="margin: 15px;"><?php esc_html_e('Default Material Selection', 'flowdino'); ?></h3>
                        <div style="padding: 15px;">
                            <table class="form-table">
                                <tr>
                                    <th scope="row"><?php esc_html_e('Default Material', 'flowdino'); ?></th>
                                    <td>
                                        <?php if (empty($flowdino_materials)): ?>
                                            <?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 materials', '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_material" class="flowdino-select2">
                                                <option value=""><?php esc_html_e('-- Select a default FlowDino material --', 'flowdino'); ?></option>
                                                <?php foreach ($flowdino_materials as $material): ?>
                                                    <option value="<?php echo esc_attr($material['id']); ?>" 
                                                            data-name="<?php echo esc_attr($material['name']); ?>"
                                                            <?php selected($default_material, $material['id']); ?>>
                                                        <?php echo esc_html($material['name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <input type="hidden" name="default_material_name" value="<?php echo esc_attr($default_material_name); ?>" />
                                        <?php endif; ?>
                                        <p class="description"><?php esc_html_e('This material will be used when no specific mapping is found for a product.', 'flowdino'); ?></p>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <?php if (!empty($wc_materials)): ?>
                        <!-- Materials Mapping Section -->
                        <div class="card">
                            <h3 style="margin: 15px;"><?php esc_html_e('Materials 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 Material', 'flowdino'); ?></th>
                                                <th style="width: 60%;"><?php esc_html_e('FlowDino Material', 'flowdino'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($wc_materials as $wc_material): ?>
                                                <?php 
                                                $material_id = isset($wc_material['id']) ? $wc_material['id'] : 0;
                                                $material_name = isset($wc_material['name']) ? $wc_material['name'] : '';
                                                $material_count = isset($wc_material['count']) ? $wc_material['count'] : 0;
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo esc_html($material_name); ?></strong>
                                                        <?php if ($material_count > 0): ?>
                                                            <span style="color: #666; font-size: 0.9em;">
                                                                (<?php echo esc_html($material_count); ?> <?php esc_html_e('products', 'flowdino'); ?>)
                                                            </span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if (empty($flowdino_materials)): ?>
                                                            <p style="color: #d63638; font-style: italic; font-size: 0.9em;">
                                                                <?php esc_html_e('Unable to retrieve FlowDino materials', 'flowdino'); ?>
                                                            </p>
                                                        <?php else: ?>
                                                            <?php $current_mapping = get_option('flowdino_material_mapping_' . $material_id, ''); ?>
                                                            <select name="flowdino_material_<?php echo esc_html($material_id); ?>" class="flowdino-select2-mapping">
                                                                <option value=""><?php esc_html_e('-- Select a FlowDino material --', 'flowdino'); ?></option>
                                                                <?php foreach ($flowdino_materials as $flowdino_material): ?>
                                                                    <option value="<?php echo esc_attr($flowdino_material['id']); ?>" 
                                                                            <?php selected($current_mapping, $flowdino_material['id']); ?>>
                                                                        <?php echo esc_html($flowdino_material['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 Material Mappings', 'flowdino'); ?>" />
                    </p>
                </form>
            <?php endif; ?>
        </div>
        
        <?php
    }
    
    /**
     * Get FlowDino materials from API
     */
    private function get_flowdino_materials() {
        try {
            $api_response = $this->api->get_materials();
            
            if ($api_response && isset($api_response['member']) && is_array($api_response['member'])) {
                $materials = array();
                
                foreach ($api_response['member'] as $material) {
                    if (isset($material['id']) && isset($material['materialName'])) {
                        $materials[] = array(
                            'id' => $material['id'],
                            'name' => $material['materialName']
                        );
                    }
                }
                
                // Sort materials by name for better UX
                usort($materials, function($a, $b) {
                    return strcasecmp($a['name'], $b['name']);
                });
                
                return $materials;
            }
            
            return array();
            
        } catch (Exception $e) {
            // error_log('FlowDino: Error retrieving materials - ' . $e->getMessage());
            return array();
        }
    }
    
    /**
     * Get WooCommerce material attributes from various sources
     * Returns standardized array format for consistent interface
     */
    private function get_wc_materials() {
        $materials = array();
        $found_taxonomy = '';
        
        // Method 1: Try product_attribute_material taxonomy (most common material attribute)
        if (taxonomy_exists('pa_material')) {
            $material_terms = get_terms(array(
                'taxonomy' => 'pa_material',
                'hide_empty' => false
            ));
            if (!is_wp_error($material_terms) && !empty($material_terms)) {
                $found_taxonomy = 'pa_material';
                foreach ($material_terms as $term) {
                    $materials[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_material'
                    );
                }
            }
        }
        
        // Method 2: Try material taxonomy
        if (empty($materials) && taxonomy_exists('material')) {
            $material_terms = get_terms(array(
                'taxonomy' => 'material',
                'hide_empty' => false
            ));
            if (!is_wp_error($material_terms) && !empty($material_terms)) {
                $found_taxonomy = 'material';
                foreach ($material_terms as $term) {
                    $materials[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'material'
                    );
                }
            }
        }
        
        // Method 3: Try pa_matiere (French alternative)
        if (empty($materials) && taxonomy_exists('pa_matiere')) {
            $material_terms = get_terms(array(
                'taxonomy' => 'pa_matiere',
                'hide_empty' => false
            ));
            if (!is_wp_error($material_terms) && !empty($material_terms)) {
                $found_taxonomy = 'pa_matiere';
                foreach ($material_terms as $term) {
                    $materials[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_matiere'
                    );
                }
            }
        }
        
        // Method 4: Try pa_composition (like PrestaShop's "Composition" feature)
        if (empty($materials) && taxonomy_exists('pa_composition')) {
            $material_terms = get_terms(array(
                'taxonomy' => 'pa_composition',
                'hide_empty' => false
            ));
            if (!is_wp_error($material_terms) && !empty($material_terms)) {
                $found_taxonomy = 'pa_composition';
                foreach ($material_terms as $term) {
                    $materials[] = array(
                        'id' => $term->term_id,
                        'name' => $term->name,
                        'count' => $term->count,
                        'taxonomy' => 'pa_composition'
                    );
                }
            }
        }
        
        // Method 5: Search for any product attribute with material-related keywords
        if (empty($materials)) {
            $all_attributes = wc_get_attribute_taxonomies();
            foreach ($all_attributes as $attribute) {
                $attribute_name = strtolower($attribute->attribute_name);
                if (strpos($attribute_name, 'material') !== false || 
                    strpos($attribute_name, 'matiere') !== false ||
                    strpos($attribute_name, 'composition') !== false ||
                    strpos($attribute_name, 'fabric') !== false ||
                    strpos($attribute_name, 'tissue') !== false ||
                    strpos($attribute_name, 'tissu') !== false) {
                    $taxonomy = 'pa_' . $attribute->attribute_name;
                    if (taxonomy_exists($taxonomy)) {
                        $material_terms = get_terms(array(
                            'taxonomy' => $taxonomy,
                            'hide_empty' => false
                        ));
                        if (!is_wp_error($material_terms) && !empty($material_terms)) {
                            $found_taxonomy = $taxonomy;
                            foreach ($material_terms as $term) {
                                $materials[] = array(
                                    'id' => $term->term_id,
                                    'name' => $term->name,
                                    'count' => $term->count,
                                    'taxonomy' => $taxonomy
                                );
                            }
                            break; // Use the first material attribute found
                        }
                    }
                }
            }
        }
        
        // Log which taxonomy was found for debugging
        if (!empty($materials)) {
            // error_log('FlowDino: Found WC materials using taxonomy: ' . $found_taxonomy);
        } else {
            // error_log('FlowDino: No WC material attributes found');
        }
        
        return $materials;
    }
}
