<?php

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

class AIEO_DMM_Checkout_Product_Images extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_checkout_product_images';

    public function get_id()       { return 'checkout_product_images'; }
    public function get_label()    { return __('Checkout Product Images', 'ai-eshop-optimizer'); }
    public function get_priority() { return 35; }
    public function get_group()    { return 'checkout_handling'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_checkout_product_images_save', array($this, 'ajax_save'));

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

        add_filter('woocommerce_cart_item_name',              array($this, 'add_product_image'), 10, 3);
        add_filter('woocommerce_checkout_cart_item_quantity', '__return_empty_string');
        add_action('wp_head',                                  array($this, 'output_styles'));
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        $legacy = get_option('om_checkout_settings', array());
        if (!is_array($legacy)) { $legacy = array(); }
        return array_merge(array(
            
            
            'enabled'        => 'yes',
            'image_source'   => isset($legacy['checkout_variation_image']) ? (string) $legacy['checkout_variation_image'] : 'swatch',
            'thumbnail_size' => 48,
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $source = isset($_POST['image_source']) ? sanitize_key(wp_unslash($_POST['image_source'])) : 'swatch';
        if (!in_array($source, array('swatch','gallery','variation','product'), true)) { $source = 'swatch'; }
        update_option(self::OPTION_KEY, array(
            'enabled'        => !empty($_POST['enabled']) ? 'yes' : 'no',
            'image_source'   => $source,
            'thumbnail_size' => isset($_POST['thumbnail_size']) ? max(24, min(160, (int) $_POST['thumbnail_size'])) : 48,
        ), false);
        wp_send_json_success(array('message' => __('Checkout product images settings saved.', 'ai-eshop-optimizer')));
    }

    
    private function get_variation_swatch_image($variation, $size, $attrs) {
        if (!$variation || !is_a($variation, 'WC_Product_Variation')) { return ''; }
        $attributes = $variation->get_attributes();
        foreach ($attributes as $attr_name => $attr_value) {
            if ($attr_value === '' || $attr_value === null) { continue; }
            $taxonomy = (strpos((string) $attr_name, 'pa_') === 0) ? (string) $attr_name : 'pa_' . $attr_name;
            if (!taxonomy_exists($taxonomy)) { continue; }
            $term = get_term_by('slug', $attr_value, $taxonomy);
            if (!$term || is_wp_error($term)) { continue; }
            
            
            $image_id = (int) get_term_meta($term->term_id, '_aieo_swatch_image_id', true);
            if ($image_id <= 0) {
                $image_id = (int) get_term_meta($term->term_id, 'product_attribute_image', true);
            }
            $image_id = (int) apply_filters('aieo_swatch_image_id_for_term', $image_id, (int) $term->term_id, $taxonomy);
            if ($image_id > 0) {
                $html = wp_get_attachment_image($image_id, $size, false, $attrs);
                if ($html !== '') { return $html; }
            }
        }
        return '';
    }

    public function add_product_image($product_name, $cart_item, $cart_item_key) {
        if (!function_exists('is_checkout') || !is_checkout()) { return $product_name; }

        $product = isset($cart_item['data']) ? $cart_item['data'] : null;
        if (!$product) { return $product_name; }

        $s            = $this->get_settings();
        $size         = (int) $s['thumbnail_size'];
        $image_size   = array($size, $size);
        $image_attrs  = array('class' => 'om-checkout-product-thumb', 'loading' => 'lazy');
        $image_source = (string) $s['image_source'];

        $thumbnail = '';

        if ($image_source !== 'product' && !empty($cart_item['variation_id'])) {
            $variation_id = absint($cart_item['variation_id']);
            $variation    = wc_get_product($variation_id);

            if ($variation) {
                switch ($image_source) {
                    case 'swatch':
                        $thumbnail = $this->get_variation_swatch_image($variation, $image_size, $image_attrs);
                        break;
                    case 'gallery':
                        
                        $gallery = get_post_meta($variation_id, 'botiga_variation_gallery', true);
                        if (!empty($gallery) && is_array($gallery)) {
                            $first = reset($gallery);
                            if (is_numeric($first)) {
                                $thumbnail = wp_get_attachment_image(absint($first), $image_size, false, $image_attrs);
                            }
                        }
                        break;
                    case 'variation':
                        $img_id = (int) get_post_meta($variation_id, '_thumbnail_id', true);
                        if ($img_id > 0) {
                            $thumbnail = wp_get_attachment_image($img_id, $image_size, false, $image_attrs);
                        }
                        break;
                }
            }
        }

        
        if ($thumbnail === '') {
            $thumbnail = (string) $product->get_image($image_size, $image_attrs);
        }
        if ($thumbnail === '') { return $product_name; }

        $qty      = isset($cart_item['quantity']) ? (int) $cart_item['quantity'] : 1;
        $qty_html = '<span class="om-checkout-product-qty">' . esc_html($qty) . '×</span>';

        
        return '<div class="om-checkout-product-item">' . $qty_html . $thumbnail . '<span class="om-checkout-product-name">' . $product_name . '</span></div>';
    }

    public function output_styles() {
        if (!function_exists('is_checkout') || !is_checkout()) { return; }
        $s    = $this->get_settings();
        $size = (int) $s['thumbnail_size'];
        ?>
        <style>
        /* Scoped to .woocommerce-checkout to avoid leaking into cart/account pages */
        .woocommerce-checkout .woocommerce-checkout-review-order-table tr.cart_item td.product-name {
            display: flex !important;
            align-items: center !important;
            text-align: left !important;
            padding: 12px 10px !important;
        }
        .woocommerce-checkout .woocommerce-checkout-review-order-table tr.cart_item td.product-total {
            vertical-align: middle !important;
            padding: 12px 10px !important;
        }
        .woocommerce-checkout .woocommerce-checkout-review-order-table .om-checkout-product-item {
            display: flex; align-items: center; gap: 10px;
        }
        .woocommerce-checkout .woocommerce-checkout-review-order-table .om-checkout-product-thumb {
            width: <?php echo (int) $size; ?>px; height: <?php echo (int) $size; ?>px;
            object-fit: cover; border-radius: 4px; flex-shrink: 0; border: 1px solid #e0e0e0;
        }
        .woocommerce-checkout .woocommerce-checkout-review-order-table .om-checkout-product-name { flex: 1; line-height: 1.4; }
        .woocommerce-checkout .woocommerce-checkout-review-order-table .om-checkout-product-qty {
            flex-shrink: 0; font-weight: 600; color: #555; min-width: 28px; text-align: center;
        }
        </style>
        <?php
    }

    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__('Checkout Product Images', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Adds product thumbnails to the classic checkout\'s order-review table, with a configurable image source for variable products (attribute swatch / variation gallery / variation thumbnail / parent product). Block checkout already renders thumbnails natively, so this module is a no-op there.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-cpi-form" class="aieo-dmm-form aieo-dmm-card"><table class="form-table">';
        echo '<tr><th>' . esc_html__('Enable', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="enabled" value="1" ' . checked($s['enabled'] === 'yes', true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Image source for variable products', 'ai-eshop-optimizer') . '</th><td>';
        echo '<select name="image_source" style="min-width:240px;">';
        $opts = array(
            'swatch'    => __('Attribute swatch image (default)', 'ai-eshop-optimizer'),
            'gallery'   => __('Variation gallery (first image)', 'ai-eshop-optimizer'),
            'variation' => __('WooCommerce variation image', 'ai-eshop-optimizer'),
            'product'   => __('Parent product image only', 'ai-eshop-optimizer'),
        );
        foreach ($opts as $val => $label) {
            echo '<option value="' . esc_attr($val) . '"' . selected($s['image_source'], $val, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
        echo '<p class="description">' . esc_html__('Falls back to the parent product image if the selected source has no image for this variation.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';
        echo '<tr><th>' . esc_html__('Thumbnail size (px)', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="number" name="thumbnail_size" min="24" max="160" step="2" value="' . esc_attr((string) $s['thumbnail_size']) . '" style="width:90px;">';
        echo '</td></tr></table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-cpi-save">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-cpi-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p></form>';
        echo '<script>(function(){var f=document.getElementById("aieo-dmm-cpi-form");var b=document.getElementById("aieo-dmm-cpi-save");var s=document.getElementById("aieo-dmm-cpi-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_checkout_product_images_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>';
    }
}
