<?php
/**
 * FlowDino Categories Tab
 * 
 * Handles the category mapping interface for the FlowDino plugin
 * 
 * @package FlowDino
 * @subpackage Admin\Tabs
 * @since 1.0.0
 */

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

/**
 * FlowDino Categories Tab Class
 */
class FlowDino_WC_Categories_Tab {
    
    /**
     * Constructor
     */
    public function __construct() {
        // Add any initialization if needed
    }
    
    /**
     * Render categories tab content
     * 
     * Main content area for the categories tab
     */
    public function render() {
        // Check if required classes exist
        if (!class_exists('FlowDino_WC_API') || !class_exists('FlowDino_WC_Database')) {
            echo '<div class="notice notice-error"><p>' . esc_html(__('Required FlowDino classes not found. Please check plugin installation.', 'flowdino')) . '</p></div>';
            return;
        }
        
        $api = new FlowDino_WC_API();
        $database = new FlowDino_WC_Database();
        
        // Handle form submission
        if (isset($_POST['save_category_mapping']) && isset($_POST['flowdino_categories_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_categories_nonce'])), 'flowdino_categories')) {
            $this->handle_form_submission($api, $database);
        }
        
        // Get WooCommerce categories with hierarchy
        try {
            $wc_categories = $this->get_wc_categories_hierarchy();
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Error getting WC categories: ' . $e->getMessage());
            $wc_categories = array();
        }
        
        // Get FlowDino categories
        $flowdino_categories = array();
        try {
            if (!empty($api->get_token())) {
                $flowdino_categories = $api->get_categories();
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino: Error getting FlowDino categories: ' . $e->getMessage());
            $flowdino_categories = array();
        }
        
        $this->render_categories_interface($api, $database, $wc_categories, $flowdino_categories);
    }
    
    /**
     * Handle form submission for category mappings
     */
    private function handle_form_submission($api, $database) {
        try {
            // Validate that database connection is available
            global $wpdb;
            if (!$wpdb) {
                throw new Exception('Database connection not available');
            }
            
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification handled in calling method
            $category_mappings = isset($_POST['category_mapping']) ? map_deep(wp_unslash($_POST['category_mapping']), 'sanitize_text_field') : array();
            $success_count = 0;
            $error_count = 0;
            
            // Validate category_mappings is an array
            if (!is_array($category_mappings)) {
                throw new Exception('Invalid category mapping data');
            }
            
            foreach ($category_mappings as $wc_cat_id => $flowdino_cat_id) {
                // Sanitize the values
                $wc_cat_id = sanitize_text_field($wc_cat_id);
                $flowdino_cat_id = sanitize_text_field($flowdino_cat_id);
                
                try {
                    // Validate inputs
                    if (!is_numeric($wc_cat_id)) {
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                        error_log('FlowDino: Invalid WC category ID: ' . $wc_cat_id);
                        $error_count++;
                        continue;
                    }
                    
                    if (!empty($flowdino_cat_id) && is_numeric($flowdino_cat_id)) {
                        // Utiliser le format d'options individuelles comme pour les couleurs/matériaux
                        $option_name = 'flowdino_category_mapping_' . intval($wc_cat_id);
                        $result = update_option($option_name, intval($flowdino_cat_id));
                        if ($result !== false) {
                            $success_count++;
                            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                            error_log('FlowDino: Successfully set category mapping: ' . $option_name . ' = ' . intval($flowdino_cat_id));
                        } else {
                            $error_count++;
                            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                            error_log('FlowDino: Failed to set mapping for WC cat ' . $wc_cat_id . ' -> FlowDino cat ' . $flowdino_cat_id);
                        }
                    } else {
                        // Supprimer le mapping
                        $option_name = 'flowdino_category_mapping_' . intval($wc_cat_id);
                        $result = delete_option($option_name);
                        if ($result !== false) {
                            $success_count++;
                            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                            error_log('FlowDino: Successfully deleted category mapping: ' . $option_name);
                        } else {
                            $error_count++;
                            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                            error_log('FlowDino: Failed to delete mapping for WC cat ' . $wc_cat_id);
                        }
                    }
                } catch (Exception $e) {
                    $error_count++;
                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                    error_log('FlowDino Category Mapping Error for WC cat ' . $wc_cat_id . ': ' . $e->getMessage());
                }
            }
            
            if ($error_count > 0) {
                // translators: %d is the number of errors
                echo '<div class="notice notice-warning"><p>' . sprintf(esc_html(__('Category mappings saved with %d errors. Check error logs for details.', 'flowdino')), esc_html($error_count)) . '</p></div>';
            } else {
                echo '<div class="notice notice-success"><p>' . esc_html(__('Category mappings saved successfully!', 'flowdino')) . '</p></div>';
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino Category Mapping Critical Error: ' . $e->getMessage());
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino Stack trace: ' . $e->getTraceAsString());
            // translators: %s is the error message
            echo '<div class="notice notice-error"><p>' . sprintf(esc_html(__('An error occurred while saving category mappings: %s', 'flowdino')), esc_html($e->getMessage())) . '</p></div>';
        } catch (Error $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino Category Mapping Fatal Error: ' . $e->getMessage());
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino Stack trace: ' . $e->getTraceAsString());
            // translators: %s is the error message
            echo '<div class="notice notice-error"><p>' . sprintf(esc_html(__('A fatal error occurred: %s', 'flowdino')), esc_html($e->getMessage())) . '</p></div>';
        }
    }
    
    /**
     * Render the categories interface
     */
    private function render_categories_interface($api, $database, $wc_categories, $flowdino_categories) {
        // Force-load select2 CSS — wp_enqueue_style outputs before wp_head which is already past.
        global $wp_styles;
        if (isset($wp_styles->registered['select2'])) {
            echo '<link rel="stylesheet" type="text/css" href="' . esc_url($wp_styles->registered['select2']->src) . '">';
        }
        // Inline fallback: the two critical rules that make select2 visible.
        ?>
        <style>
        .select2-hidden-accessible{clip:rect(0,0,0,0)!important;border:0!important;height:1px!important;overflow:hidden!important;padding:0!important;position:absolute!important;width:1px!important;white-space:nowrap!important}
        .select2-container{box-sizing:border-box;display:inline-block!important;margin:0;position:relative;vertical-align:middle}
        .select2-container .select2-selection--single{box-sizing:border-box;cursor:pointer;display:block;height:28px;user-select:none;-webkit-user-select:none}
        .select2-container--default .select2-selection--single{background-color:#fff;border:1px solid #aaa;border-radius:4px}
        .select2-container--default .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px;padding-left:8px;padding-right:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
        .select2-container--default .select2-selection--single .select2-selection__arrow{height:26px;position:absolute;top:1px;right:1px;width:20px}
        .select2-container--default .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0}
        .select2-dropdown{background-color:#fff;border:1px solid #aaa;border-radius:4px;box-sizing:border-box;display:block;position:absolute;width:100%;z-index:1051}
        .select2-search--dropdown .select2-search__field{padding:4px;width:100%;box-sizing:border-box}
        .select2-results__option{padding:6px;user-select:none;-webkit-user-select:none}
        .select2-container--default .select2-results__option--highlighted[aria-selected]{background-color:#5897fb;color:#fff}
        </style>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('Categories Mapping', 'flowdino'); ?></h2>
            <p><?php esc_html_e('Map your WooCommerce categories to FlowDino categories to enable product synchronization.', 'flowdino'); ?></p>
            
            <?php if (empty($api->get_token())): ?>
                <div class="notice notice-warning">
                    <p><?php esc_html_e('Please configure your FlowDino credentials in the Settings tab first.', 'flowdino'); ?></p>
                    <p><a href="?page=flowdino-sync&tab=settings" class="button"><?php esc_html_e('Go to Settings', 'flowdino'); ?></a></p>
                </div>
            <?php elseif (empty($flowdino_categories) || !isset($flowdino_categories['data']) || empty($flowdino_categories['data'])): ?>
                <div class="notice notice-error">
                    <p><?php esc_html_e('Unable to load FlowDino categories. Please check your connection.', 'flowdino'); ?></p>
                    <p><?php esc_html_e('Please verify:', 'flowdino'); ?></p>
                    <ul>
                        <li><?php esc_html_e('Your FlowDino API credentials are correct', 'flowdino'); ?></li>
                        <li><?php esc_html_e('Your server can connect to FlowDino API', 'flowdino'); ?></li>
                        <li><?php esc_html_e('You have categories configured in your FlowDino account', 'flowdino'); ?></li>
                    </ul>
                    <p><a href="?page=flowdino-sync&tab=settings" class="button"><?php esc_html_e('Test Connection', 'flowdino'); ?></a></p>
                </div>
            <?php else: ?>
                <!-- Success: categories loaded -->
                <div class="notice notice-success">
                    <?php /* translators: %d is the number of categories loaded */ ?>
                    <p><?php printf(esc_html(__('Successfully loaded %d categories from FlowDino.', 'flowdino')), count($flowdino_categories['data'])); ?></p>
                </div>
                
                <?php if (empty($wc_categories)): ?>
                    <div class="notice notice-info">
                        <p><?php esc_html_e('No WooCommerce categories found. You can create categories in WooCommerce > Products > Categories.', 'flowdino'); ?></p>
                    </div>
                <?php else: ?>
                    <form method="post" action="">
                        <?php wp_nonce_field('flowdino_categories', 'flowdino_categories_nonce'); ?>
                        
                        <div class="table-responsive">
                            <table class="wp-list-table widefat fixed striped">
                                <thead>
                                    <tr>
                                        <th style="width: 40%;"><?php esc_html_e('WooCommerce Category', 'flowdino'); ?></th>
                                        <th style="width: 60%;"><?php esc_html_e('FlowDino Category', 'flowdino'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($wc_categories as $wc_category): ?>
                                        <?php $current_mapping = get_option('flowdino_category_mapping_' . $wc_category->term_id, ''); ?>
                                        <tr>
                                            <td>
                                                <?php 
                                                // Afficher l'indentation pour l'arborescence
                                                if ($wc_category->parent > 0) {
                                                    $depth = $this->get_category_depth($wc_category->term_id);
                                                    echo esc_html(str_repeat('   ', $depth));
                                                    echo '└─ ';
                                                }
                                                echo esc_html($wc_category->name);
                                                ?>
                                                <span style="color: #666; font-size: 0.9em;">(<?php echo esc_html($wc_category->count); ?> <?php esc_html_e('products', 'flowdino'); ?>)</span>
                                            </td>
                                            <td>
                                                <select name="category_mapping[<?php echo esc_attr($wc_category->term_id); ?>]" 
                                                        class="flowdino-category-select" 
                                                        data-wc-category="<?php echo esc_attr($wc_category->term_id); ?>"
                                                        data-current-mapping="<?php echo esc_attr($current_mapping ? $current_mapping : ''); ?>"
                                                        data-placeholder="<?php esc_html_e('Search for a FlowDino category...', 'flowdino'); ?>"
                                                        style="width: 100%; max-width: 500px;">
                                                    <option value=""><?php esc_html_e('-- Select FlowDino Category --', 'flowdino'); ?></option>
                                                    <?php if (is_array($flowdino_categories) && isset($flowdino_categories['data'])): ?>
                                                        <?php 
                                                        $this->render_flowdino_category_options_with_path($flowdino_categories['data'], $current_mapping, array());
                                                        ?>
                                                    <?php endif; ?>
                                                </select>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <p class="submit">
                            <input type="submit" name="save_category_mapping" class="button-primary" 
                                   value="<?php esc_html_e('Save Category Mappings', 'flowdino'); ?>" />
                        </p>
                    </form>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <script>
        (function($) {
            function initCategorySelect2() {
                var fn = typeof $.fn.selectWoo !== 'undefined' ? 'selectWoo'
                       : (typeof $.fn.select2 !== 'undefined' ? 'select2' : null);
                if (!fn) { return false; }
                $('.flowdino-category-select').each(function() {
                    if ($(this).data('select2')) { return; }
                    $(this)[fn]({
                        width: '100%',
                        placeholder: $(this).data('placeholder') || '-- Select --',
                        allowClear: true,
                        matcher: function(params, data) {
                            if ($.trim(params.term) === '') { return data; }
                            if (data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) { return data; }
                            return null;
                        }
                    });
                });
                return true;
            }

            $(document).ready(function() {
                if (!initCategorySelect2()) {
                    var attempts = 0;
                    var interval = setInterval(function() {
                        attempts++;
                        if (initCategorySelect2() || attempts >= 30) {
                            clearInterval(interval);
                        }
                    }, 100);
                }
            });
        }(jQuery));
        </script>

        <?php
    }
    
    /**
     * Get WooCommerce categories with hierarchy
     */
    private function get_wc_categories_hierarchy() {
        try {
            $categories = get_terms(array(
                'taxonomy' => 'product_cat',
                'hide_empty' => false,
                'orderby' => 'name',
                'order' => 'ASC'
            ));
            
            if (is_wp_error($categories)) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino WC Categories Error: ' . $categories->get_error_message());
                return array();
            }
            
            // Trier les catégories par hiérarchie
            $sorted_categories = array();
            $this->sort_categories_hierarchically($categories, $sorted_categories, 0);
            
            return $sorted_categories;
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
            error_log('FlowDino WC Categories Exception: ' . $e->getMessage());
            return array();
        }
    }
    
    /**
     * Sort categories hierarchically
     */
    private function sort_categories_hierarchically($categories, &$sorted, $parent_id) {
        foreach ($categories as $category) {
            if ($category->parent == $parent_id) {
                $sorted[] = $category;
                $this->sort_categories_hierarchically($categories, $sorted, $category->term_id);
            }
        }
    }
    
    /**
     * Get category depth for indentation
     */
    private function get_category_depth($category_id, $depth = 0) {
        $category = get_term($category_id, 'product_cat');
        if ($category && $category->parent > 0) {
            return $this->get_category_depth($category->parent, $depth + 1);
        }
        return $depth;
    }
    
    /**
     * Render FlowDino category options with full path for Select2.
     * Only leaf categories (no children) are rendered.
     *
     * @param array $categories
     * @param mixed $selected
     * @param array $path
     */
    private function render_flowdino_category_options_with_path($categories, $selected = null, $path = array()) {
        if (!is_array($categories)) return;

        foreach ($categories as $category) {
            if (is_array($category) && isset($category['id'], $category['name'])) {
                $current_path = array_merge($path, array($category['name']));

                $has_children = isset($category['children']) && is_array($category['children']) && count($category['children']) > 0;

                if ($has_children) {
                    // Do not render parent categories — recurse into children only.
                    $this->render_flowdino_category_options_with_path($category['children'], $selected, $current_path);
                } else {
                    // Leaf category: render option with full hierarchical path.
                    $full_path = implode(' > ', $current_path);
                    $selected_attr = ($selected == $category['id']) ? 'selected="selected"' : '';

                    echo '<option value="' . esc_attr($category['id']) . '" ' . esc_attr($selected_attr) . '>';
                    echo esc_html($full_path);
                    echo '</option>';
                }
            }
        }
    }
}
