<?php
/**
 * 2022 Anvanto
 *
 * NOTICE OF LICENSE
 *
 * This file is not open source! Each license that you purchased is only available for 1 wesite only.
 * If you want to use this file on more websites (or projects), you need to purchase additional licenses. 
 * You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
 *
 *  @author Anvanto <anvantoco@gmail.com>
 *  @copyright  2022 Anvanto
 *  @license    Valid for 1 website (or project) for each purchase of license
 *  International Registered Trademark & Property of Anvanto
 */

 if (!defined('_PS_VERSION_')) {
    exit;
}

use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;

class anProductAttr 
{
    public static function getProductImages($product, $context)
    {
        $imageRetriever = new ImageRetriever($context->link);
        return $imageRetriever->getProductImages($product, $context->language);
    }  
    
    public static function getProductCover($productImages)
    {
        foreach ($productImages as $image){
            if ($image['cover']){
                return $image;
            }
        }
        return false;
    }



	public static function getImagesProductAttribute($product, $productObj)
	{
        $context = Context::getContext();

        $productImages = anProductAttr::getProductImages($product, $context);
		$images = anProductAttr::filterImagesForCombination($productImages, $product['id_product_attribute']);
        $coverImage = anProductAttr::getProductCoverByImages($images, $productObj);

		$cover = array_merge($coverImage, [
                    'legend' => $coverImage['legend'],
                ]); 		
        $ppp['images'] = $images;
        $ppp['cover'] = $cover;
		
		return $ppp;	 
	}

    public static function getProductCoverByImages($productImages, $productObj)
    {
        $imageRetriever = new ImageRetriever(Context::getContext()->link);   
        return $imageRetriever->getImage($productObj, $productImages['0']['id_image']);
    }

    public static function filterImagesForCombination(array $images, int $productAttributeId)
    {
        $filteredImages = [];

        foreach ($images as $image) {
            if (in_array($productAttributeId, $image['associatedVariants'])) {
                $filteredImages[] = $image;
            }
        }

        return (0 === count($filteredImages)) ? $images : $filteredImages;
    }
}