<?php

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

class AIEO_DMM_Supplier_Extras extends AIEO_DMM_Module_Base {

    public function get_id()       { return 'supplier_extras'; }
    public function get_label()    { return __('Supplier Extras', 'ai-eshop-optimizer'); }
    public function get_priority() { return 79; }
    public function get_group()    { return 'visuals'; }

    public function register_hooks() {
        
        
        
        
        
        add_action('init', array($this, 'register_supplier_taxonomy'), 9);

        
        $migrator_file = AIEO_DIR . 'includes/dmm/migrators/class-aieo-dmm-supplier-pods-migrator.php';
        if (file_exists($migrator_file)) {
            require_once $migrator_file;
            if (class_exists('AIEO_DMM_Supplier_Pods_Migrator')) {
                AIEO_DMM_Supplier_Pods_Migrator::register();
            }
        }

        
        add_filter('aieo_dmm_related_tab_taxonomies', array($this, 'register_supplier_in_related_tab'));
        
        
        
        add_filter('aieo_dmm_related_tab_axes', array($this, 'register_supplier_axis'));
        
        
        add_filter('aieo_dmm_related_tab_axes_for_source', array($this, 'limit_supplier_axes'), 10, 2);
        
        
        
        
        
        
        if (class_exists('AIEO_DMM_Related_Tab')) {
            add_action('edited_supplier',  array('AIEO_DMM_Related_Tab', 'on_term_save'), 10, 2);
            add_action('created_supplier', array('AIEO_DMM_Related_Tab', 'on_term_save'), 10, 2);
        }

        if (!is_admin()) { return; }

        
        
        
        
        add_action('admin_enqueue_scripts', array($this, 'enqueue_term_admin_assets'));

        foreach (AIEO_DMM_Supplier_Extras_Data::managed_taxonomies() as $tax) {
            add_action($tax . '_edit_form_fields', array($this, 'render_term_extras'), 1, 2);
            add_action('edited_'  . $tax,         array($this, 'save_term_extras'),    10, 2);
            add_action('created_' . $tax,         array($this, 'save_term_extras'),    10, 2);
        }
    }

    
    public function enqueue_term_admin_assets($hook) {
        if ($hook !== 'term.php') { return; }
        $tax = isset($_GET['taxonomy']) ? sanitize_key(wp_unslash($_GET['taxonomy'])) : ''; 
        if (!in_array($tax, AIEO_DMM_Supplier_Extras_Data::managed_taxonomies(), true)) { return; }

        wp_enqueue_media();
        if (function_exists('wp_enqueue_editor')) { wp_enqueue_editor(); }
        wp_enqueue_style(
            'aieo-dmm-category-extras-admin',
            AIEO_URI . 'assets/css/aieo-dmm-category-extras-admin.css',
            array(), AIEO_VERSION
        );
        wp_enqueue_script(
            'aieo-dmm-category-extras-admin',
            AIEO_URI . 'assets/js/aieo-dmm-category-extras-admin.js',
            array('jquery'), AIEO_VERSION, true
        );
        wp_localize_script('aieo-dmm-category-extras-admin', 'aieoCategoryExtras', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce(AIEO_DMM::NONCE_ACTION),
            'i18n'    => array(
                'noResults' => __('No matches.', 'ai-eshop-optimizer'),
                'searching' => __('Searching…', 'ai-eshop-optimizer'),
                'pickImage' => __('Select image', 'ai-eshop-optimizer'),
                'useImage'  => __('Use this image', 'ai-eshop-optimizer'),
            ),
        ));
    }

    public function register_supplier_in_related_tab(array $taxonomies) {
        if (!in_array('supplier', $taxonomies, true)) {
            $taxonomies[] = 'supplier';
        }
        return $taxonomies;
    }

    
    public function register_supplier_axis(array $axes) {
        if (!isset($axes['supplier'])) {
            $axes['supplier'] = array('term', 'supplier', __('Related suppliers', 'ai-eshop-optimizer'), 'term:supplier');
        }
        return $axes;
    }

    
    public function limit_supplier_axes($axes, $source) {
        if ($source === 'supplier') {
            return array_intersect_key((array) $axes, array('product_brand' => true));
        }
        return $axes;
    }

    
    public function register_supplier_taxonomy() {
        if (taxonomy_exists('supplier')) {
            return;
        }
        register_taxonomy('supplier', array('product'), array(
            'labels' => array(
                'name'              => __('Suppliers', 'ai-eshop-optimizer'),
                'singular_name'     => __('Supplier', 'ai-eshop-optimizer'),
                'menu_name'         => __('Suppliers', 'ai-eshop-optimizer'),
                'all_items'         => __('All Suppliers', 'ai-eshop-optimizer'),
                'search_items'      => __('Search Suppliers', 'ai-eshop-optimizer'),
                'edit_item'         => __('Edit Supplier', 'ai-eshop-optimizer'),
                'update_item'       => __('Update Supplier', 'ai-eshop-optimizer'),
                'add_new_item'      => __('Add New Supplier', 'ai-eshop-optimizer'),
                'new_item_name'     => __('New Supplier Name', 'ai-eshop-optimizer'),
                'not_found'         => __('No suppliers found.', 'ai-eshop-optimizer'),
            ),
            'public'             => false,
            'publicly_queryable' => false,
            'show_ui'            => true,
            'show_in_menu'       => true,   
            'show_admin_column'  => false,
            'show_in_rest'       => true,
            'hierarchical'       => false,
            'query_var'          => false,
            'rewrite'            => false,
            'capabilities'       => array(
                'manage_terms' => 'manage_woocommerce',
                'edit_terms'   => 'manage_woocommerce',
                'delete_terms' => 'manage_woocommerce',
                'assign_terms' => 'edit_products',
            ),
        ));
    }

    public function render_term_extras($term, $taxonomy) {
        if (!is_object($term) || !isset($term->term_id)) { return; }
        if (!in_array($taxonomy, AIEO_DMM_Supplier_Extras_Data::managed_taxonomies(), true)) { return; }

        $row = AIEO_DMM_Supplier_Extras_Data::get($taxonomy, (int) $term->term_id);
        $owner_label = '';
        if ($row['supplier_owner_user_id']) {
            $u = get_user_by('id', (int) $row['supplier_owner_user_id']);
            if ($u) { $owner_label = $u->display_name . ' <' . $u->user_email . '>'; }
        }
        ?>
        <tr class="form-field aieo-ce-panel-row">
            <th colspan="2" style="padding:0;">
                <div class="aieo-ce-panel" data-aieo-ce-panel data-term-id="<?php echo (int) $term->term_id; ?>" data-taxonomy="<?php echo esc_attr($taxonomy); ?>">
                    <?php wp_nonce_field('aieo_se_term_edit_' . (int) $term->term_id, 'aieo_se_nonce'); ?>
                    <div class="aieo-ce-panel-head">
                        <h2><?php esc_html_e('AIEO Supplier Extras', 'ai-eshop-optimizer'); ?></h2>
                        <p class="description"><?php esc_html_e('Stored in wp_aieo_dmm_supplier_extras + wp_aieo_dmm_term_relations. Replaces the Pods supplier fields.', 'ai-eshop-optimizer'); ?></p>
                    </div>

                    <nav class="aieo-ce-tabs" role="tablist">
                        <button type="button" class="aieo-ce-tab is-active" data-aieo-ce-tab="commercial" role="tab" aria-selected="true"><?php esc_html_e('Commercial', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="related"    role="tab" aria-selected="false"><?php esc_html_e('Related', 'ai-eshop-optimizer'); ?></button>
                    </nav>

                    <!-- ── Tab: Commercial ───────────────────────────────── -->
                    <div class="aieo-ce-tabpanel is-active" data-aieo-ce-pane="commercial" role="tabpanel">
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <label for="aieo-se-email"><?php esc_html_e('Email (orders / accounts)', 'ai-eshop-optimizer'); ?></label>
                                <input type="email" id="aieo-se-email" name="aieo_se[email]" value="<?php echo esc_attr((string) $row['email']); ?>" class="regular-text" />
                            </div>
                            <div class="aieo-ce-field">
                                <label for="aieo-se-owner"><?php esc_html_e('Internal owner (WP user)', 'ai-eshop-optimizer'); ?></label>
                                <input type="text" id="aieo-se-owner-display" value="<?php echo esc_attr($owner_label); ?>" placeholder="<?php esc_attr_e('— none —', 'ai-eshop-optimizer'); ?>" readonly class="regular-text" />
                                <input type="hidden" name="aieo_se[supplier_owner_user_id]" value="<?php echo (int) ($row['supplier_owner_user_id'] ?? 0); ?>" />
                                <p class="description"><?php esc_html_e('The accountable internal user. Editable later via a user-picker; for now use the migrator or wp-cli to set.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                        </div>
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <label for="aieo-se-lead-time"><?php esc_html_e('Lead time (days)', 'ai-eshop-optimizer'); ?></label>
                                <input type="number" id="aieo-se-lead-time" name="aieo_se[lead_time_days]" value="<?php echo $row['lead_time_days'] !== null ? (int) $row['lead_time_days'] : ''; ?>" min="0" class="small-text" />
                                <p class="description"><?php esc_html_e('Typical days from PO to delivery.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field">
                                <label for="aieo-se-payment-terms"><?php esc_html_e('Payment terms (days)', 'ai-eshop-optimizer'); ?></label>
                                <input type="number" id="aieo-se-payment-terms" name="aieo_se[payment_terms_days]" value="<?php echo $row['payment_terms_days'] !== null ? (int) $row['payment_terms_days'] : ''; ?>" min="0" class="small-text" />
                                <p class="description"><?php esc_html_e('Net-N invoice terms (e.g. 30 = net-30).', 'ai-eshop-optimizer'); ?></p>
                            </div>
                        </div>
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <label for="aieo-se-discount"><?php esc_html_e('Special discount (%)', 'ai-eshop-optimizer'); ?></label>
                                <input type="number" id="aieo-se-discount" name="aieo_se[special_discount_pct]" value="<?php echo esc_attr((string) number_format((float) $row['special_discount_pct'], 2, '.', '')); ?>" min="0" max="100" step="0.01" class="small-text" />
                                <p class="description"><?php esc_html_e('Operator-negotiated baseline discount on this supplier\'s catalogue.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field"></div>
                        </div>
                        <div class="aieo-ce-field aieo-ce-rich-field">
                            <label for="aieo_se_notes"><?php esc_html_e('Internal notes', 'ai-eshop-optimizer'); ?></label>
                            <?php wp_editor(
                                (string) $row['notes'],
                                'aieo_se_notes',
                                array(
                                    'textarea_name' => 'aieo_se[notes]',
                                    'textarea_rows' => 5,
                                    'media_buttons' => false,
                                    'teeny'         => true,
                                    'quicktags'     => true,
                                )
                            ); ?>
                            <p class="description"><?php esc_html_e('Operator notes (private). Not shown to customers.', 'ai-eshop-optimizer'); ?></p>
                        </div>
                    </div>

                    <!-- ── Tab: Related ──────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="related" role="tabpanel">
                        <?php
                        
                        
                        
                        $aieo_se_map = $GLOBALS['wpdb']->prefix . 'aieo_dmm_supplier_sku_map';
                        if (function_exists('aieo_dmm_table_exists') && aieo_dmm_table_exists($aieo_se_map)) {
                            $aieo_se_n = (int) $GLOBALS['wpdb']->get_var($GLOBALS['wpdb']->prepare(
                                "SELECT COUNT(*) FROM `{$aieo_se_map}` WHERE supplier_term_id = %d",
                                (int) $term->term_id
                            ));
                            echo '<p class="description" style="margin-bottom:14px;">' . esc_html(sprintf(
                                
                                _n('%d product SKU is mapped to this supplier from the ERP catalogue.', '%d product SKUs are mapped to this supplier from the ERP catalogue.', $aieo_se_n, 'ai-eshop-optimizer'),
                                $aieo_se_n
                            )) . '</p>';
                        }
                        if (class_exists('AIEO_DMM_Related_Tab')) {
                            AIEO_DMM_Related_Tab::render($taxonomy, (int) $term->term_id);
                        } else {
                            echo '<p>' . esc_html__('Related-tab component unavailable.', 'ai-eshop-optimizer') . '</p>';
                        }
                        ?>
                    </div>
                </div>
            </th>
        </tr>
        <?php
    }

    public function save_term_extras($term_id, $tt_id = 0) {
        $term_id = (int) $term_id;
        if (!$term_id) { return; }
        if (empty($_POST['aieo_se_nonce']) || !wp_verify_nonce(
            sanitize_key(wp_unslash($_POST['aieo_se_nonce'])),
            'aieo_se_term_edit_' . $term_id
        )) { return; }
        if (empty($_POST['aieo_se']) || !is_array($_POST['aieo_se'])) { return; }

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

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

        $patch = array();
        if (isset($raw['email']))                  { $patch['email']                  = (string) $raw['email']; }
        if (isset($raw['lead_time_days']))         { $patch['lead_time_days']         = $raw['lead_time_days']; }
        if (isset($raw['payment_terms_days']))     { $patch['payment_terms_days']     = $raw['payment_terms_days']; }
        if (isset($raw['special_discount_pct']))   { $patch['special_discount_pct']   = $raw['special_discount_pct']; }
        if (isset($raw['supplier_owner_user_id'])) { $patch['supplier_owner_user_id'] = $raw['supplier_owner_user_id']; }
        if (isset($raw['notes']))                  { $patch['notes']                  = (string) $raw['notes']; }

        AIEO_DMM_Supplier_Extras_Data::save($term->taxonomy, $term_id, $patch);
    }

    public function render_subtab() {
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Supplier Extras', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Pods-free per-supplier metadata. Edit individual suppliers at WooCommerce → Products → Suppliers → click a supplier. Related Brands are stored bidirectionally in wp_aieo_dmm_term_relations.', 'ai-eshop-optimizer') . '</p>';

        global $wpdb;
        $supplier_count = (int) $wpdb->get_var('SELECT COUNT(*) FROM ' . AIEO_DMM_Supplier_Extras_Data::table());
        echo '<table class="form-table"><tbody>';
        echo '<tr><th>' . esc_html__('Supplier metadata rows', 'ai-eshop-optimizer') . '</th><td>' . esc_html(number_format_i18n($supplier_count)) . '</td></tr>';
        echo '</tbody></table>';

        if (class_exists('AIEO_DMM_Supplier_Pods_Migrator') && AIEO_DMM_Supplier_Pods_Migrator::has_pods_source()) {
            $audit = AIEO_DMM_Supplier_Pods_Migrator::audit();
            $nonce = wp_create_nonce('aieo_supplier_pods_migrate');
            $ajax  = admin_url('admin-ajax.php');

            echo '<div class="aieo-dmm-card" style="margin-top:18px;padding:14px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;">';
            echo '<h3 style="margin-top:0;">' . esc_html__('Pods → Supplier Extras migrator', 'ai-eshop-optimizer') . '</h3>';
            echo '<p>';
            echo sprintf(
                
                esc_html__('Pods is active on `%1$s`. %2$d supplier terms total, %3$d already migrated.', 'ai-eshop-optimizer'),
                esc_html($audit['taxonomy']),
                (int) $audit['supplier_terms'],
                (int) $audit['already_migrated']
            );
            echo '</p>';
            echo '<p>';
            echo '<button type="button" class="button button-primary" id="aieo-supplier-pods-run">' . esc_html__('Run migration', 'ai-eshop-optimizer') . '</button>';
            echo ' <span id="aieo-supplier-pods-status" style="margin-left:10px;font-size:13px;color:#646970;"></span>';
            echo '</p>';
            ?>
            <script>
            (function(){
                var btn = document.getElementById('aieo-supplier-pods-run');
                if (!btn) return;
                var status = document.getElementById('aieo-supplier-pods-status');
                var NONCE = <?php echo wp_json_encode($nonce); ?>;
                var AJAX  = <?php echo wp_json_encode($ajax); ?>;
                btn.addEventListener('click', function(){
                    btn.disabled = true;
                    status.textContent = 'Migrating…';
                    var fd = new FormData();
                    fd.append('action', 'aieo_supplier_pods_migrate_run');
                    fd.append('nonce', NONCE);
                    fetch(AJAX, {method:'POST',credentials:'same-origin',body:fd}).then(function(r){return r.json();}).then(function(j){
                        if (!j || !j.success) {
                            status.textContent = 'Failed.'; status.style.color = '#b91c1c'; btn.disabled = false; return;
                        }
                        var d = j.data || {};
                        status.textContent = 'Done. processed=' + (d.processed|0) + ' migrated=' + (d.migrated|0)
                            + (d.errors && d.errors.length ? (' · ' + d.errors.length + ' errors') : '');
                        status.style.color = '#15803d'; btn.disabled = false;
                        if (d.errors && d.errors.length) console.warn(d.errors);
                    });
                });
            })();
            </script>
            <?php
            echo '</div>';
        } else {
            echo '<p class="description" style="margin-top:14px;color:#9ca3af;">' . esc_html__('Pods is not active here. Edit suppliers directly on each supplier term-edit screen.', 'ai-eshop-optimizer') . '</p>';
        }
        echo '</div>';
    }
}
