<?php

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

class AIEO_DMM_Need_Extras extends AIEO_DMM_Module_Base {

    public function get_id()       { return 'need_extras'; }
    public function get_label()    { return __('Need Extras', 'ai-eshop-optimizer'); }
    public function get_priority() { return 77; }
    public function get_group()    { return 'visuals'; }

    public function register_hooks() {
        if (!is_admin()) { return; }
        foreach (AIEO_DMM_Need_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);
        }
        add_action('admin_enqueue_scripts', array($this, 'enqueue_term_admin_assets'));
    }

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

        $term_id = (int) $term->term_id;
        $row     = AIEO_DMM_Need_Extras_Data::get($taxonomy, $term_id);
        $icon_url = $row['icon_image_id'] ? wp_get_attachment_image_url((int) $row['icon_image_id'], 'thumbnail') : '';
        $hero_url = $row['hero_image_id'] ? wp_get_attachment_image_url((int) $row['hero_image_id'], 'medium')    : '';
        $hidden   = (string) get_term_meta($term_id, 'aieo_hidden', true) === 'yes';

        
        global $wpdb;
        $product_count = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(DISTINCT tr.object_id)
               FROM {$wpdb->term_relationships} tr
               JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
               JOIN {$wpdb->posts} p ON p.ID = tr.object_id AND p.post_type = 'product' AND p.post_status = 'publish'
              WHERE tt.taxonomy = %s AND tt.term_id = %d",
            $taxonomy, $term_id
        ));
        $bulk_admin_url = admin_url('admin.php?page=ai-eshop-dmm&dmm_tab=product_needs');

        ?>
        <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_id; ?>" data-taxonomy="<?php echo esc_attr($taxonomy); ?>">
                    <?php wp_nonce_field('aieo_ne_term_edit_' . $term_id, 'aieo_ne_nonce'); ?>
                    <div class="aieo-ce-panel-head">
                        <h2><?php esc_html_e('AIEO Need Extras', 'ai-eshop-optimizer'); ?></h2>
                        <p class="description"><?php esc_html_e('Stored in wp_aieo_dmm_need_extras + wp_aieo_dmm_term_relations. The hidden-from-frontend flag stays in term meta (`aieo_hidden`) for backward compat.', '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="identity" role="tab" aria-selected="true"><?php esc_html_e('Identity', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="about"    role="tab" aria-selected="false"><?php esc_html_e('About', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="display"  role="tab" aria-selected="false"><?php esc_html_e('Display', '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>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="products" role="tab" aria-selected="false"><?php esc_html_e('Products', 'ai-eshop-optimizer'); ?> <span style="opacity:.6;">(<?php echo (int) $product_count; ?>)</span></button>
                    </nav>

                    <!-- ── Tab: Identity ─────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel is-active" data-aieo-ce-pane="identity" role="tabpanel">
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field aieo-ce-image-field" data-aieo-ce-image="icon">
                                <label><?php esc_html_e('Icon (small, square)', 'ai-eshop-optimizer'); ?></label>
                                <div class="aieo-ce-image-preview"<?php echo $icon_url ? '' : ' style="display:none;"'; ?>>
                                    <?php if ($icon_url): ?><img src="<?php echo esc_url($icon_url); ?>" alt="" /><?php endif; ?>
                                </div>
                                <input type="hidden" name="aieo_ne[icon_image_id]" value="<?php echo (int) $row['icon_image_id']; ?>" />
                                <button type="button" class="button aieo-ce-image-pick"><?php esc_html_e('Select / change', 'ai-eshop-optimizer'); ?></button>
                                <button type="button" class="button-link aieo-ce-image-clear"<?php echo $icon_url ? '' : ' style="display:none;"'; ?>><?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?></button>
                                <p class="description"><?php esc_html_e('Used in product summaries + need archive cards. Square preferred.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field aieo-ce-image-field" data-aieo-ce-image="hero">
                                <label><?php esc_html_e('Hero / banner image', 'ai-eshop-optimizer'); ?></label>
                                <div class="aieo-ce-image-preview"<?php echo $hero_url ? '' : ' style="display:none;"'; ?>>
                                    <?php if ($hero_url): ?><img src="<?php echo esc_url($hero_url); ?>" alt="" /><?php endif; ?>
                                </div>
                                <input type="hidden" name="aieo_ne[hero_image_id]" value="<?php echo (int) $row['hero_image_id']; ?>" />
                                <button type="button" class="button aieo-ce-image-pick"><?php esc_html_e('Select / change', 'ai-eshop-optimizer'); ?></button>
                                <button type="button" class="button-link aieo-ce-image-clear"<?php echo $hero_url ? '' : ' style="display:none;"'; ?>><?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?></button>
                                <p class="description"><?php esc_html_e('Wide banner shown on the need archive page header.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                        </div>
                        <div class="aieo-ce-field">
                            <label for="aieo-ne-headline"><?php esc_html_e('Headline (one-liner)', 'ai-eshop-optimizer'); ?></label>
                            <input type="text" id="aieo-ne-headline" name="aieo_ne[headline]" value="<?php echo esc_attr((string) $row['headline']); ?>" class="large-text" />
                            <p class="description"><?php esc_html_e('Short tagline shown next to the icon on summaries / archive headers.', 'ai-eshop-optimizer'); ?></p>
                        </div>
                    </div>

                    <!-- ── Tab: About ────────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="about" role="tabpanel">
                        <div class="aieo-ce-field aieo-ce-rich-field">
                            <label for="aieo_ne_about_text"><?php esc_html_e('About this need', 'ai-eshop-optimizer'); ?></label>
                            <?php wp_editor(
                                (string) $row['about_text'],
                                'aieo_ne_about_text',
                                array(
                                    'textarea_name' => 'aieo_ne[about_text]',
                                    'textarea_rows' => 8,
                                    'media_buttons' => true,
                                    'teeny'         => false,
                                    'quicktags'     => true,
                                )
                            ); ?>
                            <p class="description"><?php esc_html_e('Customer-facing description. Rendered on the need archive page above the products grid.', 'ai-eshop-optimizer'); ?></p>
                        </div>
                    </div>

                    <!-- ── Tab: Display ──────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="display" role="tabpanel">
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <label for="aieo-ne-priority"><?php esc_html_e('Priority (sort weight)', 'ai-eshop-optimizer'); ?></label>
                                <input type="number" id="aieo-ne-priority" name="aieo_ne[priority]" value="<?php echo (int) $row['priority']; ?>" step="1" />
                                <p class="description"><?php esc_html_e('Higher = surfaced earlier in need lists. 0 = default.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field">
                                <label><?php esc_html_e('Hidden from frontend', 'ai-eshop-optimizer'); ?></label>
                                <label class="aieo-ce-radio">
                                    <input type="checkbox" name="aieo_ne[hidden_from_frontend]" value="1" <?php checked($hidden, true); ?> />
                                    <?php esc_html_e('Hide from product summaries / archives', 'ai-eshop-optimizer'); ?>
                                </label>
                                <p class="description"><?php esc_html_e('Mirrors the existing aieo_hidden term meta. Operator + AI still see hidden needs in the editor; only customers do not.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                        </div>
                        <div class="aieo-ce-field aieo-ce-rich-field">
                            <label for="aieo_ne_footer_text"><?php esc_html_e('Footer text (bottom of need archive)', 'ai-eshop-optimizer'); ?></label>
                            <?php wp_editor(
                                (string) $row['footer_text'],
                                'aieo_ne_footer_text',
                                array(
                                    'textarea_name' => 'aieo_ne[footer_text]',
                                    'textarea_rows' => 6,
                                    'media_buttons' => true,
                                    'teeny'         => false,
                                    'quicktags'     => true,
                                )
                            ); ?>
                            <p class="description"><?php esc_html_e('SEO-friendly long-form content under the products grid.', 'ai-eshop-optimizer'); ?></p>
                        </div>
                    </div>

                    <!-- ── Tab: Related ──────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="related" role="tabpanel">
                        <?php
                        if (class_exists('AIEO_DMM_Related_Tab')) {
                            AIEO_DMM_Related_Tab::render($taxonomy, $term_id);
                        } else {
                            echo '<p>' . esc_html__('Related-tab component unavailable.', 'ai-eshop-optimizer') . '</p>';
                        }
                        ?>
                    </div>

                    <!-- ── Tab: Products ─────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="products" role="tabpanel">
                        <p>
                            <strong><?php
                                printf(
                                    
                                    esc_html(_n('%s published product is currently tagged with this need.', '%s published products are currently tagged with this need.', $product_count, 'ai-eshop-optimizer')),
                                    esc_html(number_format_i18n($product_count))
                                );
                            ?></strong>
                        </p>
                        <?php if ($product_count > 0): ?>
                            <?php
                            
                            $sample_ids = $wpdb->get_col($wpdb->prepare(
                                "SELECT p.ID
                                   FROM {$wpdb->term_relationships} tr
                                   JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
                                   JOIN {$wpdb->posts} p ON p.ID = tr.object_id AND p.post_type = 'product' AND p.post_status = 'publish'
                                  WHERE tt.taxonomy = %s AND tt.term_id = %d
                                  ORDER BY p.ID DESC LIMIT 10",
                                $taxonomy, $term_id
                            ));
                            ?>
                            <p class="description"><?php esc_html_e('Recent 10:', 'ai-eshop-optimizer'); ?></p>
                            <ul style="margin-left:18px;list-style:disc;">
                            <?php foreach ($sample_ids as $pid): ?>
                                <li><a href="<?php echo esc_url(get_edit_post_link((int) $pid)); ?>"><?php echo esc_html(get_the_title((int) $pid)); ?></a></li>
                            <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                        <p style="margin-top:14px;">
                            <a href="<?php echo esc_url($bulk_admin_url); ?>" class="button button-primary">
                                <?php esc_html_e('Open bulk Product → Needs editor', 'ai-eshop-optimizer'); ?>
                            </a>
                        </p>
                        <p class="description"><?php esc_html_e('To assign or unassign products from this need at scale, use the bulk editor. Per-product need assignment is also available on each product\'s edit screen.', '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_ne_nonce']) || !wp_verify_nonce(
            sanitize_key(wp_unslash($_POST['aieo_ne_nonce'])),
            'aieo_ne_term_edit_' . $term_id
        )) { return; }
        if (empty($_POST['aieo_ne']) || !is_array($_POST['aieo_ne'])) { return; }

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

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

        $patch = array();
        if (isset($raw['icon_image_id'])) { $patch['icon_image_id'] = (int) $raw['icon_image_id']; }
        if (isset($raw['hero_image_id'])) { $patch['hero_image_id'] = (int) $raw['hero_image_id']; }
        if (isset($raw['headline']))      { $patch['headline']      = sanitize_text_field((string) $raw['headline']); }
        if (isset($raw['about_text']))    { $patch['about_text']    = wp_kses_post((string) $raw['about_text']); }
        if (isset($raw['priority']))      { $patch['priority']      = (int) $raw['priority']; }
        if (isset($raw['footer_text']))   { $patch['footer_text']   = wp_kses_post((string) $raw['footer_text']); }

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

        
        $hidden = !empty($raw['hidden_from_frontend']);
        update_term_meta($term_id, 'aieo_hidden', $hidden ? 'yes' : '');
    }

    
    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_Need_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 render_subtab() {
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Need Extras', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Per-need icon, hero, headline, about text, footer, priority + bidirectional Related panel. Edit individual needs at WooCommerce → Products → Attributes → Needs → click a need.', 'ai-eshop-optimizer') . '</p>';

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

        echo '<p><a class="button" href="' . esc_url(admin_url('admin.php?page=ai-eshop-dmm&dmm_tab=product_needs')) . '">' . esc_html__('Open Product → Needs bulk editor', 'ai-eshop-optimizer') . '</a></p>';
        echo '</div>';
    }
}
