<?php

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

class AIEO_DMM_Payment_Logos extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_payment_logos_settings';

    public function get_id()       { return 'payment_logos'; }
    public function get_label()    { return __('Payment Logos', 'ai-eshop-optimizer'); }
    public function get_priority() { return 10; }
    public function get_group()    { return 'product_display'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_payment_logos_save', array($this, 'ajax_save'));
        
        add_shortcode('aieo_payment_logos',   array($this, 'shortcode_handler'));
        add_shortcode('om_ppe_payment_logos', 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'), 30);
        }
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        $legacy = get_option('om_ppe_payment-logos', array());
        if (!is_array($legacy)) { $legacy = array(); }
        return array_merge(array(
            'enabled'          => false,
            'logos'            => isset($legacy['logos']) ? (string) $legacy['logos'] : '',
            'title'            => isset($legacy['title']) ? (string) $legacy['title'] : '🔒 Safe & Secure Checkout',
            'align'            => isset($legacy['align']) ? (string) $legacy['align'] : 'flex-start',
            'font_size'        => isset($legacy['font_size']) ? (int) $legacy['font_size'] : 18,
            'text_color'       => isset($legacy['text_color']) ? (string) $legacy['text_color'] : '#212121',
            'margin_top'       => isset($legacy['margin_top']) ? (int) $legacy['margin_top'] : 20,
            'margin_bottom'    => isset($legacy['margin_bottom']) ? (int) $legacy['margin_bottom'] : 20,
            'image_max_width'  => isset($legacy['image_max_width']) ? (int) $legacy['image_max_width'] : 80,
            'image_max_height' => isset($legacy['image_max_height']) ? (int) $legacy['image_max_height'] : 100,
            'use_shortcode'    => false,
            'custom_class'     => '',
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        update_option(self::OPTION_KEY, array(
            'enabled'          => !empty($_POST['enabled']),
            'logos'            => isset($_POST['logos']) ? sanitize_text_field(wp_unslash($_POST['logos'])) : '',
            'title'            => isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '',
            'align'            => isset($_POST['align']) && in_array(sanitize_text_field( wp_unslash( $_POST['align'] ) ), array('flex-start','center','flex-end'), true) ? sanitize_text_field( wp_unslash( $_POST['align'] ) ) : 'flex-start',
            'font_size'        => max(10, min(50, isset($_POST['font_size']) ? (int) $_POST['font_size'] : 18)),
            'text_color'       => isset($_POST['text_color']) ? (sanitize_hex_color(wp_unslash($_POST['text_color'])) ?: '#212121') : '#212121',
            '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'] : 80)),
            'image_max_height' => max(20, min(200, isset($_POST['image_max_height']) ? (int) $_POST['image_max_height'] : 100)),
            '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' => __('Payment Logos 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-payment-logos',
            plugins_url('assets/css/product-display/payment-logos.css', AIEO_FILE),
            array(), $version
        );
        
        $s = $this->get_settings();
        $css = sprintf(
            '.om-ppe-payment-logos{' .
                '--om-ppe-pl-font-size:%dpx;' .
                '--om-ppe-pl-text-color:%s;' .
                '--om-ppe-pl-margin-top:%dpx;' .
                '--om-ppe-pl-margin-bottom:%dpx;' .
                '--om-ppe-pl-align:%s;' .
                '--om-ppe-pl-image-max-width:%dpx;' .
                '--om-ppe-pl-image-max-height:%dpx;' .
            '}',
            (int) $s['font_size'],
            esc_attr($s['text_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-payment-logos', $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; }

        if (is_archive() || is_page()) { return; }
        $s = $this->get_settings();
        if (!empty($s['use_shortcode'])) { return; } 

        $rendered = true;
        echo wp_kses_post($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')) {
            if (current_user_can('manage_options')) {
                return '<p style="color:red;">' . esc_html__('Payment Logos shortcode can only be used on single product pages.', 'ai-eshop-optimizer') . '</p>';
            }
            return '';
        }
        return $this->get_html();
    }

    private function get_html() {
        $s = $this->get_settings();
        $logos = !empty($s['logos']) ? array_filter(array_map('absint', explode(',', (string) $s['logos']))) : array();
        $custom_class = !empty($s['custom_class']) ? ' ' . esc_attr((string) $s['custom_class']) : '';

        ob_start();
        ?>
        <div class="om-ppe-payment-logos<?php echo $custom_class; ?>">
            <?php if (!empty($s['title'])): ?>
                <div class="om-ppe-payment-logos-title">
                    <strong><?php echo esc_html((string) $s['title']); ?></strong>
                </div>
            <?php endif; ?>
            <?php if (!empty($logos)): ?>
                <div class="om-ppe-payment-logos-images">
                    <?php foreach ($logos as $image_id):
                        $alt = (string) get_post_meta($image_id, '_wp_attachment_image_alt', true);
                        if ($alt === '') {
                            $att = get_post($image_id);
                            $alt = $att ? (string) $att->post_title : __('Payment method', 'ai-eshop-optimizer');
                        }
                        echo wp_get_attachment_image($image_id, 'thumbnail', false, array(
                            'class'   => 'om-ppe-payment-logo',
                            'alt'     => $alt,
                            'loading' => 'lazy',
                        ));
                    endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
        return (string) ob_get_clean();
    }

    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__('Payment Logos', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Show payment-method icons under the Add-to-Cart button on single product pages. Use the shortcode [aieo_payment_logos] for manual placement (toggle on below). The legacy [om_ppe_payment_logos] shortcode still works.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-pl-form" class="aieo-dmm-form aieo-dmm-card">';
        echo '<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__('Logos (comma-separated attachment IDs)', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="logos" value="' . esc_attr((string) $s['logos']) . '" class="large-text" placeholder="123,456,789">';
        echo '<p class="description">' . esc_html__('Upload PNG/SVG icons via Media Library, copy the attachment IDs from the URL after clicking each, paste here separated by commas. Or use the legacy om-product-essentials gallery picker if it\'s still active.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Title text', 'ai-eshop-optimizer') . '</th><td><input type="text" name="title" value="' . esc_attr((string) $s['title']) . '" class="regular-text"></td></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__('Title font size', 'ai-eshop-optimizer') . '</th><td><input type="number" name="font_size" min="10" max="50" 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__('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__('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 placement)', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="use_shortcode" value="1" ' . checked(!empty($s['use_shortcode']), true, false) . '> ' . esc_html__('Don\'t auto-insert; only render when [aieo_payment_logos] is used', 'ai-eshop-optimizer') . '</label></td></tr>';

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