<?php

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

class AIEO_DMM_Product_Labels extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_product_labels_settings';

    public function get_id()       { return 'product_labels'; }
    public function get_label()    { return __('Product Labels', 'ai-eshop-optimizer'); }
    public function get_priority() { return 20; }
    public function get_group()    { return 'product_display'; }

    public function register_hooks() {
        
        
        
        add_filter('aieo_eligibility_compute', array(__CLASS__, 'add_eligibility_row'), 10, 3);

        add_action('wp_ajax_aieo_dmm_product_labels_save', array($this, 'ajax_save'));
        add_shortcode('om_ppe_product_labels', array($this, 'shortcode_handler'));

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

        add_action('wp_enqueue_scripts',                   array($this, 'enqueue_styles'));
        add_action('woocommerce_before_shop_loop_item',    array($this, 'loop_output'), 10);
        add_action('woocommerce_product_thumbnails',       array($this, 'single_output'));
        
        add_filter('woocommerce_sale_flash', '__return_empty_string', 9999);
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        $legacy = get_option('om_ppe_product-labels', array());
        if (!is_array($legacy)) { $legacy = array(); }
        return array_merge(array(
            'enabled'           => false,
            'label_text'        => 'SALE',
            'display_rules'     => 'products_on_sale',
            'new_products_days' => 7,
            'label_position'    => 'top-left',
            'background_color'  => '#212121',
            'text_color'        => '#ffffff',
            'font_size'         => 14,
            'border_radius'     => 5,
            'padding_x'         => 15,
            'padding_y'         => 8,
            'show_on_single'    => true,
            'show_on_archive'   => true,
            'use_shortcode'     => false,
        ), $legacy, $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $valid_rules     = array('products_on_sale','featured_products','new_products','out_of_stock','all_products');
        $valid_positions = array('top-left','top-right','bottom-left','bottom-right');
        $rule = isset($_POST['display_rules']) ? sanitize_key(wp_unslash($_POST['display_rules'])) : 'products_on_sale';
        $pos  = isset($_POST['label_position']) ? sanitize_key(wp_unslash($_POST['label_position'])) : 'top-left';
        update_option(self::OPTION_KEY, array(
            'enabled'           => !empty($_POST['enabled']),
            'label_text'        => isset($_POST['label_text']) ? sanitize_text_field(wp_unslash($_POST['label_text'])) : 'SALE',
            'display_rules'     => in_array($rule, $valid_rules, true) ? $rule : 'products_on_sale',
            'new_products_days' => max(1, min(365, isset($_POST['new_products_days']) ? (int) $_POST['new_products_days'] : 7)),
            'label_position'    => in_array($pos, $valid_positions, true) ? $pos : 'top-left',
            'background_color'  => isset($_POST['background_color']) ? (sanitize_hex_color(wp_unslash($_POST['background_color'])) ?: '#212121') : '#212121',
            'text_color'        => isset($_POST['text_color']) ? (sanitize_hex_color(wp_unslash($_POST['text_color'])) ?: '#ffffff') : '#ffffff',
            'font_size'         => max(10, min(30, isset($_POST['font_size']) ? (int) $_POST['font_size'] : 14)),
            'border_radius'     => max(0, min(50, isset($_POST['border_radius']) ? (int) $_POST['border_radius'] : 5)),
            'padding_x'         => max(5, min(50, isset($_POST['padding_x']) ? (int) $_POST['padding_x'] : 15)),
            'padding_y'         => max(2, min(30, isset($_POST['padding_y']) ? (int) $_POST['padding_y'] : 8)),
            'show_on_single'    => !empty($_POST['show_on_single']),
            'show_on_archive'   => !empty($_POST['show_on_archive']),
            'use_shortcode'     => !empty($_POST['use_shortcode']),
        ), false);
        wp_send_json_success(array('message' => __('Product Labels settings saved.', 'ai-eshop-optimizer')));
    }

    public function enqueue_styles() {
        
        
        
        
        if (class_exists('AIEO_DMM_Badge_Renderer') && AIEO_DMM_Badge_Renderer::is_enabled()) { return; }

        
        
        
        
        
        wp_register_style('aieo-product-labels', false); 
        wp_enqueue_style('aieo-product-labels');
        
        $css = '.woocommerce .onsale,.wc-block-grid__product-onsale,.wc-block-grid__product .onsale{display:none !important;}';
        wp_add_inline_style('aieo-product-labels', $css);
    }

    public function loop_output() {
        if (class_exists('AIEO_DMM_Badge_Renderer') && AIEO_DMM_Badge_Renderer::is_enabled()) { return; }
        $s = $this->get_settings();
        if (empty($s['show_on_archive'])) { return; }
        global $product;
        if (!$product) { return; }
        echo wp_kses_post($this->get_label_html($product));
    }

    public function single_output() {
        if (class_exists('AIEO_DMM_Badge_Renderer') && AIEO_DMM_Badge_Renderer::is_enabled()) { return; }
        $s = $this->get_settings();
        if (!empty($s['use_shortcode']) || empty($s['show_on_single'])) { return; }
        global $product;
        if (!$product) { return; }
        echo wp_kses_post($this->get_label_html($product));
    }

    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__('Product Labels shortcode can only be used on single product pages.', 'ai-eshop-optimizer') . '</p>';
            }
            return '';
        }
        global $product;
        return $product ? $this->get_label_html($product) : '';
    }

    private function get_label_html($product) {
        if (!$this->should_display_label($product)) { return ''; }
        $s = $this->get_settings();
        $label = (string) $s['label_text'];
        if (strpos($label, '{sale}') !== false) {
            $label = str_replace('{sale}', $this->sale_pct($product) . '%', $label);
        }
        if (strpos($label, '{sale_amount}') !== false) {
            $label = str_replace('{sale_amount}', wc_price($this->sale_amount($product)), $label);
        }
        $position_class = 'position-' . esc_attr((string) $s['label_position']);
        $style = sprintf(
            'background-color:%s;color:%s;font-size:%dpx;border-radius:%dpx;padding:%dpx %dpx;',
            esc_attr((string) $s['background_color']),
            esc_attr((string) $s['text_color']),
            (int) $s['font_size'],
            (int) $s['border_radius'],
            (int) $s['padding_y'],
            (int) $s['padding_x']
        );
        return sprintf(
            '<div class="om-ppe-product-labels %s"><span class="om-ppe-label" style="%s">%s</span></div>',
            $position_class,
            esc_attr($style),
            esc_html($label)
        );
    }

    private function should_display_label($product) {
        if (!$product) { return false; }
        $s = $this->get_settings();
        $rule = (string) $s['display_rules'];
        switch ($rule) {
            case 'products_on_sale':  $display = $product->is_on_sale(); break;
            case 'featured_products': $display = $product->is_featured(); break;
            case 'out_of_stock':      $display = !$product->is_in_stock(); break;
            case 'all_products':      $display = true; break;
            case 'new_products':
                $days = (int) $s['new_products_days'];
                $display = $this->is_new_product($product, $days);
                break;
            default: $display = $product->is_on_sale(); break;
        }
        
        return (bool) apply_filters('om_ppe_product_label_display', $display, $product, $rule); 
    }

    
    public static function add_eligibility_row($rows, $product_id, $audience_key) {
        if (!is_array($rows)) { $rows = array(); }
        $product_id = (int) $product_id;
        if ($product_id === 0) { return $rows; }
        if (!class_exists('AIEO_Effective_Eligibility')) { return $rows; }
        $r = self::is_eligible_for($product_id, (string) $audience_key);
        if (!empty($r['eligible'])) {
            $rows[AIEO_Effective_Eligibility::SURFACE_PRODUCT_LABEL] = $r;
        }
        return $rows;
    }

    
    public static function is_eligible_for($product_id, $audience_key = 'guest') {
        $product_id = (int) $product_id;
        if ($product_id <= 0) { return array('eligible' => false); }
        if (!function_exists('wc_get_product')) { return array('eligible' => false); }
        $product = wc_get_product($product_id);
        if (!$product) { return array('eligible' => false); }

        $instance = self::eligibility_instance();
        $s = $instance->get_settings();
        if (empty($s['enabled'])) { return array('eligible' => false); }

        $rule = isset($s['display_rules']) ? (string) $s['display_rules'] : 'products_on_sale';
        switch ($rule) {
            case 'products_on_sale':  $display = $product->is_on_sale(); break;
            case 'featured_products': $display = $product->is_featured(); break;
            case 'out_of_stock':      $display = !$product->is_in_stock(); break;
            case 'all_products':      $display = true; break;
            case 'new_products':
                $days = isset($s['new_products_days']) ? (int) $s['new_products_days'] : 7;
                $display = $instance->is_new_product($product, $days);
                break;
            default: $display = $product->is_on_sale(); break;
        }
        $display = (bool) apply_filters('om_ppe_product_label_display', $display, $product, $rule); 
        if (!$display) { return array('eligible' => false); }

        return array(
            'eligible' => true,
            'offer_id' => null,
            'payload'  => array(
                'rule'  => $rule,
                'label' => isset($s['label_text']) ? (string) $s['label_text'] : 'SALE',
            ),
        );
    }

    private static function eligibility_instance() {
        static $inst = null;
        if ($inst === null) {
            if (class_exists('AIEO_DMM') && method_exists('AIEO_DMM', 'instance')) {
                $mod = AIEO_DMM::instance()->get_module('product_labels');
                $inst = ($mod instanceof self) ? $mod : new self();
            } else {
                $inst = new self();
            }
        }
        return $inst;
    }

    private function is_new_product($product, $days) {
        $product_date = (string) get_the_date('Y-m-d', $product->get_id());
        $current_date = gmdate('Y-m-d');
        $diff = abs(strtotime($current_date) - strtotime($product_date)) / DAY_IN_SECONDS;
        return $diff <= $days;
    }

    private function sale_pct($product) {
        if ($product->is_type('variable')) {
            $reg = (float) $product->get_variation_regular_price('min');
            $sal = (float) $product->get_variation_sale_price('min');
        } else {
            $reg = (float) $product->get_regular_price();
            $sal = (float) $product->get_sale_price();
        }
        if ($reg <= 0 || $sal <= 0) { return 0; }
        return (int) round(100 - ($sal / $reg * 100));
    }

    private function sale_amount($product) {
        if ($product->is_type('variable')) {
            $reg = (float) $product->get_variation_regular_price('min');
            $sal = (float) $product->get_variation_sale_price('min');
        } else {
            $reg = (float) $product->get_regular_price();
            $sal = (float) $product->get_sale_price();
        }
        return max(0, $reg - $sal);
    }

    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 Labels', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('"SALE", "NEW", "Hot" badges over product images on shop and single pages. Tokens: {sale} → discount %, {sale_amount} → discount €.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-pll-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__('Label text', 'ai-eshop-optimizer') . '</th><td><input type="text" name="label_text" value="' . esc_attr((string) $s['label_text']) . '" class="regular-text"><p class="description">' . esc_html__('Tokens: {sale} = discount percentage, {sale_amount} = discount € amount.', 'ai-eshop-optimizer') . '</p></td></tr>';

        echo '<tr><th>' . esc_html__('Display on', 'ai-eshop-optimizer') . '</th><td><select name="display_rules">';
        $rules = array(
            'products_on_sale'  => __('Products on sale', 'ai-eshop-optimizer'),
            'featured_products' => __('Featured products', 'ai-eshop-optimizer'),
            'new_products'      => __('New products', 'ai-eshop-optimizer'),
            'out_of_stock'      => __('Out of stock', 'ai-eshop-optimizer'),
            'all_products'      => __('All products', 'ai-eshop-optimizer'),
        );
        foreach ($rules as $val => $label) {
            echo '<option value="' . esc_attr($val) . '" ' . selected($s['display_rules'], $val, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';

        echo '<tr><th>' . esc_html__('"New" days threshold', 'ai-eshop-optimizer') . '</th><td><input type="number" name="new_products_days" min="1" max="365" value="' . (int) $s['new_products_days'] . '" class="small-text"><p class="description">' . esc_html__('Only used when display rule is "New products".', 'ai-eshop-optimizer') . '</p></td></tr>';

        echo '<tr><th>' . esc_html__('Position', 'ai-eshop-optimizer') . '</th><td><select name="label_position">';
        foreach (array('top-left' => __('Top left', 'ai-eshop-optimizer'), 'top-right' => __('Top right', 'ai-eshop-optimizer'), 'bottom-left' => __('Bottom left', 'ai-eshop-optimizer'), 'bottom-right' => __('Bottom right', 'ai-eshop-optimizer')) as $val => $label) {
            echo '<option value="' . esc_attr($val) . '" ' . selected($s['label_position'], $val, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';

        echo '<tr><th colspan="2"><h3 style="margin:8px 0 0;">' . esc_html__('Style', 'ai-eshop-optimizer') . '</h3></th></tr>';
        echo '<tr><th>' . esc_html__('Background', 'ai-eshop-optimizer') . '</th><td><input type="color" name="background_color" value="' . esc_attr((string) $s['background_color']) . '"></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__('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__('Border radius', 'ai-eshop-optimizer') . '</th><td><input type="number" name="border_radius" min="0" max="50" value="' . (int) $s['border_radius'] . '" class="small-text"> px</td></tr>';
        echo '<tr><th>' . esc_html__('Padding (X / Y)', 'ai-eshop-optimizer') . '</th><td><input type="number" name="padding_x" min="5" max="50" value="' . (int) $s['padding_x'] . '" class="small-text"> px <span style="color:#999;">×</span> <input type="number" name="padding_y" min="2" max="30" value="' . (int) $s['padding_y'] . '" class="small-text"> px</td></tr>';

        echo '<tr><th colspan="2"><h3 style="margin:8px 0 0;">' . esc_html__('Where to show', 'ai-eshop-optimizer') . '</h3></th></tr>';
        echo '<tr><th>' . esc_html__('Single product page', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="show_on_single" value="1" ' . checked(!empty($s['show_on_single']), true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Shop / archive pages', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="show_on_archive" value="1" ' . checked(!empty($s['show_on_archive']), true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Use shortcode for single (manual)', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="use_shortcode" value="1" ' . checked(!empty($s['use_shortcode']), true, false) . '> [om_ppe_product_labels]</label></td></tr>';

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