<?php

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

class AIEO_DMM_Product_Categories extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_product_categories_settings';

    public function get_id()       { return 'product_categories'; }
    public function get_label()    { return __('Product Categories', 'ai-eshop-optimizer'); }
    public function get_priority() { return 46; } 
    public function get_group()    { return 'product_display'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_product_categories_save', array($this, 'ajax_save'));
        add_shortcode('aieo_product_categories',   array($this, 'shortcode_handler'));
        add_shortcode('om_ppe_product_categories', 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'), 41);
        }
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        return array_merge(array(
            'enabled'       => false,
            'label'         => __('Categories', 'ai-eshop-optimizer'),
            'linked'        => true,   
            'separator'     => ', ',
            'hide_uncategorized' => true,
            'text_color'    => '',
            'label_color'   => '',
            'link_color'    => '',
            'title_bold'    => true,
            'font_size'     => '0.92em',
            'use_shortcode' => false,
            'custom_class'  => '',
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        
        
        $sep = isset($_POST['separator']) ? wp_kses(wp_unslash($_POST['separator']), array()) : ', ';
        if ($sep === '') { $sep = ', '; }
        update_option(self::OPTION_KEY, array(
            'enabled'            => !empty($_POST['enabled']),
            'label'              => isset($_POST['label']) ? sanitize_text_field(wp_unslash($_POST['label'])) : '',
            'linked'             => !empty($_POST['linked']),
            'separator'          => $sep,
            'hide_uncategorized' => !empty($_POST['hide_uncategorized']),
            'text_color'         => isset($_POST['text_color']) ? (sanitize_hex_color(wp_unslash($_POST['text_color'])) ?: '') : '',
            'label_color'        => isset($_POST['label_color']) ? (sanitize_hex_color(wp_unslash($_POST['label_color'])) ?: '') : '',
            '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 Categories settings saved.', 'ai-eshop-optimizer')));
    }

    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 render_for_block() {
        if (!$this->is_active()) { return ''; }
        if (!function_exists('is_singular') || !is_singular('product')) { return ''; }
        return $this->get_html();
    }

    public function shortcode_handler($atts = array()) {
        $s = $this->get_settings();
        if (empty($s['enabled']) || empty($s['use_shortcode'])) { 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 ''; }

        $terms = get_the_terms($product->get_id(), 'product_cat');
        if (empty($terms) || is_wp_error($terms)) { return ''; }

        $s      = $this->get_settings();
        $linked = !empty($s['linked']);
        $items  = array();
        foreach ($terms as $t) {
            if (!is_object($t)) { continue; }
            if (!empty($s['hide_uncategorized']) && $t->slug === 'uncategorized') { continue; }
            if ($linked) {
                $link = get_term_link($t);
                $items[] = (!is_wp_error($link))
                    ? '<a href="' . esc_url($link) . '">' . esc_html($t->name) . '</a>'
                    : esc_html($t->name);
            } else {
                $items[] = esc_html($t->name);
            }
        }
        if (empty($items)) { return ''; }

        $label = (string) $s['label'];
        $sep   = esc_html((string) $s['separator']);
        $cls   = 'aieo-product-meta aieo-product-categories' . (!empty($s['custom_class']) ? ' ' . esc_attr((string) $s['custom_class']) : '');
        $label_style = !empty($s['label_color']) ? ' style="color:' . esc_attr((string) $s['label_color']) . '"' : '';
        $list_style  = !empty($s['text_color'])  ? ' style="color:' . esc_attr((string) $s['text_color'])  . '"' : '';

        ob_start();
        ?>
        <div class="<?php echo esc_attr($cls); ?>">
            <div class="aieo-product-meta__row aieo-product-categories__row">
                <?php if ($label !== '') : ?>
                    <span class="aieo-product-meta__label"<?php echo $label_style; ?>><?php echo esc_html($label); ?>:</span>
                <?php endif; ?>
                <span class="aieo-product-meta__codes aieo-product-categories__list"<?php echo $list_style; ?>><?php
                    
                    echo implode($sep, $items); 
                ?></span>
            </div>
        </div>
        <?php
        return (string) ob_get_clean();
    }

    public function enqueue_styles() {
        if (!function_exists('is_product') || !is_product()) { return; }
        if (!$this->is_active()) { return; }
        
        
        
        
        
        
        
        
        
        
        $s   = $this->get_settings();
        $css = '.aieo-product-categories{margin:2px 0;line-height:1.5;font-size:' . esc_attr( (string) $s['font_size'] ) . ';}'
             . '.aieo-product-categories .aieo-product-categories__row{margin:0;line-height:1.5;}'
             . '.aieo-product-categories .aieo-product-meta__label{font-weight:' . ( !empty($s['title_bold']) ? '600' : '400' ) . ';margin-right:4px;}'
             . '.aieo-product-categories .aieo-product-categories__list{color:inherit;}'
             . '.aieo-product-categories .aieo-product-categories__list a{text-decoration:none;}'
             . '.aieo-product-categories .aieo-product-categories__list a:hover{text-decoration:underline;}'
             . ( !empty($s['link_color']) ? '.aieo-product-categories .aieo-product-categories__list a{color:' . esc_attr((string) $s['link_color']) . ';}' : '' );
        wp_register_style('aieo-product-categories', false, array(), defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');
        wp_enqueue_style('aieo-product-categories');
        wp_add_inline_style('aieo-product-categories', $css);
    }

    public function render_subtab() {
        $s     = $this->get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        ?>
        <div class="aieo-dmm-section">
            <h2><?php esc_html_e('Product Categories', 'ai-eshop-optimizer'); ?></h2>
            <p class="description" style="max-width:760px;">
                <?php esc_html_e('Show the product’s categories as a clickable, comma-separated list below the price (each links to its category archive). Restores the line WooCommerce’s native meta used to show. Position it before or after Product Meta from the Display Order card.', 'ai-eshop-optimizer'); ?>
            </p>
            <form id="aieo-dmm-pcats-form" class="aieo-dmm-form aieo-dmm-card">
                <table class="form-table">
                    <tr><th><?php esc_html_e('Enable', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="enabled" value="1" <?php checked(!empty($s['enabled'])); ?>> <?php esc_html_e('Show the categories line on single-product pages', 'ai-eshop-optimizer'); ?></label></td></tr>
                    <tr><th><?php esc_html_e('Label', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="label" value="<?php echo esc_attr((string) $s['label']); ?>" class="regular-text" placeholder="<?php esc_attr_e('Categories', 'ai-eshop-optimizer'); ?>">
                        <p class="description"><?php esc_html_e('Shown before the list (e.g. “ΚΑΤΗΓΟΡΙΕΣ”). Leave blank for no label.', 'ai-eshop-optimizer'); ?></p></td></tr>
                    <tr><th><?php esc_html_e('Clickable', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="linked" value="1" <?php checked(!empty($s['linked'])); ?>> <?php esc_html_e('Link each category to its archive page', 'ai-eshop-optimizer'); ?></label></td></tr>
                    <tr><th><?php esc_html_e('Separator', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="separator" value="<?php echo esc_attr((string) $s['separator']); ?>" style="width:80px;"></td></tr>
                    <tr><th><?php esc_html_e('Hide “Uncategorized”', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="hide_uncategorized" value="1" <?php checked(!empty($s['hide_uncategorized'])); ?>> <?php esc_html_e('Skip the default Uncategorized category', 'ai-eshop-optimizer'); ?></label></td></tr>
                    <tr><th><?php esc_html_e('Label colour', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="label_color" value="<?php echo esc_attr((string) $s['label_color']); ?>" placeholder="#333333" style="width:110px;"></td></tr>
                    <tr><th><?php esc_html_e('Text colour', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="text_color" value="<?php echo esc_attr((string) $s['text_color']); ?>" placeholder="#666666" style="width:110px;"></td></tr>
                    <tr><th><?php esc_html_e('Link colour', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="link_color" value="<?php echo esc_attr((string) $s['link_color']); ?>" placeholder="#0073aa" style="width:110px;">
                            <p class="description"><?php esc_html_e('Colour of the category links. Leave blank to inherit the theme link colour.', 'ai-eshop-optimizer'); ?></p></td></tr>
                    <tr><th><?php esc_html_e('Bold the title', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="title_bold" value="1" <?php checked(!empty($s['title_bold'])); ?>> <?php esc_html_e('Render the label (e.g. “ΚΑΤΗΓΟΡΙΕΣ:”) in bold', 'ai-eshop-optimizer'); ?></label></td></tr>
                    <tr><th><?php esc_html_e('Font size', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="font_size" value="<?php echo esc_attr((string) $s['font_size']); ?>" placeholder="0.92em" style="width:110px;">
                            <p class="description"><?php esc_html_e('CSS size, e.g. 0.92em or 13px. Tip: use the same value for Categories, SKU/Barcode and Brand for a consistent info column.', 'ai-eshop-optimizer'); ?></p></td></tr>
                    <tr><th><?php esc_html_e('Custom CSS class', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="custom_class" value="<?php echo esc_attr((string) $s['custom_class']); ?>" class="regular-text"></td></tr>
                    <tr><th><?php esc_html_e('Render via shortcode only', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="use_shortcode" value="1" <?php checked(!empty($s['use_shortcode'])); ?>> <code>[aieo_product_categories]</code></label></td></tr>
                </table>
                <p class="submit">
                    <button type="submit" class="button button-primary" data-action="aieo_dmm_product_categories_save"><?php esc_html_e('Save', 'ai-eshop-optimizer'); ?></button>
                </p>
            </form>
        </div>
        <script>
        (function(){
            var f = document.getElementById('aieo-dmm-pcats-form');
            if (!f) { return; }
            f.addEventListener('submit', function(e){
                e.preventDefault();
                var fd = new FormData(f);
                fd.append('action','aieo_dmm_product_categories_save');
                fd.append('nonce', <?php echo wp_json_encode($nonce); ?>);
                fetch(<?php echo wp_json_encode($ajax); ?>, {method:'POST',credentials:'same-origin',body:fd})
                  .then(function(r){return r.json();})
                  .then(function(j){ alert(j && j.data && j.data.message ? j.data.message : 'Saved.'); })
                  .catch(function(){ alert('Save failed.'); });
            });
        })();
        </script>
        <?php
    }
}
