<?php

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

class AIEO_DMM_Post_Relations_Metabox {

    const META_BOX_ID    = 'aieo-dmm-post-relations';
    const NONCE_FIELD    = 'aieo_pr_nonce';
    const NONCE_ACTION   = 'aieo_pr_save';
    const POST_FIELD_KEY = 'aieo_pr';

    
    private static $registered = false;

    
    public static function register() {
        if (self::$registered)                              { return; }
        if (!class_exists('AIEO_DMM_Term_Relations'))       { return; }
        if (!class_exists('AIEO_DMM_Related_Tab'))          { return; }
        self::$registered = true;

        if (!is_admin()) { return; }

        foreach (self::supported_post_types() as $pt) {
            add_action('add_meta_boxes_' . $pt, array(__CLASS__, 'add_meta_box'));
            add_action('save_post_' . $pt,     array(__CLASS__, 'save_post'), 10, 3);
        }
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_assets'));
    }

    
    public static function supported_post_types() {
        return (array) apply_filters(
            'aieo_dmm_post_relations_metabox_post_types',
            array('post')
        );
    }

    
    public static function term_axes() {
        return (array) apply_filters('aieo_dmm_post_relations_metabox_axes', array(
            'product_brand' => array('product_brand', __('Related brands',    'ai-eshop-optimizer')),
            'pa_need'       => array('pa_need',       __('Related needs',     'ai-eshop-optimizer')),
            'product_cat'   => array('product_cat',   __('Related categories','ai-eshop-optimizer')),
        ));
    }

    public static function add_meta_box($post) {
        add_meta_box(
            self::META_BOX_ID,
            __('AIEO — related brands / needs / categories', 'ai-eshop-optimizer'),
            array(__CLASS__, 'render_meta_box'),
            null,
            'side',
            'default'
        );
    }

    
    public static function render_meta_box($post) {
        if (!($post instanceof WP_Post)) { return; }
        $post_id = (int) $post->ID;

        wp_nonce_field(self::NONCE_ACTION, self::NONCE_FIELD);

        
        
        $rels = AIEO_DMM_Term_Relations::for_post($post_id, $post->post_type);
        $picked_by_tax = array();
        foreach ($rels as $r) {
            $tax = (string) ($r['taxonomy'] ?? '');
            $tid = (int)    ($r['term_id']  ?? 0);
            if ($tax === '' || $tid <= 0) { continue; }
            if (!isset($picked_by_tax[$tax])) { $picked_by_tax[$tax] = array(); }
            $picked_by_tax[$tax][] = $tid;
        }

        echo '<div class="aieo-tr-panel aieo-pr-panel">';
        foreach (self::term_axes() as $key => $axis) {
            list($taxonomy, $label) = $axis;
            $field_name = self::POST_FIELD_KEY . '[' . $taxonomy . '][]';
            $picked     = isset($picked_by_tax[$taxonomy]) ? $picked_by_tax[$taxonomy] : array();
            $chips      = self::resolve_chips($taxonomy, $picked);
            ?>
            <div class="aieo-tr-field aieo-tr-search-field"
                 data-aieo-tr-search="<?php echo esc_attr($key); ?>"
                 data-source="term:<?php echo esc_attr($taxonomy); ?>">
                <label class="aieo-tr-label"><?php echo esc_html($label); ?></label>
                <input type="search" class="aieo-tr-search-input large-text"
                       placeholder="<?php echo esc_attr(sprintf(
                           
                           __('Search %s…', 'ai-eshop-optimizer'),
                           strtolower($label)
                       )); ?>" />
                <ul class="aieo-tr-search-results" hidden></ul>
                <ul class="aieo-tr-chips" data-name="<?php echo esc_attr($field_name); ?>">
                    <?php foreach ($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
        }
        echo '</div>';
        echo '<p class="description" style="margin-top:8px;">'
            . esc_html__('Picks here mirror the term-side Related tab. Saving the post writes the edges into wp_aieo_dmm_term_relations (bidirectional).', 'ai-eshop-optimizer')
            . '</p>';
    }

    
    public static function save_post($post_id, $post, $update) {
        $post_id = (int) $post_id;
        if ($post_id <= 0) { return; }
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)              { return; }
        if (wp_is_post_revision($post_id))                            { return; }
        if (!current_user_can('edit_post', $post_id))                 { return; }
        if (empty($_POST[self::NONCE_FIELD]))                         { return; }
        if (!wp_verify_nonce(
            sanitize_key(wp_unslash($_POST[self::NONCE_FIELD])),
            self::NONCE_ACTION
        )) { return; }

        $axes_raw = isset($_POST[self::POST_FIELD_KEY]) ? wp_unslash($_POST[self::POST_FIELD_KEY]) : array();
        if (!is_array($axes_raw)) { $axes_raw = array(); }

        
        $current_by_tax = array();
        foreach (AIEO_DMM_Term_Relations::for_post($post_id, $post->post_type) as $r) {
            $tax = (string) ($r['taxonomy'] ?? '');
            $tid = (int)    ($r['term_id']  ?? 0);
            if ($tax === '' || $tid <= 0) { continue; }
            if (!isset($current_by_tax[$tax])) { $current_by_tax[$tax] = array(); }
            $current_by_tax[$tax][] = $tid;
        }

        $post_type = (string) $post->post_type;

        foreach (self::term_axes() as $axis) {
            list($taxonomy) = $axis;
            $current = isset($current_by_tax[$taxonomy]) ? array_values(array_unique(array_map('intval', $current_by_tax[$taxonomy]))) : array();
            $incoming_raw = isset($axes_raw[$taxonomy]) ? (array) $axes_raw[$taxonomy] : array();
            $incoming = array();
            foreach ($incoming_raw as $id) {
                $id = (int) $id;
                if ($id > 0) { $incoming[] = $id; }
            }
            $incoming = array_values(array_unique($incoming));

            $to_add    = array_diff($incoming, $current);
            $to_remove = array_diff($current,  $incoming);

            foreach ($to_add as $tid) {
                AIEO_DMM_Term_Relations::add_edge($taxonomy, $tid, 'post', $post_type, $post_id);
            }
            foreach ($to_remove as $tid) {
                AIEO_DMM_Term_Relations::delete_edge($taxonomy, $tid, 'post', $post_type, $post_id);
            }
        }
    }

    
    public static function enqueue_assets($hook) {
        if (!in_array($hook, array('post.php', 'post-new.php'), true)) { return; }
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || !in_array($screen->post_type, self::supported_post_types(), 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'),
        ));
    }

    
    private static function resolve_chips($taxonomy, array $ids) {
        $out = array();
        foreach (array_unique(array_map('intval', $ids)) as $tid) {
            if ($tid <= 0) { continue; }
            $term = get_term($tid, $taxonomy);
            $label = ($term && !is_wp_error($term)) ? $term->name : ('#' . $tid);
            $out[] = array('id' => $tid, 'label' => $label);
        }
        return $out;
    }
}
