<?php

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

class AIEO_DMM_Wishlist extends AIEO_DMM_Module_Base {

    public function get_id()       { return 'wishlist'; }
    public function get_label()    { return __('Wishlist Analytics', 'ai-eshop-optimizer'); }
    public function get_priority() { return 68; } 
    public function get_group()    { return 'customer_profiling'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_wishlist_save_display', array($this, 'ajax_save_display'));
    }

    public function enqueue_admin_assets() {
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_add_inline_script('wp-color-picker',
            'jQuery(function($){$(".aieo-dmm-wl-color").wpColorPicker();});'
        );
    }

    public function ajax_save_display() {
        AIEO_DMM::verify_ajax_request();

        $placement_keys = array_keys(AIEO_Wishlist::single_placement_map());
        $placement = isset($_POST['single_placement']) ? sanitize_key(wp_unslash($_POST['single_placement'])) : 'after_add_to_cart';
        if (!in_array($placement, $placement_keys, true)) { $placement = 'after_add_to_cart'; }

        $archive_pos = isset($_POST['archive_position']) ? sanitize_key(wp_unslash($_POST['archive_position'])) : 'top-right';
        if (!in_array($archive_pos, array('top-right', 'top-left', 'bottom-right', 'bottom-left'), true)) {
            $archive_pos = 'top-right';
        }

        $data = array(
            'color_empty'     => sanitize_hex_color(wp_unslash($_POST['color_empty']  ?? '')) ?: '#c0c4c9',
            'color_filled'    => sanitize_hex_color(wp_unslash($_POST['color_filled'] ?? '')) ?: '#e0245e',
            'color_hover'     => sanitize_hex_color(wp_unslash($_POST['color_hover']  ?? '')) ?: '#a01c48',
            'size'            => isset($_POST['size']) ? max(12, min(60, (int) $_POST['size'])) : 22,
            
            'size_mobile'     => isset($_POST['size_mobile'])
                ? ((int) $_POST['size_mobile'] <= 0 ? 0 : max(12, min(60, (int) $_POST['size_mobile'])))
                : 18,
            'tooltip_add'     => isset($_POST['tooltip_add'])    ? sanitize_text_field(wp_unslash($_POST['tooltip_add']))    : '',
            'tooltip_remove'  => isset($_POST['tooltip_remove']) ? sanitize_text_field(wp_unslash($_POST['tooltip_remove'])) : '',
            'show_tooltip'    => !empty($_POST['show_tooltip'])    ? 'yes' : 'no',
            'single_label_add'  => isset($_POST['single_label_add'])  ? sanitize_text_field(wp_unslash($_POST['single_label_add']))  : '',
            'single_label_view' => isset($_POST['single_label_view']) ? sanitize_text_field(wp_unslash($_POST['single_label_view'])) : '',
            'single_show_label' => !empty($_POST['single_show_label']) ? 'yes' : 'no',
            'show_on_single'  => !empty($_POST['show_on_single'])  ? 'yes' : 'no',
            'show_on_archive' => !empty($_POST['show_on_archive']) ? 'yes' : 'no',
            'single_placement'=> $placement,
            'archive_position'=> $archive_pos,
            'wishlist_page_id'=> isset($_POST['wishlist_page_id']) ? max(0, (int) $_POST['wishlist_page_id']) : 0,
            
            'wishlist_type_product'  => !empty($_POST['wishlist_type_product'])  ? 'yes' : 'no',
            'wishlist_type_brand'    => !empty($_POST['wishlist_type_brand'])    ? 'yes' : 'no',
            'wishlist_type_category' => !empty($_POST['wishlist_type_category']) ? 'yes' : 'no',
            'wishlist_type_need'     => !empty($_POST['wishlist_type_need'])     ? 'yes' : 'no',
            'wishlist_type_blogpost' => !empty($_POST['wishlist_type_blogpost']) ? 'yes' : 'no',
        );
        update_option(AIEO_Wishlist::DISPLAY_OPTION, $data, false);
        wp_send_json_success(array('message' => __('Wishlist display settings saved.', 'ai-eshop-optimizer')));
    }

    public function render_subtab() {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_wishlist';

        
        
        $exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));
        if ($exists !== $table) {
            echo '<div class="aieo-dmm-section">';
            echo '<h2>' . esc_html__('Wishlist analytics', 'ai-eshop-optimizer') . '</h2>';
            echo '<div class="aieo-dmm-card"><p>';
            echo esc_html__('No wishlist table found. The AIEO wishlist module may not be active yet — activate it and the analytics will appear here.', 'ai-eshop-optimizer');
            echo '</p></div>';
            echo '</div>';
            return;
        }

        $total      = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table}");
        $unique     = (int) $wpdb->get_var("SELECT COUNT(DISTINCT item_id) FROM {$table}");
        
        
        
        
        
        $unique_logged_in = (int) $wpdb->get_var(
            "SELECT COUNT(DISTINCT user_id) FROM {$table} WHERE user_id > 0"
        );
        $unique_anonymous = (int) $wpdb->get_var(
            "SELECT COUNT(DISTINCT session_id) FROM {$table} WHERE user_id = 0 AND session_id <> ''"
        );
        $unique_customers = $unique_logged_in + $unique_anonymous;
        $popular    = $wpdb->get_results("SELECT item_id, COUNT(*) AS c FROM {$table} GROUP BY item_id ORDER BY c DESC LIMIT 20");
        $by_source  = $wpdb->get_results("SELECT source_type, COUNT(*) AS c FROM {$table} WHERE source_type <> '' GROUP BY source_type ORDER BY c DESC LIMIT 10");
        $breakdown  = $wpdb->get_results("SELECT source_type, source_id, source_name, COUNT(*) AS c FROM {$table} WHERE source_type <> '' GROUP BY source_type, source_id, source_name ORDER BY c DESC LIMIT 20");
        $total_with_source = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table} WHERE source_type <> ''");

        
        
        
        echo '<div class="aieo-dmm-section"><p class="description" style="font-size:12px;">';
        echo wp_kses_post(sprintf(
            
            __('Looking for the heart-button styling (placement, colors, labels)? It now lives under %1$sVisual Display → Wishlist Display%2$s.', 'ai-eshop-optimizer'),
            '<a href="' . esc_url(add_query_arg(array('page' => AIEO_DMM::MENU_SLUG, 'dmm_tab' => 'wishlist_display'), admin_url('admin.php'))) . '">',
            '</a>'
        ));
        echo '</p></div>';

        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Wishlist analytics', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('View which products are most popular in customer wishlists and where they were added from.', 'ai-eshop-optimizer') . '</p>';

        
        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Overview', 'ai-eshop-optimizer') . '</h3>';
        echo '<div class="aieo-attr-tiles">';
        $this->tile(__('Total items in wishlists', 'ai-eshop-optimizer'), number_format_i18n($total));
        $this->tile(__('Unique products', 'ai-eshop-optimizer'), number_format_i18n($unique));
        $this->tile(__('Customers with a list', 'ai-eshop-optimizer'), number_format_i18n($unique_customers));
        $this->tile(__('… logged in', 'ai-eshop-optimizer'), number_format_i18n($unique_logged_in));
        $this->tile(__('… anonymous', 'ai-eshop-optimizer'), number_format_i18n($unique_anonymous));
        $this->tile(__('Items with a known source', 'ai-eshop-optimizer'), number_format_i18n($total_with_source));
        echo '</div></div>';

        $this->render_source_stats_card($by_source, $total_with_source);
        $this->render_source_breakdown_card($breakdown);
        $this->render_popular_products_card($popular);

        echo '</div>';
    }

    
    public function render_display_settings_card() {
        $d = AIEO_Wishlist::get_display_settings();
        $placements = array(
            'before_title'         => __('Before title', 'ai-eshop-optimizer'),
            'after_title'          => __('After title', 'ai-eshop-optimizer'),
            'after_price'          => __('After price', 'ai-eshop-optimizer'),
            'after_excerpt'        => __('After short description', 'ai-eshop-optimizer'),
            'before_add_to_cart'   => __('Before Add to Cart form', 'ai-eshop-optimizer'),
            'after_add_to_cart_btn'=> __('Next to Add to Cart button', 'ai-eshop-optimizer'),
            'after_add_to_cart'    => __('After Add to Cart (default)', 'ai-eshop-optimizer'),
            'after_meta'           => __('After product meta', 'ai-eshop-optimizer'),
        );
        $archive_positions = array(
            'top-right'    => __('Top right', 'ai-eshop-optimizer'),
            'top-left'     => __('Top left', 'ai-eshop-optimizer'),
            'bottom-right' => __('Bottom right', 'ai-eshop-optimizer'),
            'bottom-left'  => __('Bottom left', 'ai-eshop-optimizer'),
        );
        echo '<form id="aieo-dmm-wishlist-display-form" class="aieo-dmm-form">';

        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Where it appears', 'ai-eshop-optimizer') . '</h3>';
        echo '<table class="form-table">';
        echo '<tr><th>' . esc_html__('Show on single product', 'ai-eshop-optimizer') . '</th>';
        echo '<td><label><input type="checkbox" name="show_on_single" value="1" ' . checked($d['show_on_single'], 'yes', false) . '> ' . esc_html__('Render the heart on product pages', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th>' . esc_html__('Placement on single product', 'ai-eshop-optimizer') . '</th><td><select name="single_placement">';
        foreach ($placements as $k => $label) {
            echo '<option value="' . esc_attr($k) . '"' . selected($d['single_placement'], $k, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';
        echo '<tr><th>' . esc_html__('Show on archive cards', 'ai-eshop-optimizer') . '</th>';
        echo '<td><label><input type="checkbox" name="show_on_archive" value="1" ' . checked($d['show_on_archive'], 'yes', false) . '> ' . esc_html__('Render on shop / category pages', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th>' . esc_html__('Archive corner', 'ai-eshop-optimizer') . '</th><td><select name="archive_position">';
        foreach ($archive_positions as $k => $label) {
            echo '<option value="' . esc_attr($k) . '"' . selected($d['archive_position'], $k, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';
        echo '<tr><th>' . esc_html__('Wishlist page', 'ai-eshop-optimizer') . '</th><td>';
        wp_dropdown_pages(array(
            'name'             => 'wishlist_page_id',
            'selected'         => (int) $d['wishlist_page_id'],
            'show_option_none' => esc_html__('— none —', 'ai-eshop-optimizer'),
            'option_none_value'=> 0,
        ));
        echo '<p class="description" style="font-weight:400;">' . esc_html__('When set, clicking a filled heart navigates to this page instead of un-wishlisting.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';
        echo '</table></div>';

        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Text', 'ai-eshop-optimizer') . '</h3>';
        echo '<table class="form-table">';
        echo '<tr><th>' . esc_html__('Tooltip — not yet in list', 'ai-eshop-optimizer') . '</th><td><input type="text" name="tooltip_add" value="' . esc_attr($d['tooltip_add']) . '" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Tooltip — when in list', 'ai-eshop-optimizer') . '</th><td><input type="text" name="tooltip_remove" value="' . esc_attr($d['tooltip_remove']) . '" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Show tooltip on hover', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="show_tooltip" value="1" ' . checked($d['show_tooltip'], 'yes', false) . '> ' . esc_html__('Display the tooltip pill above the heart on hover. (Single product page uses the inline labels below instead.)', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th colspan="2" style="padding-top:14px;"><strong>' . esc_html__('Inline labels (single product page only)', 'ai-eshop-optimizer') . '</strong></th></tr>';
        echo '<tr><th>' . esc_html__('Show inline label', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="single_show_label" value="1" ' . checked($d['single_show_label'], 'yes', false) . '> ' . esc_html__('Render a clickable text label next to the heart on the single product page.', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th>' . esc_html__('Label — not yet in list', 'ai-eshop-optimizer') . '</th><td><input type="text" name="single_label_add" value="' . esc_attr($d['single_label_add']) . '" class="regular-text"><p class="description" style="font-weight:400;">' . esc_html__('Clicking either the heart or this label adds the product.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th>' . esc_html__('Label — when in list', 'ai-eshop-optimizer') . '</th><td><input type="text" name="single_label_view" value="' . esc_attr($d['single_label_view']) . '" class="regular-text"><p class="description" style="font-weight:400;">' . esc_html__('Clicking this label opens the side cart\'s Favorites tab so the shopper can see what they\'ve saved.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '</table></div>';

        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Appearance', 'ai-eshop-optimizer') . '</h3>';
        echo '<table class="form-table">';
        echo '<tr><th>' . esc_html__('Empty (outline) color', 'ai-eshop-optimizer') . '</th><td><input type="text" name="color_empty" value="' . esc_attr($d['color_empty']) . '" class="aieo-dmm-wl-color" data-default-color="#c0c4c9"></td></tr>';
        echo '<tr><th>' . esc_html__('Filled (active) color', 'ai-eshop-optimizer') . '</th><td><input type="text" name="color_filled" value="' . esc_attr($d['color_filled']) . '" class="aieo-dmm-wl-color" data-default-color="#e0245e"></td></tr>';
        echo '<tr><th>' . esc_html__('Hover color', 'ai-eshop-optimizer') . '</th><td><input type="text" name="color_hover" value="' . esc_attr($d['color_hover']) . '" class="aieo-dmm-wl-color" data-default-color="#a01c48"></td></tr>';
        echo '<tr><th>' . esc_html__('Icon size — desktop (px)', 'ai-eshop-optimizer') . '</th>'
            . '<td><input type="number" min="12" max="60" name="size" value="' . (int) $d['size'] . '" class="small-text">'
            . '<p class="description">' . esc_html__('Default heart size used everywhere. Range 12–60px.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th>' . esc_html__('Icon size — mobile (px)', 'ai-eshop-optimizer') . '</th>'
            . '<td><input type="number" min="0" max="60" name="size_mobile" value="' . (int) ($d['size_mobile'] ?? 0) . '" class="small-text">'
            . '<p class="description">' . esc_html__('Applied on viewports ≤ 768px wide. Set 0 to inherit the desktop size. Default 18px keeps the archive heart proportional to mobile card images.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '</table></div>';

        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Enabled wishlist types', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description" style="font-weight:400;">' . esc_html__('Choose which kinds of things shoppers can add to their favourites. Disabling a type hides its add-to-wishlist control, blocks its add endpoint, and removes its tab from the side-cart favourites panel. Saved favourites of a disabled type are kept (just hidden) and reappear if you re-enable it.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="form-table">';
        foreach (array(
            'wishlist_type_product'  => __('Products', 'ai-eshop-optimizer'),
            'wishlist_type_brand'    => __('Brands', 'ai-eshop-optimizer'),
            'wishlist_type_category' => __('Categories', 'ai-eshop-optimizer'),
            'wishlist_type_need'     => __('Needs', 'ai-eshop-optimizer'),
            'wishlist_type_blogpost' => __('Blogposts', 'ai-eshop-optimizer'),
        ) as $tkey => $tlabel) {
            $on = !isset($d[$tkey]) || $d[$tkey] === 'yes';
            echo '<tr><th>' . esc_html($tlabel) . '</th><td><label><input type="checkbox" name="' . esc_attr($tkey) . '" value="1" ' . checked($on, true, false) . '> ' . esc_html__('Enabled', 'ai-eshop-optimizer') . '</label></td></tr>';
        }
        echo '</table></div>';

        echo '<p class="submit">';
        echo '<button type="submit" class="button button-primary aieo-dmm-btn-fixed" data-action="aieo_dmm_wishlist_save_display">';
        echo esc_html__('Save display settings', 'ai-eshop-optimizer') . '</button></p>';
        echo '</form>';
    }

    private function tile($label, $value) {
        echo '<div class="aieo-attr-tile">';
        echo '<div class="aieo-attr-tile-label">' . esc_html($label) . '</div>';
        echo '<div class="aieo-attr-tile-value">' . esc_html($value) . '</div>';
        echo '</div>';
    }

    private function render_source_stats_card($rows, $total) {
        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Where products are added from', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description" style="margin:0 0 8px;">'
           . esc_html__('Source-type breakdown: which surface the shopper was on when they hit the heart.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="widefat striped aieo-attr-sortable-table">';
        echo '<thead><tr>';
        echo '<th data-sort-type="text">' . esc_html__('Source type', 'ai-eshop-optimizer') . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '<th data-sort-type="num">'  . esc_html__('Times added', 'ai-eshop-optimizer') . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '<th data-sort-type="num">'  . esc_html__('Percentage', 'ai-eshop-optimizer') . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '</tr></thead><tbody>';
        if (empty($rows)) {
            echo '<tr><td colspan="3" style="text-align:center;color:#646970;">'
               . esc_html__('No source-typed wishlist entries yet.', 'ai-eshop-optimizer') . '</td></tr>';
        } else {
            foreach ($rows as $r) {
                $pct = $total > 0 ? round(100 * ((int) $r->c) / $total, 1) : 0;
                echo '<tr>';
                echo '<td data-sort-value="' . esc_attr($r->source_type) . '">';
                echo '<strong>' . esc_html($this->source_type_label((string) $r->source_type)) . '</strong><br>';
                echo '<code style="font-size:11px;color:#646970;">' . esc_html($r->source_type) . '</code>';
                echo '</td>';
                echo '<td data-sort-value="' . (int) $r->c . '">' . (int) $r->c . '</td>';
                echo '<td data-sort-value="' . esc_attr($pct) . '">';
                echo '<div style="display:inline-block;min-width:120px;background:#f3f4f6;border-radius:4px;overflow:hidden;vertical-align:middle;">';
                echo '<div style="height:14px;background:#4f46e5;width:' . esc_attr($pct) . '%;"></div>';
                echo '</div> <span style="color:#1f2937;font-size:12px;">' . esc_html($pct) . '%</span>';
                echo '</td>';
                echo '</tr>';
            }
        }
        echo '</tbody></table></div>';
    }

    private function render_source_breakdown_card($rows) {
        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Detailed source breakdown', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description" style="margin:0 0 8px;">'
           . esc_html__('Specific pages / categories where wishlist adds happened.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="widefat striped aieo-attr-sortable-table">';
        echo '<thead><tr>';
        echo '<th data-sort-type="text">' . esc_html__('Source', 'ai-eshop-optimizer')      . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '<th data-sort-type="text">' . esc_html__('Type', 'ai-eshop-optimizer')        . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '<th data-sort-type="num">'  . esc_html__('Count', 'ai-eshop-optimizer')       . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '</tr></thead><tbody>';
        if (empty($rows)) {
            echo '<tr><td colspan="3" style="text-align:center;color:#646970;">'
               . esc_html__('No detailed source data yet.', 'ai-eshop-optimizer') . '</td></tr>';
        } else {
            foreach ($rows as $r) {
                $name = $r->source_name ?: __('(No name)', 'ai-eshop-optimizer');
                echo '<tr>';
                echo '<td data-sort-value="' . esc_attr($name) . '">';
                echo '<strong>' . esc_html($name) . '</strong>';
                if ((int) $r->source_id > 0) {
                    echo '<br><small style="color:#646970;">ID: ' . (int) $r->source_id . '</small>';
                }
                echo '</td>';
                echo '<td data-sort-value="' . esc_attr($r->source_type) . '">';
                echo '<code>' . esc_html($r->source_type) . '</code>';
                echo '</td>';
                echo '<td data-sort-value="' . (int) $r->c . '">' . (int) $r->c . '</td>';
                echo '</tr>';
            }
        }
        echo '</tbody></table></div>';
    }

    private function render_popular_products_card($rows) {
        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('Most popular products', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description" style="margin:0 0 8px;">'
           . esc_html__('Top 20 products by wishlist additions — the demand signal your merch team can use to decide stock reorders.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="widefat striped aieo-attr-sortable-table">';
        echo '<thead><tr>';
        echo '<th style="width:50px;">' . esc_html__('#', 'ai-eshop-optimizer') . '</th>';
        echo '<th data-sort-type="text">' . esc_html__('Product', 'ai-eshop-optimizer')      . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '<th data-sort-type="num">'  . esc_html__('Times added', 'ai-eshop-optimizer')  . ' <span class="aieo-attr-dt-sort-ind">⇅</span></th>';
        echo '<th>' . esc_html__('Actions', 'ai-eshop-optimizer') . '</th>';
        echo '</tr></thead><tbody>';
        if (empty($rows)) {
            echo '<tr><td colspan="4" style="text-align:center;color:#646970;">'
               . esc_html__('No wishlist data yet — items will appear once customers start adding them.', 'ai-eshop-optimizer') . '</td></tr>';
        } else {
            foreach ($rows as $i => $r) {
                $pid   = (int) $r->item_id;
                $title = $pid > 0 ? get_the_title($pid) : '';
                if ($title === '' || $title === null) { $title = '#' . $pid . ' ' . __('(deleted)', 'ai-eshop-optimizer'); }
                $permalink = $pid > 0 ? get_permalink($pid) : '';
                $edit_url  = $pid > 0 ? admin_url('post.php?post=' . $pid . '&action=edit') : '';
                echo '<tr>';
                echo '<td>' . (int) ($i + 1) . '</td>';
                echo '<td data-sort-value="' . esc_attr($title) . '">';
                if ($edit_url) {
                    echo '<strong><a href="' . esc_url($edit_url) . '">' . esc_html($title) . '</a></strong>';
                } else {
                    echo '<strong>' . esc_html($title) . '</strong>';
                }
                echo '<br><small style="color:#646970;">ID: ' . (int) $pid . '</small>';
                echo '</td>';
                echo '<td data-sort-value="' . (int) $r->c . '">' . (int) $r->c . '</td>';
                echo '<td>';
                if ($permalink) {
                    echo '<a href="' . esc_url($permalink) . '" target="_blank" class="button button-small">' . esc_html__('View', 'ai-eshop-optimizer') . '</a>';
                } else {
                    echo '—';
                }
                echo '</td>';
                echo '</tr>';
            }
        }
        echo '</tbody></table></div>';
    }

    
    private function source_type_label($key) {
        $map = array(
            'single_product'   => __('Product page', 'ai-eshop-optimizer'),
            'archive'          => __('Shop / category listing', 'ai-eshop-optimizer'),
            'home'             => __('Home page', 'ai-eshop-optimizer'),
            'sidecart'         => __('Side cart', 'ai-eshop-optimizer'),
            'quickview'        => __('Quick view', 'ai-eshop-optimizer'),
            'cart'             => __('Cart', 'ai-eshop-optimizer'),
            'checkout'         => __('Checkout', 'ai-eshop-optimizer'),
            'related'          => __('Related products', 'ai-eshop-optimizer'),
            'upsells'          => __('Upsells', 'ai-eshop-optimizer'),
            'cross-sells'      => __('Cross-sells', 'ai-eshop-optimizer'),
            'same-needs'       => __('Product needs', 'ai-eshop-optimizer'),
            'recently_viewed'  => __('Recently viewed', 'ai-eshop-optimizer'),
            'search'           => __('Search results', 'ai-eshop-optimizer'),
        );
        return isset($map[$key]) ? $map[$key] : $key;
    }
}
