<?php
if (!defined('ABSPATH')) {
    exit;
}

global $page_ids, $rings_data, $krfsapp_filters, $krfsapp_attributes_mapping;

$page_ids = json_decode(krfsapp_getMeta('_page_ids'), true);
$product_img = '';

$kirf_product_all_metals = [];
$kirf_product_all_metals_imgs = [];
$kirf_product_all_metals_gallery = [];

$kirf_product_all_shapes = [];
$kirf_product_all_shapes_imgs = [];
$kirf_product_all_shapes_gallery = [];

$kirf_product_gallery = [];

$metal_attr_postfix = !empty($krfsapp_attributes_mapping['metal'])
    ? $krfsapp_attributes_mapping['metal']
    : 'krfs_metal_attr';

$shape_attr_postfix = !empty($krfsapp_attributes_mapping['shape'])
    ? $krfsapp_attributes_mapping['shape']
    : 'krfs_shape_attr';


if (isset($krfsapp_filters['metal']) && is_array($krfsapp_filters['metal'])) {
    $krfsapp_filters['metal'] = $krfsapp_filters['metal'][0];
}

$metal_filter_mapping = $krfsapp_attributes_mapping['metal_terms'][$krfsapp_filters['metal']]
    ?? $krfsapp_filters['metal'];

$shape_filter_mapping = $krfsapp_attributes_mapping['shape_terms'][$krfsapp_filters['shape']]
    ?? $krfsapp_filters['shape'];

$flipped_metal_terms_array = isset($krfsapp_attributes_mapping['metal']) && !empty(isset($krfsapp_attributes_mapping['metal'])) ? array_flip($krfsapp_attributes_mapping['metal_terms']) : false;

if ($product->is_type('variable')) {
    foreach ($product->get_available_variations() as $variation) {

        /* ─────────────────────────  START variation processing  ───────────────────────── */

        $metal_attr = $variation['attributes']['attribute_pa_' . $metal_attr_postfix]
            ?? $variation['attributes']['attribute_' . $metal_attr_postfix]
            ?? '';

        $shape_attr = $variation['attributes']['attribute_pa_' . $shape_attr_postfix]
            ?? $variation['attributes']['attribute_' . $shape_attr_postfix]
            ?? '';

        if ($metal_attr === '' && $shape_attr === '') {
            continue;
        }

        $primary_img = $variation['image']['url'] ?? '';

        if ($shape_attr == '') {
            $temp_shape = $krfsapp_filters['shape'];
        } else {
            $temp_shape = $shape_attr;
        }

        if (
            $primary_img &&
            $metal_attr !== '' && stripos($metal_attr, $metal_filter_mapping) !== false &&
            $temp_shape !== '' && stripos($temp_shape, $shape_filter_mapping) !== false
        ) {
            $product_img = $primary_img;
        }

        if ($metal_attr !== '') {
            $kirf_product_all_metals[] = $metal_attr;
            $kirf_product_all_metals_imgs[$metal_attr] = $primary_img ?: ($kirf_product_all_metals_imgs[$metal_attr] ?? '');
        }
        if ($shape_attr !== '') {
            $kirf_product_all_shapes[] = $shape_attr;
            $kirf_product_all_shapes_imgs[$shape_attr] = $primary_img ?: ($kirf_product_all_shapes_imgs[$shape_attr] ?? '');
        }

        if ($metal_attr !== '') {
            $kirf_product_all_metals_gallery[$metal_attr] = $kirf_product_all_metals_gallery[$metal_attr] ?? [];
        }
        if ($shape_attr !== '') {
            $kirf_product_all_shapes_gallery[$shape_attr] = $kirf_product_all_shapes_gallery[$shape_attr] ?? [];
        }
        if ($metal_attr !== '' && $shape_attr !== '') {
            $kirf_product_gallery[$metal_attr][$shape_attr] = $kirf_product_gallery[$metal_attr][$shape_attr] ?? [];
        }

        if ($primary_img) {
            if ($metal_attr !== '' && !in_array($primary_img, $kirf_product_all_metals_gallery[$metal_attr], true)) {
                array_unshift($kirf_product_all_metals_gallery[$metal_attr], $primary_img);
            }
            if ($shape_attr !== '' && !in_array($primary_img, $kirf_product_all_shapes_gallery[$shape_attr], true)) {
                array_unshift($kirf_product_all_shapes_gallery[$shape_attr], $primary_img);
            }
            if (
                $metal_attr !== '' && $shape_attr !== '' &&
                !in_array($primary_img, $kirf_product_gallery[$metal_attr][$shape_attr], true)
            ) {
                array_unshift($kirf_product_gallery[$metal_attr][$shape_attr], $primary_img);
            }
        }

        $gallery_ids = maybe_unserialize(
            get_post_meta($variation['variation_id'], 'woo_variation_gallery_images', true)
        ) ?: [];

        foreach ($gallery_ids as $img_id) {
            $img_url = wp_get_attachment_url($img_id);
            if (!$img_url) {
                continue;
            }

            if ($metal_attr !== '') {
                $kirf_product_all_metals_gallery[$metal_attr][] = $img_url;
            }
            if ($shape_attr !== '') {
                $kirf_product_all_shapes_gallery[$shape_attr][] = $img_url;
            }
            if ($metal_attr !== '' && $shape_attr !== '') {
                $kirf_product_gallery[$metal_attr][$shape_attr][] = $img_url;
            }
        }

        if ($metal_attr !== '') {
            $kirf_product_all_metals_gallery[$metal_attr] =
                array_values(array_unique($kirf_product_all_metals_gallery[$metal_attr]));
        }
        if ($shape_attr !== '') {
            $kirf_product_all_shapes_gallery[$shape_attr] =
                array_values(array_unique($kirf_product_all_shapes_gallery[$shape_attr]));
        }
        if ($metal_attr !== '' && $shape_attr !== '') {
            $kirf_product_gallery[$metal_attr][$shape_attr] =
                array_values(array_unique($kirf_product_gallery[$metal_attr][$shape_attr]));
        }

        /* ───────────────────────────  END variation processing  ────────────────────────── */
    }
}

$kirf_product_all_shapes = array_values(
    array_unique(
        array_filter($kirf_product_all_shapes, fn($s) => is_string($s) && trim($s) !== '')
    )
);

$clean_metals = array_values(
    array_unique(
        array_filter($kirf_product_all_metals, fn($m) => is_string($m) && trim($m) !== '')
    )
);

if (empty($clean_metals)) {
    $kirf_product_all_metals = [];
} else {
    // group by base metal (strip standalone “18k” or “14k”)
    $grouped = [];
    foreach ($clean_metals as $metal) {
        $base = trim(preg_replace('/\b(18k|14k)\b/i', '', $metal));
        $grouped[$base][] = $metal;
    }

    // pick 18k if present, else 14k, else fallback to first
    $kirf_product_all_metals = [];
    foreach ($grouped as $list) {
        $pick = preg_grep('/\b18k\b/i', $list) ?: preg_grep('/\b14k\b/i', $list);
        $kirf_product_all_metals[] = $pick ? reset($pick) : reset($list);
    }
}

if (empty($product_img)) {
    $product_img = esc_attr(wp_get_attachment_url($product->get_image_id())) ? esc_attr(wp_get_attachment_url($product->get_image_id())) : '';
}

// ── Gallery First-Image Extractor (use 2nd pic when available) ──
$first_image_url = '';

/* quick helpers */
$metal_matches = fn(string $metal_key, string $filter) => stripos($metal_key, $filter) !== false;
$pick_img = fn(array $imgs) => $imgs[1] ?? $imgs[0] ?? '';   // ← NEW: prefer index-1

/* 1️⃣ exact metal + shape */
if ($metal_filter_mapping && $shape_filter_mapping) {
    foreach ($kirf_product_gallery as $metal_key => $shape_arr) {
        if (
            $metal_matches($metal_key, $metal_filter_mapping)
            && !empty($shape_arr[$shape_filter_mapping])
        ) {

            $first_image_url = $pick_img($shape_arr[$shape_filter_mapping]);
            break;
        }
    }
}

/* 2️⃣ metal only */
if (!$first_image_url && $metal_filter_mapping) {
    foreach ($kirf_product_all_metals_gallery as $metal_key => $imgs) {
        if ($metal_matches($metal_key, $metal_filter_mapping) && !empty($imgs)) {
            $first_image_url = $pick_img($imgs);
            break;
        }
    }
}

/* 3️⃣ shape only */
if (
    !$first_image_url && $shape_filter_mapping
    && !empty($kirf_product_all_shapes_gallery[$shape_filter_mapping])
) {

    $first_image_url = $pick_img($kirf_product_all_shapes_gallery[$shape_filter_mapping]);
}

// fallback
if (!$first_image_url) {
    $attachment_ids = $product->get_gallery_image_ids();
    $first_image_id = null;
    $first_image_url = null;
    if (!empty($attachment_ids)) {
        $first_image_id = $attachment_ids[0];
        $first_image_url = wp_get_attachment_url($first_image_id);
    }
}


?>
<div class="prod-item" id="krfs_grid_item_<?php echo esc_attr($product->get_id()); ?>">
    <?php $href_name = str_replace(' ', '', $product->get_name()) ?>
    <div class="image-div" id="image-div<?php echo esc_attr($product->get_id()); ?>"
        data-id="<?php echo esc_attr($product->get_id()); ?>">
        <div class="krfs-360-icon">
            <?php
            $video_360 = get_post_meta($product->get_id(), '_ki_video_360', true);


            if (!empty($video_360)) { ?>

                <div class="item-360 view-360" data-bs-toggle="modal" data-bs-target="#view-360"
                    data-id="<?php echo esc_attr($product->get_id()); ?>" data-video-url="<?php echo esc_url($video_360); ?>"
                    onclick="krfs_load_360(this);">
                    <div class="item-360">
                        <img src="<?php echo esc_url(KRFSAPP_PLUGIN_DIR . '/assets/images/360-icon.svg'); ?>" alt="">
                    </div>
                </div>
            <?php } ?>
        </div>
        <a href="<?php echo esc_url(get_permalink($product->get_id())); ?>">
            <img src="<?php echo esc_attr($product_img); ?>" class="krfs_prod_item_img"
                data-default="<?php echo esc_attr($product_img); ?>"
                id="krfs_prod_item_img_<?php echo esc_attr($product->get_id()); ?>" loading="lazy">

            <?php if (isset($first_image_url) && !empty($first_image_url)) { ?>
                <img src="<?php echo esc_url($first_image_url); ?>" class="krfs_prod_item_gallery_img"
                    style="display: none;" loading="lazy">
            <?php } ?>
        </a>
    </div>

    <div class="content-div text-center" data-id="<?php echo esc_attr($product->get_id()); ?>">
        <div class="krfs_prod-item-metal">
            <?php
            $kirb_all_metal_term_slugs = is_array($kirb_all_metal_term_slugs) ? $kirb_all_metal_term_slugs : [];
            $kirf_product_gallery = is_array($kirf_product_gallery) ? $kirf_product_gallery : [];

            $current_shape = $shape_filter_mapping ?? '';

            $priority = ['white', 'rose', 'yellow', 'platinum'];

            // Sort Metals
            usort($kirf_product_all_metals, function ($a, $b) use ($priority) {
                $getPriority = function ($metal) use ($priority) {
                    foreach ($priority as $index => $keyword) {
                        if (str_contains($metal, $keyword)) {
                            return $index;
                        }
                    }
                    return count($priority); // lowest priority if no match
                };

                return $getPriority($a) <=> $getPriority($b);
            });

            $shown_metal_colors = [];

            foreach ($kirf_product_all_metals as $metal) {

                if (!in_array($metal, $kirb_all_metal_term_slugs, true)) {
                    continue;
                }

                $label = $flipped_metal_terms_array[$metal] ?? '';

                if (str_contains($label, 'white')) {
                    $icon = 'white-gold';
                } elseif (str_contains($label, 'yellow')) {
                    $icon = 'yellow-gold';
                } elseif (str_contains($label, 'rose')) {
                    $icon = 'rose-gold';
                } elseif (str_contains($label, 'platinum')) {
                    $icon = 'platinum';
                } else {
                    $icon = 'white-gold';
                }

                // Skip if this color/icon is already shown
                if (in_array($icon, $shown_metal_colors, true)) {
                    continue;
                }

                $shown_metal_colors[] = $icon;

                $img_url = '';

                if ($current_shape && isset($kirf_product_gallery[$metal][$current_shape][0])) {
                    $img_url = $kirf_product_gallery[$metal][$current_shape][0];
                } elseif (isset($kirf_product_all_metals_imgs[$metal])) {
                    $img_url = $kirf_product_all_metals_imgs[$metal];
                }
                ?>

                <div class="krfs-metal-item" data-img="<?php echo esc_attr($img_url); ?>"
                    data-metal="<?php echo esc_attr($metal); ?>" data-shape="<?php echo esc_attr($current_shape); ?>">
                    <div class="krfs-metal-item-img krfs-metal-name <?php echo esc_attr($icon); ?>"></div>
                </div>

                <?php
            }
            ?>
        </div>
        <a href="<?php echo esc_url(get_permalink($product->get_id())); ?>">
            <?php
            // Split the title into words
            // $titleWords = explode(' ', $product->get_name());
            // Iterate over each word and translate if possible
            // foreach ($titleWords as &$word) {
            //     $translatedWord = __($word, 'krfs_translations');
            //     if ($translatedWord !== $word) {
            //         $word = $translatedWord;
            //     }
            // }
            // $translatedTitle = implode(' ', $titleWords);
            ?>
            <?php echo esc_html($product->get_name()); ?>
        </a>
        <div class="price">
            <?php
            $product_id = $product->get_id();
            ?>
            <span
                class="<?php echo esc_attr($product_id); ?>-prices <?php echo esc_attr($product_id); ?>-default-price"><?php echo esc_html(krfsapp_format_price($price)); ?></span> 
            <?php
            // foreach ($variant_prices as $variant_type => $variant_price) {
            //     $formatted_price = esc_html(krfsapp_format_price($variant_price)); 
            //     echo "<span class=\"" . esc_html($product_id) . "-prices " . esc_html($product_id) . "-" . esc_html($variant_type) . "\" style=\"display: none;\">" . esc_html($formatted_price) . "</span>";
            // }

            $regular_price = $product->get_regular_price();
            $sale_price = $product->get_sale_price();

            if ($regular_price > $sale_price) {
                echo '<span><del>' . esc_html(krfsapp_format_price($price)) . '</del></span>'; 
            }
            ?>
        </div>
    </div>
</div>
