<?php

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

class AIEO_DMM_Trust_Badges extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_trust_badges_settings';

    public function get_id()       { return 'trust_badges'; }
    public function get_label()    { return __('Trust Badges', 'ai-eshop-optimizer'); }
    public function get_priority() { return 40; }
    public function get_group()    { return 'product_display'; }

    
    private function builtin_badges() {
        $base = plugins_url('assets/images/product-display/trust-badges/', AIEO_FILE);
        return array(
            'secure-checkout' => array(
                'label'       => __('Secure Checkout', 'ai-eshop-optimizer'),
                'description' => __('Your payment information is processed securely.', 'ai-eshop-optimizer'),
                'image_url'   => $base . 'secure-checkout.svg',
            ),
            'money-back' => array(
                'label'       => __('Money Back', 'ai-eshop-optimizer'),
                'description' => __('Full refund if you are not satisfied with your purchase.', 'ai-eshop-optimizer'),
                'image_url'   => $base . 'money-back.svg',
            ),
            'free-shipping' => array(
                'label'       => __('Free Shipping', 'ai-eshop-optimizer'),
                'description' => __('Free shipping on qualifying orders.', 'ai-eshop-optimizer'),
                'image_url'   => $base . 'free-shipping.svg',
            ),
            'quality' => array(
                'label'       => __('Quality', 'ai-eshop-optimizer'),
                'description' => __('High quality products guaranteed.', 'ai-eshop-optimizer'),
                'image_url'   => $base . 'quality.svg',
            ),
            'satisfaction' => array(
                'label'       => __('Satisfaction', 'ai-eshop-optimizer'),
                'description' => __('Your satisfaction is our priority.', 'ai-eshop-optimizer'),
                'image_url'   => $base . 'satisfaction.svg',
            ),
            'support' => array(
                'label'       => __('Support', 'ai-eshop-optimizer'),
                'description' => __('Customer support available when you need it.', 'ai-eshop-optimizer'),
                'image_url'   => $base . 'support.svg',
            ),
        );
    }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_trust_badges_save', array($this, 'ajax_save'));
        
        add_shortcode('aieo_trust_badges',   array($this, 'shortcode_handler'));
        add_shortcode('om_ppe_trust_badges', array($this, 'shortcode_handler'));

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

        add_action('wp_enqueue_scripts',                array($this, 'enqueue_styles'));
        if (empty($s['use_shortcode'])) {
            
            
            
            
            
            
            
            add_action('woocommerce_single_product_summary',  array($this, 'output'), 35);
        }
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        $legacy = get_option('om_ppe_trust-badges', array());
        if (!is_array($legacy)) { $legacy = array(); }
        return array_merge(array(
            'enabled'           => false,
            'title'             => 'Product Quality Guaranteed!',
            'badges'            => isset($legacy['badges']) ? (string) $legacy['badges'] : '',
            'default_badges'    => isset($legacy['default_badges']) ? (array) $legacy['default_badges'] : array('secure-checkout','money-back','free-shipping'),
            'hidden_badges'     => isset($legacy['hidden_badges']) ? (array) $legacy['hidden_badges'] : array(),
            'badge_overrides'   => isset($legacy['default_badges_data']) && is_array($legacy['default_badges_data']) ? $legacy['default_badges_data'] : array(),
            'align'             => 'center',
            'font_size'         => 15,
            'text_color'        => '#212121',
            'border_color'      => '#e5e5e5',
            'margin_top'        => 20,
            'margin_bottom'     => 20,
            'image_max_width'   => 70,
            'image_max_height'  => 70,
            'mobile_columns'    => '2',
            'use_shortcode'     => false,
            'custom_class'      => '',
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $valid_align = array('flex-start','center','flex-end');
        $align = isset($_POST['align']) ? sanitize_key(wp_unslash($_POST['align'])) : 'center';
        $defaults = isset($_POST['default_badges']) && is_array($_POST['default_badges'])
            ? array_values(array_filter(array_map('sanitize_key', wp_unslash($_POST['default_badges']))))
            : array();
        $hidden   = isset($_POST['hidden_badges']) && is_array($_POST['hidden_badges'])
            ? array_values(array_filter(array_map('sanitize_key', wp_unslash($_POST['hidden_badges']))))
            : array();
        
        $overrides = array();
        if (isset($_POST['badge_overrides']) && is_array($_POST['badge_overrides'])) {
            foreach (wp_unslash($_POST['badge_overrides']) as $key => $v) {
                $key = sanitize_key($key);
                if ($key === '') { continue; }
                $label = isset($v['label']) ? sanitize_text_field($v['label']) : '';
                $desc  = isset($v['description']) ? sanitize_text_field($v['description']) : '';
                if ($label !== '' || $desc !== '') {
                    $overrides[] = array('badge_key' => $key, 'label' => $label, 'description' => $desc);
                }
            }
        }
        update_option(self::OPTION_KEY, array(
            'enabled'           => !empty($_POST['enabled']),
            'title'             => isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '',
            'badges'            => isset($_POST['badges']) ? sanitize_text_field(wp_unslash($_POST['badges'])) : '',
            'default_badges'    => $defaults,
            'hidden_badges'     => $hidden,
            'badge_overrides'   => $overrides,
            'align'             => in_array($align, $valid_align, true) ? $align : 'center',
            'font_size'         => max(10, min(30, isset($_POST['font_size']) ? (int) $_POST['font_size'] : 15)),
            'text_color'        => isset($_POST['text_color']) ? (sanitize_hex_color(wp_unslash($_POST['text_color'])) ?: '#212121') : '#212121',
            'border_color'      => isset($_POST['border_color']) ? (sanitize_hex_color(wp_unslash($_POST['border_color'])) ?: '#e5e5e5') : '#e5e5e5',
            'margin_top'        => max(0, min(100, isset($_POST['margin_top']) ? (int) $_POST['margin_top'] : 20)),
            'margin_bottom'     => max(0, min(100, isset($_POST['margin_bottom']) ? (int) $_POST['margin_bottom'] : 20)),
            'image_max_width'   => max(20, min(200, isset($_POST['image_max_width']) ? (int) $_POST['image_max_width'] : 70)),
            'image_max_height'  => max(20, min(200, isset($_POST['image_max_height']) ? (int) $_POST['image_max_height'] : 70)),
            'mobile_columns'    => isset($_POST['mobile_columns']) ? (string) (int) $_POST['mobile_columns'] : '2',
            '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' => __('Trust Badges settings saved.', 'ai-eshop-optimizer')));
    }

    public function enqueue_styles() {
        if (!function_exists('is_product') || !is_product()) { return; }
        $version = defined('AIEO_VERSION') ? AIEO_VERSION : '1.0';
        wp_enqueue_style(
            'aieo-trust-badges',
            plugins_url('assets/css/product-display/trust-badges.css', AIEO_FILE),
            array(), $version
        );
        $s = $this->get_settings();
        $css = sprintf(
            '.aieo-trust-badges{' .
                '--aieo-tb-font-size:%dpx;--aieo-tb-text-color:%s;--aieo-tb-border-color:%s;' .
                '--aieo-tb-margin-top:%dpx;--aieo-tb-margin-bottom:%dpx;--aieo-tb-align:%s;' .
                '--aieo-tb-image-max-width:%dpx;--aieo-tb-image-max-height:%dpx;' .
            '}',
            (int) $s['font_size'], esc_attr($s['text_color']), esc_attr($s['border_color']),
            (int) $s['margin_top'], (int) $s['margin_bottom'], esc_attr($s['align']),
            (int) $s['image_max_width'], (int) $s['image_max_height']
        );
        wp_add_inline_style('aieo-trust-badges', $css);
    }

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

    public function output() {
        
        if (!$this->is_active()) { return; }
        
        
        
        
        static $rendered = false;
        if ($rendered) { return; }
        $rendered = true;
        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();
    }

    private function effective_badge($key) {
        $s = $this->get_settings();
        $catalog = $this->builtin_badges();
        $b = isset($catalog[$key]) ? $catalog[$key] : array();
        $custom = array();
        foreach ((array) $s['badge_overrides'] as $o) {
            if (isset($o['badge_key']) && $o['badge_key'] === $key) { $custom = $o; break; }
        }
        return array(
            'label'       => !empty($custom['label']) ? (string) $custom['label'] : (isset($b['label']) ? (string) $b['label'] : ucwords(str_replace('-', ' ', $key))),
            'description' => !empty($custom['description']) ? (string) $custom['description'] : (isset($b['description']) ? (string) $b['description'] : ''),
            'image_url'   => isset($b['image_url']) ? (string) $b['image_url'] : '',
        );
    }

    private function get_html() {
        $s = $this->get_settings();
        $defaults = (array) $s['default_badges'];
        $hidden   = (array) $s['hidden_badges'];
        $visible  = array_values(array_diff($defaults, $hidden));
        $customs  = array_filter(array_map('absint', explode(',', (string) $s['badges'])));

        if (empty($visible) && empty($customs)) { return ''; }

        
        
        
        
        
        
        $cls = 'aieo-trust-badges om-ppe-trust-badges' . (!empty($s['custom_class']) ? ' ' . esc_attr((string) $s['custom_class']) : '');
        $cols = (string) (int) $s['mobile_columns'];

        
        
        
        $visible_count_for_grid = 0;
        foreach ($visible as $key) {
            $b = $this->effective_badge($key);
            if (!empty($b['image_url'])) { $visible_count_for_grid++; }
        }
        $visible_count_for_grid += count($customs);
        $odd_attr = ($visible_count_for_grid % 2 === 1) ? ' data-total-odd="true"' : '';

        ob_start();
        ?>
        <fieldset class="<?php echo esc_attr($cls); ?>" data-mobile-cols="<?php echo esc_attr($cols); ?>"<?php echo $odd_attr; ?>>
            <?php if (!empty($s['title'])): ?>
                <legend class="aieo-trust-badges-title"><?php echo esc_html((string) $s['title']); ?></legend>
            <?php endif; ?>
            <div class="aieo-trust-badges-images">
                <?php foreach ($visible as $key):
                    $b = $this->effective_badge($key);
                    if ($b['image_url'] === '') { continue; }
                    $title_attr = $b['description'] !== '' ? $b['description'] : $b['label'];
                ?>
                    <div class="aieo-trust-badges-item">
                        <img src="<?php echo esc_url($b['image_url']); ?>" class="aieo-trust-badges-default" alt="<?php echo esc_attr($b['label']); ?>" title="<?php echo esc_attr($title_attr); ?>" width="70" height="70" loading="lazy">
                        <span class="aieo-trust-badges-text"><?php echo esc_html($b['label']); ?></span>
                    </div>
                <?php endforeach; ?>
                <?php foreach ($customs as $img_id):
                    $alt = (string) get_post_meta($img_id, '_wp_attachment_image_alt', true);
                    if ($alt === '') {
                        $att = get_post($img_id);
                        $alt = $att ? (string) $att->post_title : '';
                    }
                    $img = wp_get_attachment_image($img_id, 'thumbnail', false, array('class' => 'aieo-trust-badges-custom', 'alt' => $alt, 'loading' => 'lazy'));
                    if ($img === '') { continue; }
                ?>
                    <div class="aieo-trust-badges-item"><?php echo $img; ?></div>
                <?php endforeach; ?>
            </div>
        </fieldset>
        <?php
        return (string) ob_get_clean();
    }

    public function render_subtab() {
        $s = $this->get_settings();
        $catalog = $this->builtin_badges();
        $defaults = (array) $s['default_badges'];
        $hidden   = (array) $s['hidden_badges'];
        $overrides_by_key = array();
        foreach ((array) $s['badge_overrides'] as $o) {
            if (!empty($o['badge_key'])) { $overrides_by_key[$o['badge_key']] = $o; }
        }
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');

        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Trust Badges', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Reassurance badges (Free Shipping, Secure Checkout, Money Back, etc.) on single product pages. Pick which built-ins to show, override their labels, optionally append custom badges by Media Library attachment IDs.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-tb-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__('Title', 'ai-eshop-optimizer') . '</th><td><input type="text" name="title" value="' . esc_attr((string) $s['title']) . '" class="regular-text"></td></tr>';

        echo '<tr><th colspan="2"><h3 style="margin:8px 0 4px;">' . esc_html__('Built-in badges', 'ai-eshop-optimizer') . '</h3></th></tr>';
        foreach ($catalog as $key => $info) {
            $on   = in_array($key, $defaults, true);
            $hid  = in_array($key, $hidden, true);
            $o    = isset($overrides_by_key[$key]) ? $overrides_by_key[$key] : array();
            $lab  = isset($o['label']) ? (string) $o['label'] : '';
            $desc = isset($o['description']) ? (string) $o['description'] : '';
            echo '<tr><th>' . esc_html((string) $info['label']) . '</th><td>';
            echo '<label style="margin-right:14px;"><input type="checkbox" name="default_badges[]" value="' . esc_attr($key) . '" ' . checked($on, true, false) . '> ' . esc_html__('Show', 'ai-eshop-optimizer') . '</label>';
            echo '<label style="margin-right:14px;"><input type="checkbox" name="hidden_badges[]" value="' . esc_attr($key) . '" ' . checked($hid, true, false) . '> ' . esc_html__('Temporarily hide', 'ai-eshop-optimizer') . '</label>';
            echo '<br><input type="text" name="badge_overrides[' . esc_attr($key) . '][label]" value="' . esc_attr($lab) . '" placeholder="' . esc_attr((string) $info['label']) . '" class="regular-text" style="margin-top:6px;">';
            echo '<input type="text" name="badge_overrides[' . esc_attr($key) . '][description]" value="' . esc_attr($desc) . '" placeholder="' . esc_attr((string) $info['description']) . '" class="large-text" style="margin-top:6px;">';
            echo '</td></tr>';
        }

        echo '<tr><th>' . esc_html__('Custom badge attachment IDs', 'ai-eshop-optimizer') . '</th><td><input type="text" name="badges" value="' . esc_attr((string) $s['badges']) . '" class="large-text" placeholder="123,456,789"><p class="description">' . esc_html__('Comma-separated Media Library attachment IDs. Appended after the built-in badges.', 'ai-eshop-optimizer') . '</p></td></tr>';

        echo '<tr><th colspan="2"><h3 style="margin:8px 0 4px;">' . esc_html__('Style', 'ai-eshop-optimizer') . '</h3></th></tr>';
        echo '<tr><th>' . esc_html__('Alignment', 'ai-eshop-optimizer') . '</th><td><select name="align">';
        foreach (array('flex-start' => __('Left', 'ai-eshop-optimizer'), 'center' => __('Center', 'ai-eshop-optimizer'), 'flex-end' => __('Right', 'ai-eshop-optimizer')) as $val => $label) {
            echo '<option value="' . esc_attr($val) . '" ' . selected($s['align'], $val, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';
        echo '<tr><th>' . esc_html__('Font size', 'ai-eshop-optimizer') . '</th><td><input type="number" name="font_size" min="10" max="30" value="' . (int) $s['font_size'] . '" class="small-text"> px</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__('Border colour', 'ai-eshop-optimizer') . '</th><td><input type="color" name="border_color" value="' . esc_attr((string) $s['border_color']) . '"></td></tr>';
        echo '<tr><th>' . esc_html__('Margin top', 'ai-eshop-optimizer') . '</th><td><input type="number" name="margin_top" min="0" max="100" value="' . (int) $s['margin_top'] . '" class="small-text"> px</td></tr>';
        echo '<tr><th>' . esc_html__('Margin bottom', 'ai-eshop-optimizer') . '</th><td><input type="number" name="margin_bottom" min="0" max="100" value="' . (int) $s['margin_bottom'] . '" class="small-text"> px</td></tr>';
        echo '<tr><th>' . esc_html__('Image max width', 'ai-eshop-optimizer') . '</th><td><input type="number" name="image_max_width" min="20" max="200" value="' . (int) $s['image_max_width'] . '" class="small-text"> px</td></tr>';
        echo '<tr><th>' . esc_html__('Image max height', 'ai-eshop-optimizer') . '</th><td><input type="number" name="image_max_height" min="20" max="200" value="' . (int) $s['image_max_height'] . '" class="small-text"> px</td></tr>';
        echo '<tr><th>' . esc_html__('Mobile columns', 'ai-eshop-optimizer') . '</th><td><select name="mobile_columns">';
        foreach (array('1','2','3') as $c) {
            echo '<option value="' . esc_attr($c) . '" ' . selected($s['mobile_columns'], $c, false) . '>' . esc_html($c) . '</option>';
        }
        echo '</select></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 (manual)', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="use_shortcode" value="1" ' . checked(!empty($s['use_shortcode']), true, false) . '> [aieo_trust_badges]</label> <span style="color:#6b7280;font-size:12px;">' . esc_html__('(legacy [om_ppe_trust_badges] alias still works)', 'ai-eshop-optimizer') . '</span></td></tr>';

        echo '</table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-tb-save">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-tb-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p>';
        echo '</form>';
        echo '<script>(function(){var f=document.getElementById("aieo-dmm-tb-form");var b=document.getElementById("aieo-dmm-tb-save");var s=document.getElementById("aieo-dmm-tb-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_trust_badges_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>';
    }
}
