<?php

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

class AIEO_DMM_Related_Tab {

    private static $registered = false;

    
    public static function register() {
        if (self::$registered) { return; }
        self::$registered = true;

        if (is_admin()) {
            foreach (self::source_taxonomies() as $tax) {
                add_action('edited_'  . $tax, array(__CLASS__, 'on_term_save'), 10, 2);
                add_action('created_' . $tax, array(__CLASS__, 'on_term_save'), 10, 2);
            }
            add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_assets'));
            add_action('wp_ajax_aieo_dmm_related_search', array(__CLASS__, 'ajax_search'));
        }
    }

    
    public static function source_taxonomies() {
        return (array) apply_filters(
            'aieo_dmm_related_tab_taxonomies',
            array('product_cat', 'product_brand', 'pa_need', 'product_tag')
        );
    }

    
    public static function target_axes() {
        
        
        
        
        
        $axes = array(
            'product_cat'   => array('term', 'product_cat',   __('Related categories',  'ai-eshop-optimizer'), 'term:product_cat'),
            'product_brand' => array('term', 'product_brand', __('Related brands',      'ai-eshop-optimizer'), 'term:product_brand'),
            'pa_need'       => array('term', 'pa_need',       __('Related needs',       'ai-eshop-optimizer'), 'term:pa_need'),
            'product_tag'   => array('term', 'product_tag',   __('Related tags',        'ai-eshop-optimizer'), 'term:product_tag'),
            'post'          => array('post', 'post',          __('Related blog posts',  'ai-eshop-optimizer'), 'post:post'),
            'campaign'      => array('post', 'campaign',      __('Related campaigns',   'ai-eshop-optimizer'), 'post:campaign'),
        );
        return (array) apply_filters('aieo_dmm_related_tab_axes', $axes);
    }

    
    public static function render($source_taxonomy, $source_term_id) {
        $source_taxonomy = (string) $source_taxonomy;
        $source_term_id  = (int) $source_term_id;
        if ($source_taxonomy === '' || $source_term_id <= 0) { return; }

        
        
        
        $axes = (array) apply_filters('aieo_dmm_related_tab_axes_for_source', self::target_axes(), $source_taxonomy);

        
        
        $existing = array();
        foreach ($axes as $key => $axis) {
            list($kind, $subtype, $label, $js_source) = $axis;
            
            if ($kind === 'term' && $subtype === $source_taxonomy) { continue; }
            $rows = AIEO_DMM_Term_Relations::for_term($source_taxonomy, $source_term_id, $kind, $subtype);
            $ids  = array_map(static function ($r) { return (int) $r['id']; }, $rows);
            $existing[$key] = array(
                'kind'      => $kind,
                'subtype'   => $subtype,
                'label'     => $label,
                'js_source' => $js_source,
                'ids'       => $ids,
                'chips'     => self::resolve_chips($kind, $subtype, $ids),
            );
        }

        wp_nonce_field('aieo_tr_term_edit_' . $source_term_id, 'aieo_tr_nonce');
        ?>
        <div class="aieo-tr-panel">
            <?php foreach ($existing as $key => $axis): ?>
                <?php
                $field_name = 'aieo_tr[' . $axis['kind'] . ':' . $axis['subtype'] . '][]';
                ?>
                <div class="aieo-tr-field aieo-tr-search-field" data-aieo-tr-search="<?php echo esc_attr($key); ?>" data-source="<?php echo esc_attr($axis['js_source']); ?>">
                    <label class="aieo-tr-label"><?php echo esc_html($axis['label']); ?></label>
                    <input type="search" class="aieo-tr-search-input large-text"
                           placeholder="<?php echo esc_attr(sprintf(
                               
                               __('Search %s…', 'ai-eshop-optimizer'),
                               strtolower($axis['label'])
                           )); ?>" />
                    <ul class="aieo-tr-search-results" hidden></ul>
                    <ul class="aieo-tr-chips" data-name="<?php echo esc_attr($field_name); ?>">
                        <?php foreach ($axis['chips'] as $c): ?>
                            <li class="aieo-tr-chip" data-id="<?php echo (int) $c['id']; ?>">
                                <span class="aieo-tr-chip-label"><?php echo esc_html($c['label']); ?></span>
                                <button type="button" class="aieo-tr-chip-remove" aria-label="<?php esc_attr_e('Remove', 'ai-eshop-optimizer'); ?>">&times;</button>
                                <input type="hidden" name="<?php echo esc_attr($field_name); ?>" value="<?php echo (int) $c['id']; ?>" />
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
    }

    
    public static function on_term_save($term_id, $tt_id = 0) {
        $term_id = (int) $term_id;
        if (!$term_id) { return; }
        if (empty($_POST['aieo_tr_nonce']) || !wp_verify_nonce(
            sanitize_key(wp_unslash($_POST['aieo_tr_nonce'])),
            'aieo_tr_term_edit_' . $term_id
        )) {
            return;
        }
        if (empty($_POST['aieo_tr']) || !is_array($_POST['aieo_tr'])) { return; }

        $term = get_term($term_id);
        if (!$term || is_wp_error($term)) { return; }
        if (!in_array($term->taxonomy, self::source_taxonomies(), true)) { return; }

        $raw = wp_unslash($_POST['aieo_tr']);
        if (!is_array($raw)) { return; }

        foreach ($raw as $axis_key => $ids) {
            
            if (!is_string($axis_key) || strpos($axis_key, ':') === false) { continue; }
            list($kind, $subtype) = array_map('strval', explode(':', $axis_key, 2));
            if (!in_array($kind, array('term', 'post'), true)) { continue; }
            if ($subtype === '')                                { continue; }

            $clean_ids = array();
            if (is_array($ids)) {
                foreach ($ids as $id) {
                    $id = (int) $id;
                    if ($id > 0) { $clean_ids[] = $id; }
                }
                $clean_ids = array_values(array_unique($clean_ids));
            }

            AIEO_DMM_Term_Relations::set_targets(
                $term->taxonomy, $term_id, $kind, $subtype, $clean_ids
            );
        }
    }

    
    public static function ajax_search() {
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => 'permission_denied'), 403);
        }
        check_ajax_referer('aieo_tr_search', 'nonce');

        $kind    = isset($_GET['kind'])    ? sanitize_key(wp_unslash($_GET['kind']))    : 'term';
        $subtype = isset($_GET['subtype']) ? sanitize_key(wp_unslash($_GET['subtype'])) : '';
        $q       = isset($_GET['q'])       ? sanitize_text_field(wp_unslash($_GET['q'])) : '';
        if (!in_array($kind, array('term', 'post'), true) || $subtype === '' || $q === '') {
            wp_send_json_success(array('results' => array()));
        }

        $results = array();
        if ($kind === 'term') {
            $terms = get_terms(array(
                'taxonomy'   => $subtype,
                'hide_empty' => false,
                'number'     => 20,
                'name__like' => $q,
            ));
            if (!is_wp_error($terms) && is_array($terms)) {
                foreach ($terms as $t) {
                    $results[] = array('id' => (int) $t->term_id, 'label' => (string) $t->name);
                }
            }
        } else {
            $posts = get_posts(array(
                'post_type'      => $subtype,
                'post_status'    => array('publish', 'private', 'future'),
                'posts_per_page' => 20,
                's'              => $q,
                'orderby'        => 'title',
                'order'          => 'ASC',
            ));
            foreach ($posts as $p) {
                $results[] = array('id' => (int) $p->ID, 'label' => (string) get_the_title($p));
            }
        }
        wp_send_json_success(array('results' => $results));
    }

    
    private static function resolve_chips($kind, $subtype, array $ids) {
        $ids = array_map('intval', $ids);
        $ids = array_filter($ids);
        if (empty($ids)) { return array(); }
        $out = array();
        if ($kind === 'term') {
            foreach ($ids as $tid) {
                $term = get_term($tid, $subtype);
                $label = ($term && !is_wp_error($term)) ? $term->name : ('#' . $tid);
                $out[] = array('id' => $tid, 'label' => $label);
            }
        } else {
            foreach ($ids as $pid) {
                $title = get_the_title($pid);
                $out[] = array('id' => $pid, 'label' => $title !== '' ? $title : ('#' . $pid));
            }
        }
        return $out;
    }

    
    public static function enqueue_assets($hook) {
        if (!in_array($hook, array('term.php', 'edit-tags.php'), true)) { return; }
        $tax = isset($_GET['taxonomy']) ? sanitize_key(wp_unslash($_GET['taxonomy'])) : '';
        if (!in_array($tax, self::source_taxonomies(), true)) { return; }

        $version = defined('AIEO_VERSION') ? AIEO_VERSION : '1.0';
        wp_enqueue_style(
            'aieo-dmm-related-tab',
            plugins_url('assets/css/aieo-dmm-related-tab.css', AIEO_FILE),
            array(), $version
        );
        wp_enqueue_script(
            'aieo-dmm-related-tab',
            plugins_url('assets/js/aieo-dmm-related-tab.js', AIEO_FILE),
            array(), $version, true
        );
        wp_localize_script('aieo-dmm-related-tab', 'aieoTrConfig', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('aieo_tr_search'),
        ));
    }
}
