<?php

namespace CouponsPlus\App\Handlers;

use WC_Product_Variable;
use CouponsPlus\Original\Events\Handler\EventHandler;

Class ProductVariationSearchAdminAjaxExtender extends EventHandler
{
    protected $numberOfArguments = 1;
    protected $priority = 10;

    public function execute()
    {
        // Check if we're in admin and it's our specific ajax request
        add_filter('woocommerce_json_search_found_products', [$this, 'extendProductSearchResults'], 10, 1);
    }

    /**
     * Extend the WooCommerce product search results with additional information
     *
     * @param array $products The original search results
     * @return array Modified search results
     */
    public function extendProductSearchResults($products)
    {
        (string) $nonce = sanitize_text_field(wp_unslash($_REQUEST['couponsPlusDashboardNonce'] ?? ''));

        if (!wp_verify_nonce($nonce, 'coupons-plus-dashboard')) {
            return $products;
        }

        // Only modify the response if our custom parameter is present
        if (!isset($_GET['couponsPlusMode']) || $_GET['couponsPlusMode'] !== 'tree') {
            return $products;
        }

        return $this->formatProducts(array_keys($products));
    }

    /**
     * Get product image URL with specified size
     *
     * @param \WC_Product $product Product object
     * @param string $size Image size (thumbnail, medium, large, etc.)
     * @return string Image URL or empty string if no image
     */
    private function getProductImageUrl($product, $size = 'thumbnail')
    {
        $image_url = '';
        $image_id = $product->get_image_id();

        // If product has no image and it's a variation, try to get parent product image
        if (!$image_id && $product->get_type() === 'variation') {
            $parent_id = $product->get_parent_id();
            $parent = wc_get_product($parent_id);
            if ($parent) {
                $image_id = $parent->get_image_id();
            }
        }

        if ($image_id) {
            $image = wp_get_attachment_image_src($image_id, $size);
            if ($image) {
                $image_url = $image[0];
            }
        }

        // Return default WooCommerce placeholder if no image is found
        if (empty($image_url)) {
            $image_url = wc_placeholder_img_src($size);
        }

        return $image_url ?: null;
    }

    public function formatProducts(array $productIds) : array
    {
        $enhanced_products = [];

        foreach ($productIds as $id) {
            $product = wc_get_product($id);

            if (!$product) {
                // Skip if product not found, it will be rendered as ?
                continue;
            }
            // Enhance the product data with more information
            $enhanced_products[$id] = [
                'id' => $id,
                'name' => $product->get_name('edit'), // replace the ugly name with the base product name
                'price' => $product->get_price(),
                'regular_price' => $product->get_regular_price(),
                'sale_price' => $product->get_sale_price(),
                'type' => $product->get_type(),
                'typeLabel' => isset(wc_get_product_types()[$product->get_type()]) ? wc_get_product_types()[$product->get_type()] : ucfirst($product->get_type()),
                'isVariable' => $product->get_type() === 'variable',
                'isVariation' => $product->get_type() === 'variation',
                'sku' => $product->get_sku(),
                'stock_status' => $product->get_stock_status(),
                'image_url' => $this->getProductImageUrl($product, 'thumbnail'), // Add small square thumbnail
            ];

            // For variations, add parent product info
            if ($product->get_type() === 'variation') {
                $parent_id = $product->get_parent_id();
                $parent_product = wc_get_product($parent_id);

                if ($parent_product) {
                    $enhanced_products[$id]['parent_id'] = $parent_id;
                    $enhanced_products[$id]['parent_name'] = $parent_product->get_name();

                    // Get the variation attributes
                    $attributes = [];
                    $variation_attributes = $product->get_attributes();

                    if (!empty($variation_attributes)) {
                        foreach ($variation_attributes as $attribute_name => $attribute_value) {
                            $taxonomy = str_replace('attribute_', '', $attribute_name);

                            // Get attribute label
                            $attribute_label = wc_attribute_label($taxonomy, $parent_product);
                            // For taxonomy-based attributes
                            if (taxonomy_exists($taxonomy)) {
                                $term = get_term_by('slug', $attribute_value, $taxonomy);
                                $attribute_value_label = $term ? $term->name : $attribute_value;
                                $attribute_value = $attribute_value_label;
                            }

                            $attributes[] = [
                                'name' => $attribute_label,
                                'value' => $attribute_value,
                                'slug' => $taxonomy,
                            ];
                        }
                    }

                    $enhanced_products[$id]['attributes'] = $attributes;
                }
            }
        }

        return array_values($enhanced_products);
    }
}