<?php

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

class AIEO_DMM_Product_Meta extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_product_meta_settings';

    public function get_id()       { return 'product_meta'; }
    public function get_label()    { return __('Product Meta', 'ai-eshop-optimizer'); }
    public function get_priority() { return 50; }
    public function get_group()    { return 'product_display'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_product_meta_save', array($this, 'ajax_save'));
        
        add_shortcode('aieo_product_meta',   array($this, 'shortcode_handler'));
        add_shortcode('om_ppe_product_meta', array($this, 'shortcode_handler'));

        $s = $this->get_settings();
        if (empty($s['enabled'])) { return; }

        add_action('wp_loaded',      array($this, 'remove_default_meta'));
        add_action('woocommerce_single_product_summary', array($this, 'output'), 40);
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        
        
        
        
        
        
        
        $legacy = empty($stored) ? get_option('om_ppe_product-meta', array()) : array();
        if (!is_array($legacy)) { $legacy = array(); }
        return array_merge(array(
            'enabled'              => false,
            'show_sku'             => true,
            'show_barcode'         => true,
            'sku_label'            => 'SKU',
            'sku_label_plural'     => 'SKUs',
            'barcode_label'        => 'Barcode',
            'barcode_label_plural' => 'Barcodes',
            'max_visible'          => 4,
            'more_text'            => 'and %d more',
            'text_color'           => '#666666',
            'label_color'          => '#333333',
            'link_color'           => '',
            'title_bold'           => true,
            'font_size'            => '0.92em',
            'use_shortcode'        => false,
            'custom_class'         => '',
        ), $legacy, $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        update_option(self::OPTION_KEY, array(
            'enabled'              => !empty($_POST['enabled']),
            'show_sku'             => !empty($_POST['show_sku']),
            'show_barcode'         => !empty($_POST['show_barcode']),
            'sku_label'            => isset($_POST['sku_label']) ? sanitize_text_field(wp_unslash($_POST['sku_label'])) : 'SKU',
            'sku_label_plural'     => isset($_POST['sku_label_plural']) ? sanitize_text_field(wp_unslash($_POST['sku_label_plural'])) : 'SKUs',
            'barcode_label'        => isset($_POST['barcode_label']) ? sanitize_text_field(wp_unslash($_POST['barcode_label'])) : 'Barcode',
            'barcode_label_plural' => isset($_POST['barcode_label_plural']) ? sanitize_text_field(wp_unslash($_POST['barcode_label_plural'])) : 'Barcodes',
            'max_visible'          => max(1, min(20, isset($_POST['max_visible']) ? (int) $_POST['max_visible'] : 4)),
            'more_text'            => isset($_POST['more_text']) ? sanitize_text_field(wp_unslash($_POST['more_text'])) : 'and %d more',
            'text_color'           => isset($_POST['text_color']) ? (sanitize_hex_color(wp_unslash($_POST['text_color'])) ?: '#666666') : '#666666',
            'label_color'          => isset($_POST['label_color']) ? (sanitize_hex_color(wp_unslash($_POST['label_color'])) ?: '#333333') : '#333333',
            'link_color'           => isset($_POST['link_color']) ? (sanitize_hex_color(wp_unslash($_POST['link_color'])) ?: '') : '',
            'title_bold'           => !empty($_POST['title_bold']),
            'font_size'            => (isset($_POST['font_size']) && preg_match('/^[0-9]*\.?[0-9]+\s*(rem|em|px|%|vw|vh|pt)$/i', trim((string) wp_unslash($_POST['font_size'])))) ? trim((string) wp_unslash($_POST['font_size'])) : '0.92em',
            'use_shortcode'        => !empty($_POST['use_shortcode']),
            'custom_class'         => isset($_POST['custom_class']) ? sanitize_html_class(wp_unslash($_POST['custom_class'])) : '',
        ), false);
        wp_send_json_success(array('message' => __('Product Meta settings saved.', 'ai-eshop-optimizer')));
    }

    public function remove_default_meta() {
        
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40);
    }

    public function enqueue_scripts() {
        if (!function_exists('is_product') || !is_product()) { return; }
        
        $js = '(function(){function close(except){document.querySelectorAll(".aieo-product-meta__tooltip.visible").forEach(function(el){if(el!==except)el.classList.remove("visible");});}document.addEventListener("click",function(e){var t=e.target.nodeType===1?e.target:e.target.parentElement;if(!t)return;var btn=t.closest(".aieo-product-meta__more");if(btn){e.preventDefault();var row=btn.closest(".aieo-product-meta__row");var tip=row?row.querySelector(".aieo-product-meta__tooltip"):null;if(!tip)return;var open=tip.classList.contains("visible");close(open?tip:null);tip.classList.toggle("visible",!open);return;}if(!t.closest(".aieo-product-meta__row"))close(null);});})();';
        wp_register_script('aieo-product-meta', false, array(), defined('AIEO_VERSION') ? AIEO_VERSION : '1.0', true);
        wp_enqueue_script('aieo-product-meta');
        wp_add_inline_script('aieo-product-meta', $js);
        
        
        
        
        
        
        
        $s   = $this->get_settings();
        $css = '
            .aieo-product-meta {
                --aieo-product-meta-text:  ' . esc_attr( (string) $s['text_color']  ) . ';
                --aieo-product-meta-label: ' . esc_attr( (string) $s['label_color'] ) . ';
                color: var(--aieo-product-meta-text);
                font-size: ' . esc_attr( (string) $s['font_size'] ) . ';
                line-height: 1.45;
                /* Keep the top gap (separation from price) but tighten the
                 * bottom so the next meta-style line (Categories / brand-text)
                 * sits ~4px below the last code row — matching the SKU↔Barcode
                 * rhythm. The info column is a flex container on FSE (margins do
                 * NOT collapse between sibling blocks), so 2px here + 2px on the
                 * Categories wrapper sums to the same 4px as the intra-row gap. */
                margin: 14px 0 2px;
            }
            /* Plain block row so label + codes flow as one inline text
             * stream — flex-wrap was treating each <span> as its own
             * shrinkable unit, which pushed long code lists (barcodes
             * are 13 chars each) onto the line BELOW the label. With
             * normal block + inline children, the browser wraps mid-
             * stream wherever the line break naturally falls. */
            .aieo-product-meta__row {
                position: relative;
                margin: 4px 0;
                line-height: 1.5;
            }
            /* Flush the block edges so inter-block spacing is governed only by
             * the wrapper margins (keeps SKU/Barcode/Categories evenly spaced). */
            .aieo-product-meta__row:first-child { margin-top: 0; }
            .aieo-product-meta__row:last-child  { margin-bottom: 0; }
            .aieo-product-meta__label {
                color: var(--aieo-product-meta-label);
                font-weight: 600;
                margin-right: 4px;
            }
            .aieo-product-meta__codes {
                color: inherit;
            }
            .aieo-product-meta__more {
                color: var(--aieo-product-meta-label);
                cursor: pointer;
                text-decoration: underline dotted;
                text-underline-offset: 2px;
                margin-left: 2px;
                user-select: none;
            }
            .aieo-product-meta__more:hover,
            .aieo-product-meta__more:focus-visible {
                text-decoration-style: solid;
                outline: none;
            }
            .aieo-product-meta__tooltip {
                display: none;
                position: absolute;
                left: 0;
                top: calc(100% + 6px);
                z-index: 10;
                max-width: min(560px, 90vw);
                max-height: 280px;
                overflow: auto;
                padding: 10px 12px;
                background: #fff;
                color: var(--aieo-product-meta-text);
                border: 1px solid rgba(0, 0, 0, 0.12);
                border-radius: 8px;
                box-shadow: 0 12px 28px rgba(0, 0, 0, 0.12), 0 2px 6px rgba(0, 0, 0, 0.06);
                font-size: 0.9em;
                line-height: 1.5;
                white-space: normal;
                word-break: break-word;
            }
            .aieo-product-meta__tooltip.visible {
                display: block;
            }
        ';
        
        $css .= '.aieo-product-meta .aieo-product-meta__label{font-weight:' . ( !empty($s['title_bold']) ? '600' : '400' ) . ';}';
        if (!empty($s['link_color'])) {
            $css .= '.aieo-product-meta .aieo-product-meta__more{color:' . esc_attr((string) $s['link_color']) . ';}';
        }
        wp_register_style('aieo-product-meta', false, array(), defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');
        wp_enqueue_style('aieo-product-meta');
        wp_add_inline_style('aieo-product-meta', $css);
    }

    
    public function is_active() {
        $s = $this->get_settings();
        return !empty($s['enabled']);
    }

    public function output() {
        if (!$this->is_active()) { return; }
        $s = $this->get_settings();
        if (!empty($s['use_shortcode'])) { return; }
        echo $this->get_html(); 
    }

    public function shortcode_handler($atts = array()) {
        $s = $this->get_settings();
        if (empty($s['enabled']) || empty($s['use_shortcode'])) { return ''; }
        if (!is_singular('product')) { return ''; }
        return $this->get_html();
    }

    
    public function render_for_block() {
        if (empty($this->get_settings()['enabled']))           { return ''; }
        if (!function_exists('is_singular') || !is_singular('product')) { return ''; }
        return $this->get_html();
    }

    private function get_html() {
        global $product;
        if (!$product || !is_a($product, 'WC_Product')) { $product = wc_get_product(get_the_ID()); }
        if (!$product) { return ''; }

        $s = $this->get_settings();
        if (empty($s['show_sku']) && empty($s['show_barcode'])) { return ''; }

        $is_variable = $product->is_type('variable');
        $codes = $this->get_codes($product, $is_variable);
        if (empty($codes['sku']) && empty($codes['barcode'])) { return ''; }

        $cls = 'aieo-product-meta' . (!empty($s['custom_class']) ? ' ' . esc_attr((string) $s['custom_class']) : '');
        $sku_label     = $is_variable ? (string) $s['sku_label_plural'] : (string) $s['sku_label'];
        $barcode_label = $is_variable ? (string) $s['barcode_label_plural'] : (string) $s['barcode_label'];

        ob_start();
        ?>
        <div class="<?php echo esc_attr($cls); ?>">
            <?php if (!empty($s['show_sku']) && !empty($codes['sku'])): ?>
                <div class="aieo-product-meta__row aieo-product-meta__row--sku">
                    <span class="aieo-product-meta__label"><?php echo esc_html($sku_label); ?>:</span>
                    <?php echo $this->render_codes($codes['sku'], $is_variable, $codes['sku_total']); ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($s['show_barcode']) && !empty($codes['barcode'])): ?>
                <div class="aieo-product-meta__row aieo-product-meta__row--barcode">
                    <span class="aieo-product-meta__label"><?php echo esc_html($barcode_label); ?>:</span>
                    <?php echo $this->render_codes($codes['barcode'], $is_variable, $codes['barcode_total']); ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
        return (string) ob_get_clean();
    }

    private function get_codes($product, $is_variable) {
        global $wpdb;
        $sku = trim((string) $product->get_sku());
        $barcode = trim((string) get_post_meta($product->get_id(), '_global_unique_id', true));
        if ($barcode === '') { $barcode = trim((string) get_post_meta($product->get_id(), '_barcode', true)); }

        
        
        
        
        if ($is_variable) {
            $tbl = $wpdb->prefix . 'aieo_core_product_vitals';
            $exists = (string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tbl)) === $tbl;
            if ($exists) {
                $pid = (int) $product->get_id();
                $row = $wpdb->get_row($wpdb->prepare(
                    "SELECT sku_index, barcode_index FROM {$tbl} WHERE product_id = %d AND parent_id = %d LIMIT 1",
                    $pid, $pid
                ), ARRAY_A);
                if (!$row) {
                    $row = $wpdb->get_row($wpdb->prepare(
                        "SELECT sku_index, barcode_index FROM {$tbl} WHERE product_id = %d LIMIT 1", $pid
                    ), ARRAY_A);
                }
                $sku_csv = isset($row['sku_index']) ? (string) $row['sku_index'] : '';
                $bar_csv = isset($row['barcode_index']) ? (string) $row['barcode_index'] : '';
                return array(
                    'sku'           => $this->csv_to_list($sku_csv),
                    'barcode'       => $this->csv_to_list($bar_csv),
                    'sku_total'     => null,
                    'barcode_total' => null,
                );
            }
        }
        return array(
            'sku'           => $sku !== '' ? array($sku) : array(),
            'barcode'       => $barcode !== '' ? array($barcode) : array(),
            'sku_total'     => null,
            'barcode_total' => null,
        );
    }

    private function csv_to_list($csv) {
        if (!is_string($csv) || $csv === '') { return array(); }
        return array_values(array_filter(array_map('trim', explode(',', $csv)), function($v){ return $v !== ''; }));
    }

    private function render_codes($codes, $is_variable, $total = null) {
        $codes = array_values(array_filter(array_unique(array_map('trim', $codes))));
        if (empty($codes)) { return ''; }
        $s = $this->get_settings();
        $max = max(1, (int) $s['max_visible']);
        if (!$is_variable) {
            return '<span class="aieo-product-meta__codes">' . esc_html(implode(', ', $codes)) . '</span>';
        }
        $first = array_slice($codes, 0, $max);
        $rest  = array_slice($codes, $max);
        $html  = '<span class="aieo-product-meta__codes">' . esc_html(implode(', ', $first)) . '</span>';
        $remaining = is_numeric($total) ? max(0, (int) $total - count($first)) : count($rest);
        if ($remaining > 0) {
            $label = sprintf((string) $s['more_text'], $remaining);
            $html .= ' <span class="aieo-product-meta__more" role="button" tabindex="0" aria-haspopup="true">' . esc_html($label) . '</span>';
            if (!empty($rest)) {
                $html .= '<div class="aieo-product-meta__tooltip" role="tooltip">' . esc_html(implode(', ', $rest)) . '</div>';
            }
        }
        return $html;
    }

    public function render_subtab() {
        $s = $this->get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Product Meta', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Show SKU + barcode below the price on single product pages. For variable products with the AIEO/Pods vitals table, displays an aggregated index across all variations with an "and N more" overflow pill.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-pm-form" class="aieo-dmm-form aieo-dmm-card"><table class="form-table">';
        echo '<tr><th>' . esc_html__('Enable', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="enabled" value="1" ' . checked(!empty($s['enabled']), true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Show SKU', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="show_sku" value="1" ' . checked(!empty($s['show_sku']), true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Show barcode', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="show_barcode" value="1" ' . checked(!empty($s['show_barcode']), true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('SKU label (singular / plural)', 'ai-eshop-optimizer') . '</th><td><input type="text" name="sku_label" value="' . esc_attr((string) $s['sku_label']) . '" class="regular-text"> <input type="text" name="sku_label_plural" value="' . esc_attr((string) $s['sku_label_plural']) . '" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Barcode label (singular / plural)', 'ai-eshop-optimizer') . '</th><td><input type="text" name="barcode_label" value="' . esc_attr((string) $s['barcode_label']) . '" class="regular-text"> <input type="text" name="barcode_label_plural" value="' . esc_attr((string) $s['barcode_label_plural']) . '" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Max visible (variable products)', 'ai-eshop-optimizer') . '</th><td><input type="number" name="max_visible" min="1" max="20" value="' . (int) $s['max_visible'] . '" class="small-text"></td></tr>';
        
        echo '<tr><th>' . esc_html__('Overflow text', 'ai-eshop-optimizer') . '</th><td><input type="text" name="more_text" value="' . esc_attr((string) $s['more_text']) . '" class="regular-text"><p class="description">' . esc_html__('Use %d for the count.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th>' . esc_html__('Text colour', 'ai-eshop-optimizer') . '</th><td><input type="color" name="text_color" value="' . esc_attr((string) $s['text_color']) . '"></td></tr>';
        echo '<tr><th>' . esc_html__('Label colour', 'ai-eshop-optimizer') . '</th><td><input type="color" name="label_color" value="' . esc_attr((string) $s['label_color']) . '"></td></tr>';
        echo '<tr><th>' . esc_html__('Link colour', 'ai-eshop-optimizer') . '</th><td><input type="text" name="link_color" value="' . esc_attr((string) $s['link_color']) . '" placeholder="#0073aa" style="width:120px;"><p class="description">' . esc_html__('Colour of the “and N more” link. Leave blank to inherit.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th>' . esc_html__('Bold the title', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="title_bold" value="1" ' . checked(!empty($s['title_bold']), true, false) . '> ' . esc_html__('Render the label (e.g. “SKUs:”) in bold', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th>' . esc_html__('Font size', 'ai-eshop-optimizer') . '</th><td><input type="text" name="font_size" value="' . esc_attr((string) $s['font_size']) . '" placeholder="0.92em" style="width:120px;"><p class="description">' . esc_html__('CSS size, e.g. 0.92em or 13px. Match Categories / Brand for a consistent info column.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th>' . esc_html__('Custom CSS class', 'ai-eshop-optimizer') . '</th><td><input type="text" name="custom_class" value="' . esc_attr((string) $s['custom_class']) . '" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Use shortcode', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="use_shortcode" value="1" ' . checked(!empty($s['use_shortcode']), true, false) . '> [aieo_product_meta]</label></td></tr>';
        echo '</table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-pm-save">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-pm-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p>';
        echo '</form>';
        echo '<script>(function(){var f=document.getElementById("aieo-dmm-pm-form");var b=document.getElementById("aieo-dmm-pm-save");var s=document.getElementById("aieo-dmm-pm-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_product_meta_save");fd.set("nonce","' . esc_js($nonce) . '");s.style.color="#646970";s.textContent="' . esc_js(__('Saving…', 'ai-eshop-optimizer')) . '";fetch("' . esc_js($ajax) . '",{method:"POST",credentials:"same-origin",body:fd}).then(function(r){return r.json();}).then(function(j){if(j&&j.success){s.style.color="#15803d";s.textContent=j.data.message;}else{s.style.color="#b91c1c";s.textContent=(j&&j.data&&j.data.message)||"' . esc_js(__('Save failed.', 'ai-eshop-optimizer')) . '";}});});})();</script>';
        echo '</div>';
    }
}
