<?php
/**
 * Flex @package Helix Framework
 * @author Aplikko http://www.aplikko.com
 * @copyright Copyright (c) 2025 Aplikko
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Router\Route;

class VirtueMartCustomFieldRenderer {

	// Add this helper method to wrap selects with width control
	static function renderSelectWithWidth($selectHtml, $customClass = '') {
		//  d-block mx-auto mx-md-0 gets it in the middle (center)
        $wrapperClass = 'vm-select-wrapper col-9 col-sm-12 col-lg-9 col-xl-7 ' . $customClass;
        return '<div class="' . $wrapperClass . '">' . $selectHtml . '</div>';
    }

    static function renderCustomfieldsFE(&$product,&$customfields,$virtuemart_category_id){

        static $calculator = false;
        if(!$calculator){
            $calculator = calculationHelper::getInstance ();
        }

        $selectList = array();

        $dynChilds = 1;

        static $currency = false;
        if(!$currency){
            $currency = CurrencyDisplay::getInstance ();
        }

        foreach($customfields as $key => $customfield){

            if(!isset($customfield->display))$customfield->display = '';

            $calculator->_product = $product;

            if ($customfield->field_type == "E") {

                vDispatcher::importVMPlugins ('vmcustom');
                $ret = vDispatcher::trigger ('plgVmOnDisplayProductFEVM3', array(&$product, &$customfields[$key]));
                continue;
            }

            $fieldname = 'field['.$product->virtuemart_product_id.'][' . $customfield->virtuemart_customfield_id . '][customfield_value]';
            $customProductDataName = 'customProductData['.$product->virtuemart_product_id.']['.$customfield->virtuemart_custom_id.']';

            //This is a kind of fallback, setting default of custom if there is no value of the productcustom
            $customfield->customfield_value = (!isset($customfield->customfield_value) or $customfield->customfield_value==='') ? $customfield->custom_value : $customfield->customfield_value;

            $type = $customfield->field_type;

            $idTag = 'customProductData_'.(int)$product->virtuemart_product_id.'_'.$customfield->virtuemart_customfield_id;
            $idTag = VmHtml::ensureUniqueId($idTag);

            $emptyOption = new stdClass();
            $emptyOption->text = vmText::_ ('COM_VIRTUEMART_ADDTOCART_CHOOSE_VARIANT');
            $emptyOption->value = 0;
            switch ($type) {

                case 'C':
                    $html = '';

                    $dropdowns = array();

                    if(isset($customfield->options->{$product->virtuemart_product_id})){
                        $productSelection = $customfield->options->{$product->virtuemart_product_id};
                    } else {
                        $productSelection = false;
                    }

                    $stockhandle = VmConfig::get('stockhandle_products', false) && $product->product_stockhandle ? $product->product_stockhandle : VmConfig::get('stockhandle','none');
                    $extra = ' and ( published = "1" ';
                    if($stockhandle == 'disableit_children'){
                        $extra .= ' AND (`product_in_stock` - `product_ordered`) > "0" ';
                    }
                    $extra .= ')';

                    $productModel = VmModel::getModel ('product');
                    $avail = $productModel->getProductChildIds($customfield->virtuemart_product_id, $extra);
                    if(!in_array($customfield->virtuemart_product_id,$avail)){
                        array_unshift($avail,$customfield->virtuemart_product_id);
                    }

                    foreach($customfield->options as $product_id=>$variants){
                        static $counter = 0;
                        if(!in_array($product_id,$avail)){
                            vmdebug('$customfield->options Product to ignore, continue ',$product_id);
                            continue;
                        }

                        foreach($variants as $k => $variant){

                            if(!isset($dropdowns[$k]) or !is_array($dropdowns[$k])) $dropdowns[$k] = array();
                            if(!in_array($variant,$dropdowns[$k])  ){

                                if($k==0 or !$productSelection){
                                    $dropdowns[$k][] = $variant;
                                } else{
                                    if($productSelection[$k-1] == $variants[$k-1]) {
                                        $break = false;
                                        for( $h = 1; $h<=$k; $h++ ) {
                                            if($productSelection[$h - 1] != $variants[$h - 1]) {
                                                $break = true;
                                            }
                                        }
                                        if(!$break) {
                                            $dropdowns[$k][] = $variant;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Flex 4.3: We have to disable "Chosen" JS in Joomla 6
                    //$class = 'vm-chzn-select';
                    $class = 'form-select form-select-sm vm-custom-select ps-4 ps-sm-2 ps-md-2 ps-lg-3 pe-5 pe-sm-2 pe-md-3 pe-lg-4 pt-1';
                    $selectType = 'select.genericlist';

                    if(!empty($customfield->selectType)){
                        $selectType = 'select.radiolist';
                        $class = '';
                        $dom = '';
                        //$idTagK = VmHtml::ensureUniqueId($idTag.'cvard'.$k);
                    } else {
                        // Important fix in Flex 4.3 for radios in Category view. We have to disable "Chosen" JS in Joomla 6
                        //vmJsApi::chosenDropDowns();
                        $dom = 'select';
                        //$idTagK = '[';	//Joomla workaround to get a list without id
                    }
            
                    // Not working without "Chosen" JS, which is not compatible with Joomla 6
                    // $attribs = array('class'=>$class.' cvselection no-vm-bind form-radio','style'=>'min-width:50%;');
                    // added role="button"
					$attribs = array('class'=>$class, 'role'=>'button');

                    $view = 'productdetails';
                    $attribs['data-reload'] = '1';
                    $view = $viewJs = vRequest::getCmd('view','productdetails');

                    if(VmConfig::get ('jdynupdate', TRUE)){

                        if($view == 'productdetails' or ($customfield->browseajax and $view == 'category')){
                            $attribs['data-dynamic-update'] = '1';
                            unset($attribs['data-reload']);
                        } else {
                            $viewJs = 'productdetails';
                        }
                    }

                    $Itemid = vRequest::getInt('Itemid',''); // '&Itemid=127';
                    if(!empty($Itemid)){
                        $Itemid = '&Itemid='.$Itemid;
                    }

                    //create array for js
                    $jsArray = array();

                    $url = '';

                    if($view == 'productdetails' and $customfield->withImage){
                        $withImage = true;
                        $mediaM = VmModel::getModel('media');
                        $tablePM = $mediaM->getTable('product_medias');
                        //$html .= '<div class="child-Image-Container">';
                        // major_color_bckg-80 
                        $html .= '<div class="d-flex mb-3 w-100">';
                    } else {
                        $withImage = false;
                    }
					foreach($customfield->options as $prodId => $variants){

						if(!in_array($prodId,$avail)){continue;}

						$url = Route::_('index.php?option=com_virtuemart&view='.$viewJs.'&virtuemart_category_id=' . $virtuemart_category_id . '&virtuemart_product_id='.$prodId.$Itemid,false);
						$jsArray[] = '["'.$url.'","'.implode('","',$variants).'"]';
						if($withImage){

							if($prodId == $product->virtuemart_product_id) continue;

							/*
							$images = $tablePM->load($prodId);

							if(!isset($images[0]) and isset($product->virtuemart_media_id[0])){
								$images[0] = $product->virtuemart_media_id[0];  //If the image is missing, the parent has it
							}
							*/
							// New Flex 4.3 Fix for Joomla 6
							$images = $tablePM->load($prodId);

							// Ensure $images is always an array
							if (!is_array($images) && !is_object($images)) {
								$images = array();
							}

							if(!isset($images[0]) and isset($product->virtuemart_media_id[0])){
								$images[0] = $product->virtuemart_media_id[0];  //If the image is missing, the parent has it
							}
							
							if(isset($images[0])){
								$media = $mediaM->createMediaByIds($images[0]);
								$html .= '<div class="floatleft">';
								// Thumbnail images for custom fields
								$html .= '<a class="d-flex border rounded-1 me-2" style="max-width:80px;height:auto;" title="'.implode('","',$variants).'" data-toggle="tooltip" href="'.$url.'" >'. $media[0]->displayMediaThumb(array ('class' => 'child-Images rounded-1'), false, '', true, false, false, VmConfig::get('img_width',50), VmConfig::get('img_height',90)) .'</a>';
								$html .= '</div>';
							}
						}
					}

                    if($view == 'productdetails' and $customfield->withImage){
                        $html .= '</div>';
                    }
                    foreach($customfield->selectoptions as $k => $soption){

                        $html .= '<div class="custom_field_C_container">';
                        $options = array();
                        $selected = false;
                        $idTagK = VmHtml::ensureUniqueId($idTag);

                        if(isset($dropdowns[$k])){
                            foreach($dropdowns[$k] as $i=> $elem){

                                $elem = trim((string)$elem);
                                $text = $elem;
                                
                                // Flex 3.9.9 fix for Radios
                                if(isset($customfield->selectType)){
                                    if(empty($customfield->selectType)){
                                        // If custom field is "Select"
                                        $text = vmText::_($elem);
                                    } else {
                                        // If custom field is "Radio"
                                        $text = '<span class="checker">'. vmText::_($elem) .'</span>';
                                    }
                                }
                                
                                if($soption->clabel!='' and in_array($soption->voption,VirtueMartModelCustomfields::$dimensions) ){
                                    $rd = $soption->clabel;
                                    if(is_numeric($rd) and is_numeric($elem)){
                                        $text = number_format(round((float)$elem,(int)$rd),$rd);
                                    } 
                                } 

                                // Flex 3.9.9 fix for Radios
                                if(empty($elem)){
                                    if(empty($customfield->selectType)){
                                        // If custom field is "Select"
                                        $text = vmText::_('COM_VIRTUEMART_LIST_EMPTY_OPTION');
                                    } else {
                                        // If custom field is "Radio"
                                        $text = '<span class="checker-select">'. vmText::_('COM_VIRTUEMART_LIST_EMPTY_OPTION') .'</span>';
                                    }
                                }
                                
                                $o = new stdClass();
                                $o->value = $elem;
                                $o->text = $text;
                                $o->id = VmHtml::ensureUniqueId($idTagK.'-'.$i);
                                $options[] = $o;

                                if($productSelection and $productSelection[$k] == $elem){
                                    $selected = $elem;
                                }
                            }
                        }

                        if(empty($selected)){
                            $product->orderable=false;
                        }

                        if($customfield->showlabels){
                            if( in_array($soption->voption,VirtueMartModelCustomfields::$dimensions) ){
                                $soption->slabel = vmText::_('COM_VIRTUEMART_'.strtoupper($soption->voption));
                            } else if(!empty($soption->clabel) and !in_array($soption->voption,VirtueMartModelCustomfields::$dimensions) ){
                                $soption->slabel = vmText::_($soption->clabel);
                            }
                            if(isset($soption->slabel)){
                                $html .= '<span class="vm-cmv-label" >'.$soption->slabel.'</span>';
                            }
                        }

                        $attribs['data-cvsel'] = 'field' . $customfield->virtuemart_customfield_id ;
                        $fname = $fieldname.'['.$k.']';

                        $selectHtml = HTMLHelper::_($selectType, $options, $fname, $attribs, "value", "text", $selected, $idTagK);
                        
                        // Wrap select with width control if it's a dropdown (not radio)
                        if (empty($customfield->selectType)) {
                            $html .= self::renderSelectWithWidth($selectHtml, 'vm-custom-field-select');
                        } else {
                            $html .= $selectHtml;
                        }
                        
                        $html .= '</div>';
                    }

                    vmJsApi::addJScript('cvfind');

                    $BrowserNewState =  '';
                    if($view != 'productdetails'){
                        $BrowserNewState = 'Virtuemart.setBrowserState = false;';
                    }

                    $jsVariants = implode(',',$jsArray);

                    $selector = $dom."[data-cvsel=\"".$attribs['data-cvsel']."\"]";
                    $hash = md5($selector);
                    // Disabled in Flex 3.9.9 --- $j = "function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}r(function(){
                    $j = "jQuery(document).ready(function($) {
                            ".$BrowserNewState."
                            $('".$selector."').off('change',Virtuemart.cvFind);
                            $('".$selector."').on('change', { variants:[".$jsVariants."] },Virtuemart.cvFind);
                        });";
                    vmJsApi::addJScript('cvselvars'.$hash,$j,true,false,false,$hash);

                    //Now we need just the JS to reload the correct product
                    $customfield->display = $html;

                    break;

                case 'A':

                    $html = '';

                    $productModel = VmModel::getModel ('product');

                    //Note by Jeremy Magne (Daycounts) 2013-08-31
                    //Previously the the product model is loaded but we need to ensure the correct product id is set because the getUncategorizedChildren does not get the product id as parameter.
                    //In case the product model was previously loaded, by a related product for example, this would generate wrong uncategorized children list
                    $productModel->setId($customfield->virtuemart_product_id);

                    $uncatChildren = $productModel->getUncategorizedChildren ($customfield->withParent);

                    $options = array();

                    $selected = vRequest::getInt ('virtuemart_product_id',0);
                    $selectedFound = false;

                    $view = 'productdetails';
                    $attribs['data-reload'] = '1';
                    if(VmConfig::get ('jdynupdate', TRUE)){
                        $attribs['url'] = 'value';
                        $view = vRequest::getCmd('view','productdetails');
                        if($view == 'productdetails' or ($customfield->browseajax and $view == 'category')){
                            $attribs['data-dynamic-update'] = '1';
                            unset($attribs['data-reload']);
                        } else {
                            $view = 'productdetails';
                        }
                    }

                    $Itemid = vRequest::getInt('Itemid',''); // '&Itemid=127';
                    if(!empty($Itemid)){
                        $Itemid = '&Itemid='.$Itemid;
                    }

                    if(!$customfield->withParent){
                        $options[0] = $emptyOption;
                        $options[0]->value = Route::_ ('index.php?option=com_virtuemart&view='.$view.'&virtuemart_category_id=' . $virtuemart_category_id . '&virtuemart_product_id=' . $customfield->virtuemart_product_id,FALSE);
                        //$options[0] = array('value' => Route::_ ('index.php?option=com_virtuemart&view=productdetails&virtuemart_category_id=' . $virtuemart_category_id . '&virtuemart_product_id=' . $customfield->virtuemart_product_id,FALSE), 'text' => vmText::_ ('COM_VIRTUEMART_ADDTOCART_CHOOSE_VARIANT'));
                    }

                    $parentStock = 0;
                    if($uncatChildren){
                        foreach ($uncatChildren as $k => $child) {
                            /*if(!isset($child[$customfield->customfield_value])){
                                vmdebug('The child has no value at index '.$customfield->customfield_value,$customfield,$child);
                            } else {*/

                            $productChild = $productModel->getProduct((int)$child,true);

                            if(!$productChild) continue;
                            if(!isset($productChild->{$customfield->customfield_value})){
                                vmdebug('The child has no value at index '.$child);
                                continue;
                            }
                            $available = $productChild->product_in_stock - $productChild->product_ordered;
                            if(VmConfig::get('stockhandle','none')=='disableit_children' and $available <= 0){
                                continue;
                            }
                            $parentStock += $available;
                            $priceStr = '';
                            if($customfield->wPrice){
                                //$product = $productModel->getProductSingle((int)$child['virtuemart_product_id'],false);
                                $productPrices = $calculator->getProductPrices ($productChild);
                                $priceStr =  ' (' . $currency->priceDisplay ($productPrices['salesPrice']) . ')';
                            }
                            $options[] = array('value' => Route::_ ('index.php?option=com_virtuemart&view='.$view.'&virtuemart_category_id=' . $virtuemart_category_id . '&virtuemart_product_id=' . $productChild->virtuemart_product_id,false), 'text' => $productChild->{$customfield->customfield_value}.$priceStr);

                            if($selected==$child){
                                $selectedFound = true;
                                vmdebug($customfield->virtuemart_product_id.' $selectedFound by vRequest '.$selected);
                            }
                            //vmdebug('$child productId ',$child['virtuemart_product_id'],$customfield->customfield_value,$child);
                            //}
                        }
                    }

                    if(!$selectedFound){
                        $pos = array_search($customfield->virtuemart_product_id, $product->allIds);
                        if(isset($product->allIds[$pos-1])){
                            $selected = $product->allIds[$pos-1];
                            //vmdebug($customfield->virtuemart_product_id.' Set selected to - 1 allIds['.($pos-1).'] = '.$selected.' and count '.$dynChilds);
                            //break;
                        } elseif(isset($product->allIds[$pos])){
                            $selected = $product->allIds[$pos];
                            //vmdebug($customfield->virtuemart_product_id.' Set selected to allIds['.$pos.'] = '.$selected.' and count '.$dynChilds);
                        } else {
                            $selected = $customfield->virtuemart_product_id;
                            //vmdebug($customfield->virtuemart_product_id.' Set selected to $customfield->virtuemart_product_id ',$selected,$product->allIds);
                        }
                    }

                    $url = 'index.php?option=com_virtuemart&view='.$view.'&virtuemart_category_id='.
                    $virtuemart_category_id .'&virtuemart_product_id='. $selected;
                    $attribs['option.key.toHtml'] = false;
                    $attribs['id'] = '[';//$idTag;

                    $och = '';
                    if(!empty($attribs['data-reload'])){
                        $och = ' onchange="window.top.location.href=this.options[this.selectedIndex].value" data-reload=1';
                        unset($attribs['data-reload']);
                    } else {
                        $och = ' data-dynamic-update="1" url="value"';
                        unset($attribs['data-dynamic-update']);
                    }

					// Added role="button"
					$attribs['list.attr'] = 'size="1" class="form-select form-select-sm vm-custom-select no-vm-bind avselection" role="button"'.$och;
					
                    $attribs['list.translate'] = false;
                    $attribs['option.key'] = 'value';
                    $attribs['option.text'] = 'text';
                    $attribs['list.select'] = Route::_ ($url,false);

                    $selectHtml = HTMLHelper::_ ('select.genericlist', $options, $fieldname, $attribs);
                    $html .= self::renderSelectWithWidth($selectHtml, 'vm-advanced-select');

                    // Important fix in Flex 4.3 for radios in Category view. We have to disable "Chosen" JS in Joomla 6
                    //vmJsApi::chosenDropDowns();

                    if($customfield->parentOrderable==0){
                        if($product->virtuemart_product_id==$customfield->virtuemart_product_id){
                            $product->orderable = false;
                            $product->product_in_stock = $parentStock;
                        }
                    }

                    $dynChilds++;
                    $customfield->display = $html;

                    vmJsApi::addJScript('cvfind');

                    $BrowserNewState =  '';
                    if($view != 'productdetails'){
                        $BrowserNewState = 'Virtuemart.setBrowserState = false;';
                    }

                    break;
                
                case 'B':
                case 'S':
                case 'M':
                case 'PB':
                    if(VmConfig::get('hideEmptyCustomfields',false) and empty($customfield->customfield_value)) break;
                    //vmdebug('Example for params ',$customfield);
                    if(isset($customfield->selectType)){
                        if(empty($customfield->selectType)){
                            $selectType = 'select.genericlist';
                            if(!empty($customfield->is_input)){
                                // Important fix in Flex 4.3 for radios in Category view. We have to disable "Chosen" JS in Joomla 6
                                //vmJsApi::chosenDropDowns();
                                //$class = 'class="vm-chzn-select"';
                                $class = 'form-select form-select-sm vm-custom-select';
                                $idTag = '[';
                            }
                        } else {
                            $selectType = 'select.radiolist';
                            $class = '';
                        }
                    } else {
                        if($type== 'M'){
                            $selectType = 'select.radiolist';
                            $class = '';
                        } else {
                            $selectType = 'select.genericlist';
                            if(!empty($customfield->is_input)){
                                // Important fix in Flex 4.3 for radios in Category view. We have to disable "Chosen" JS in Joomla 6
                                //vmJsApi::chosenDropDowns();
                                //$class = 'class="vm-chzn-select"';
                                $class = 'form-select form-select-sm vm-custom-select';
                                $idTag = '[';
                            }
                        }
                    }

                    if($customfield->is_list and $customfield->is_list!=2){

                        if(!empty($customfield->is_input)){

                            $options = array();

                            if($customfield->addEmpty){
                                $options[0] = $emptyOption;
                            }

                            $values = explode (';', $customfield->custom_value);

                            foreach ($values as $val) {

                                //if($val == 0 and $customfield->addEmpty){
                                    //continue;
                                //}
                                if($type == 'M'){
                                    $tmp = array('value' => $val, 'text' => VirtueMartModelCustomfields::displayCustomMedia ($val,'product',$customfield->width,$customfield->height));
                                } else {
                                    $tmp = array('value' => $val, 'text' => vmText::_($val));
                                }
                                $options[] = (object)$tmp;
                            }
                            $currentValue = $customfield->customfield_value;

                            $selectHtml = HTMLHelper::_ ($selectType, $options, $customProductDataName.'[' . $customfield->virtuemart_customfield_id . ']', $class, 'value', 'text', $currentValue,$idTag);
                            
                            // Wrap select with width control
                            if ($selectType == 'select.genericlist') {
                                $customfield->display = self::renderSelectWithWidth($selectHtml, 'vm-standard-select');
                            } else {
                                $customfield->display = $selectHtml;
                            }
                        } else {
                            if($type == 'M'){
                                $customfield->display =  VirtueMartModelCustomfields::displayCustomMedia ($customfield->customfield_value,'product',$customfield->width,$customfield->height);
                            } else {
                                $customfield->display =  vmText::_ ($customfield->customfield_value);
                            }
                        }
                    } else {

                        if(!empty($customfield->is_input)){

                            if(!isset($selectList[$customfield->virtuemart_custom_id])) {
                                $selectList[$customfield->virtuemart_custom_id] = $key;
                                if($customfield->addEmpty){
                                    if(empty($customfields[$selectList[$customfield->virtuemart_custom_id]]->options)){
                                        $customfields[$selectList[$customfield->virtuemart_custom_id]]->options[0] = $emptyOption;
                                        $customfields[$selectList[$customfield->virtuemart_custom_id]]->options[0]->virtuemart_customfield_id = $emptyOption->value;
                                        //$customfields[$selectList[$customfield->virtuemart_custom_id]]->options['nix'] = array('virtuemart_customfield_id' => 'none', 'text' => vmText::_ ('COM_VIRTUEMART_ADDTOCART_CHOOSE_VARIANT'));
                                    }
                                }

                                $tmpField = clone($customfield);
                                $tmpField->options = null;
                                $customfield->options[$customfield->virtuemart_customfield_id] = $tmpField;

                                $customfield->customProductDataName = $customProductDataName;

                            } else {
                                $customfields[$selectList[$customfield->virtuemart_custom_id]]->options[$customfield->virtuemart_customfield_id] = $customfield;
                                unset($customfields[$key]);

                            }

                            if (isset($customfields[$selectList[$customfield->virtuemart_custom_id]])) {
                                $default = reset($customfields[$selectList[$customfield->virtuemart_custom_id]]->options);//vmdebug('list with empty option',$default, $customfields[$selectList[$customfield->virtuemart_custom_id]]->options);
                            }
                            else {
                                $customfields[$selectList[$customfield->virtuemart_custom_id]] = new stdClass();
                                $customfields[$selectList[$customfield->virtuemart_custom_id]]->options = array();
                                $default = new stdClass();
                            }
                            if(!isset($default->customfield_value)){
                                $default->customfield_value = '';
                            }
                            foreach ($customfields[$selectList[$customfield->virtuemart_custom_id]]->options as $k => $productCustom) {
                                if($k == 0){
                                    //$productCustom->text =

                                } else {
                                    if(!isset($productCustom->customfield_price)) $productCustom->customfield_price = 0.0;
                                    if(!isset($productCustom->customfield_value)) $productCustom->customfield_value = '';
                                    $price = VirtueMartModelCustomfields::renderCustomfieldPrice($productCustom, $product, $calculator);

                                        
                                    if($type == 'M'){
                                        $productCustom->text = VirtueMartModelCustomfields::displayCustomMedia ($productCustom->customfield_value,'product',$customfield->width,$customfield->height).' '.$price;
                                    } else if($type == 'PB') {
                                        $productB = VmModel::getModel('product')->getProduct($productCustom->bundle_product_id);
                                        $productCustom->text = $productB->product_name . ' ' . $price;
                                    } else {
                                        $trValue = vmText::_($productCustom->customfield_value);
                                        
                                        // Flex 3.9.9 fix for Radios
                                        if(isset($customfield->selectType)){
                                            if(empty($customfield->selectType)){
                                                // If custom field is "Select"
                                                $trValue .= '';
                                            } else {
                                                // If custom field is "Radio"
                                                $trValue .= '<span class="checker">';
                                            }
                                        } 
                                        
                                        if($productCustom->customfield_value!=$trValue and strpos($trValue,'%1')!==false){
                                            $productCustom->text = vmText::sprintf($productCustom->customfield_value,$price);
                                        } else {
                                            $productCustom->text = $trValue.' '.$price;
                                        }
                                        
                                        // Flex 3.9.9 fix for Radios
                                        if(isset($customfield->selectType)){
                                            if(empty($customfield->selectType)){
                                                // If custom field is "Select"
                                                $trValue .= '';
                                            } else {
                                                // If custom field is "Radio"
                                                $trValue .= '</span>';
                                            }
                                        } 
                                        
                                    }

                                }
                                $customfields[$selectList[$customfield->virtuemart_custom_id]]->options[$k] = $productCustom;

                            }

                            $selectHtml = HTMLHelper::_ ($selectType, $customfields[$selectList[$customfield->virtuemart_custom_id]]->options,
                            $customfields[$selectList[$customfield->virtuemart_custom_id]]->customProductDataName,
                            $class, 'virtuemart_customfield_id', 'text', $default->customfield_value,$idTag);
                            
                            // Wrap select with width control
                            if ($selectType == 'select.genericlist') {
                                $customfields[$selectList[$customfield->virtuemart_custom_id]]->display = self::renderSelectWithWidth($selectHtml, 'vm-grouped-select');
                            } else {
                                $customfields[$selectList[$customfield->virtuemart_custom_id]]->display = $selectHtml;
                            }
                        } else {
                            if($type == 'M'){
                                $customfield->display = VirtueMartModelCustomfields::displayCustomMedia ($customfield->customfield_value,'product',$customfield->width,$customfield->height);
                            } else {
                                $customfield->display = vmText::_ ($customfield->customfield_value);
                            }
                        }
                    }

                    break;

                // ... Rest of your cases (D, X, Y, P, Z, RC, R) remain unchanged
                
                // Add the remaining cases here (they don't contain selects)
            }

            $viewData['customfields'][$key] = $customfield;
            //vmdebug('my customfields '.$type,$viewData['customfields'][$k]->display);
        }
    }

	static function renderRelatedProduct($customfield,$related){


		$thumb = '';
		if($customfield->wImage) {
			if(!empty( $related->virtuemart_media_id[0] )) {
				$thumb = VirtueMartModelCustomfields::displayCustomMedia( $related->virtuemart_media_id[0], 'product', $customfield->width, $customfield->height ).' ';
			} else {
				$thumb = VirtueMartModelCustomfields::displayCustomMedia( 0, 'product', $customfield->width, $customfield->height ).' ';
			}
		}

		if($customfield->waddtocart){
			if (!empty($related->customfields)) {

				$customfieldsModel = VmModel::getModel ('customfields');
				if(empty($customfield->from)) {
					$customfield->from = $related->virtuemart_product_id;
					$customfieldsModel -> displayProductCustomfieldFE ($related, $related->customfields);
				} else if($customfield->from!=$related->virtuemart_product_id){
					$customfieldsModel -> displayProductCustomfieldFE ($related, $related->customfields);
				}

			}
			$isCustomVariant = false;
			if (!empty($related->customfields)) {
				foreach ($related->customfields as $k => $custom) {
					if($custom->field_type == 'C' and $custom->virtuemart_product_id != (int)$customfield->customfield_value){
						$isCustomVariant = $custom;
					}
					if (!empty($custom->layout_pos)) {
						$related->customfieldsSorted[$custom->layout_pos][] = $custom;
					} else {
						$related->customfieldsSorted['normal'][] = $custom;
					}
					unset($related->customfields);
				}

			}
		}

		return shopFunctionsF::renderVmSubLayout('related',array('customfield'=>$customfield,'related'=>$related, 'thumb'=>$thumb));


	}

	static function renderCustomfieldsCart($product, $html, $trigger){
		if(isset($product->param)){
			vmTrace('param found, seek and destroy');
			return false;
		}
		$row = 0;

		$variantmods = isset($product -> customProductData)?$product -> customProductData:$product -> product_attribute;

		if(!is_array($variantmods)){
			$variantmods = json_decode($variantmods,true);
		}

		//We let that here as Fallback
		if(empty($product->customfields)){

			$productDB = VmModel::getModel('product')->getProduct($product->virtuemart_product_id);
			if($productDB and !empty($productDB->customfields)){

				$product->customfields = $productDB->customfields;
			} else {
				$product->customfields = array();
			}
		}
		//vmdebug('renderCustomfieldsCart $variantmods',$variantmods);
		$productCustoms = array();
		foreach( (array)$product->customfields as $prodcustom){

			//We just add the customfields to be shown in the cart to the variantmods
			if(is_object($prodcustom)){

				//We need this here to ensure that broken customdata of order items is shown updated info, or at least displayed,
				if($prodcustom->is_cart_attribute or $prodcustom->is_input){

					//The problem here is that a normal value and an array can be valid. The function should complement, or update the product. So we are not allowed
					//to override existing values. When the $variantmods array is not set for the key, then we add an array, when the customproto is used more than one time
					if(!isset($variantmods[$prodcustom->virtuemart_custom_id])){
						$variantmods[$prodcustom->virtuemart_custom_id][$prodcustom->virtuemart_customfield_id] = $prodcustom->virtuemart_customfield_id;
					}
					//the missing values are added with an own key.
					if( is_array($variantmods[$prodcustom->virtuemart_custom_id]) and
						!isset($variantmods[$prodcustom->virtuemart_custom_id][$prodcustom->virtuemart_customfield_id]) ){

						$variantmods[$prodcustom->virtuemart_custom_id][$prodcustom->virtuemart_customfield_id] = $prodcustom->virtuemart_customfield_id;
					}
				}

				$productCustoms[$prodcustom->virtuemart_customfield_id] = $prodcustom;
			}
		}

		foreach ( (array)$variantmods as $i => $customfield_ids) {

			if(!is_array($customfield_ids)){
				$customfield_ids = array( $customfield_ids =>false);
			}

			foreach($customfield_ids as $customfield_id=>$params){

				if(empty($productCustoms) or !isset($productCustoms[$customfield_id])){
					//vmdebug('displayProductCustomfieldSelected continue',$customfield_id,$productCustoms);
					continue;
				}
				$productCustom = $productCustoms[$customfield_id];
				//vmdebug('displayProductCustomfieldSelected ',$customfield_id,$productCustom);
				//The stored result in vm2.0.14 looks like this {"48":{"textinput":{"comment":"test"}}}
				//and now {"32":[{"invala":"100"}]}
				if (!empty($productCustom)) {
					$otag = ' <span class="product-field-type-' . $productCustom->field_type . ' mb-0 pb-0">';
					$tmp = '';
					if ($productCustom->field_type == "E") {

						vDispatcher::importVMPlugins ('vmcustom');
						vDispatcher::trigger ($trigger.'VM3', array(&$product, &$productCustom, &$tmp));
					}
					else {
						$value = '';

						if (($productCustom->field_type == 'G')) {
							$db = Factory::getDBO ();
							$db->setQuery ('SELECT  `product_name` FROM `#__virtuemart_products_' . VmConfig::$vmlang . '` WHERE virtuemart_product_id=' . (int)$productCustom->customfield_value);
							$child = $db->loadObject ();
							$value = $child->product_name;
						}
						elseif (($productCustom->field_type == 'M')) {
							$customFieldModel = VmModel::getModel('customfields');
							$value = $customFieldModel->displayCustomMedia ($productCustom->customfield_value,'product',$productCustom->width,$productCustom->height,VirtueMartModelCustomfields::$useAbsUrls);
						}
						elseif (($productCustom->field_type == 'S')) {

							if($productCustom->is_list and $productCustom->is_input){
								if($productCustom->is_list==2){
									$value = vmText::_($productCustom->customfield_value);
								} else {
									$value = vmText::_($params);
								}

							} else {
								$value = vmText::_($productCustom->customfield_value);
							}
						}
						elseif (($productCustom->field_type == 'PB')) {
							///vmdebug('$productCustom->customfield_value',$productCustom);
							$productDB = VmModel::getModel('product')->getProduct($productCustom->bundle_product_id);
							//my suggestion, we could even add the price here
							$value = $productDB->product_name. ' ('.$productDB->product_sku .') - '.$productDB->virtuemart_product_id;
						}
						elseif (($productCustom->field_type == 'A')) {
							if(!property_exists($product,$productCustom->customfield_value)){
								$productDB = VmModel::getModel('product')->getProduct($product->virtuemart_product_id);
								if($productDB){
									$attr = $productCustom->customfield_value;
									$product->{$attr} = $productDB->{$attr};
								}
							}
							$value = vmText::_( $product->{$productCustom->customfield_value} );
						}
						elseif (($productCustom->field_type == 'C')) {

							foreach($productCustom->options->{$product->virtuemart_product_id} as $k=>$option){
								$value .= '<hr class="border border-top-0 border-dark border-opacity-25 d-block w-100 clearfix mt-2 mb-1" /><span style="color:#999;font-size:85%;">';
								if(!empty($productCustom->selectoptions[$k]->clabel) and in_array($productCustom->selectoptions[$k]->voption,VirtueMartModelCustomfields::$dimensions)){
									$value .= vmText::_('COM_VIRTUEMART_'.$productCustom->selectoptions[$k]->voption);
									$rd = $productCustom->selectoptions[$k]->clabel;
									if(is_numeric($rd) and is_numeric($option)){
										$value .= ' '.number_format(round((float)$option,(int)$rd),$rd);
									}
								} else {
									if(!empty($productCustom->selectoptions[$k]->clabel)) $value .= vmText::_($productCustom->selectoptions[$k]->clabel);
									$value .= ' <strong style="color:#333;font-size:110%;" class="d-block w-100 clearfix mb-3">'.vmText::_($option).'</strong> ';
								}
								$value .= '</span>';
							}
							$value = trim($value);
							if(!empty($value)){
								$html .= $otag.$value.'</span>';
							}

							continue;
						}
						elseif (($productCustom->field_type == 'D')) {
							//vmdebug('my date product customfield',$productCustom);
							if($productCustom->is_input){
								$value = $params;
							} else {
								$value = $productCustom->customfield_value;
							}

						}
						else {
							$value = vmText::_($productCustom->customfield_value);
						}
						$trTitle = vmText::_($productCustom->custom_title);
						$tmp = '';

						if($productCustom->custom_title!=$trTitle and strpos($trTitle,'%1')!==false){
							$tmp .= vmText::sprintf($productCustom->custom_title,$value);
						} else {
							$tmp .= $trTitle.' '.$value;
						}
					}
					if(!empty($tmp)){
						$html .= $otag.$tmp.'</span><br />';
					}


				}
				else {
					foreach ((array)$customfield_id as $key => $value) {
						$html .= '<br/ >Couldnt find customfield' . ($key ? '<span>' . $key . ' </span>' : '') . $value;
					}
					vmdebug ('customFieldDisplay, $productCustom is EMPTY '.$customfield_id);
				}
			}

		}

		return $html . '</div>';
	}
}

