<?php

namespace OfficeBrain\Bundle\ServiceGroupBundle\Manager\Extended;

use OfficeBrain\Bundle\ServiceGroupBundle\Manager\AbstractManager\ServiceRuleAbstract;

/**
 * @author OfficeBrain 4589 <info@officebrain.com>
 *
 * Description : Service Group Extended Class
 */
class ServiceRuleChargesCalculationExtended extends ServiceRuleAbstract
{
	protected $embroideryMethods;
    public function __construct($entityManager, $request, $session, $serviceContainer, $translatorService, $countries, $languages, $coreManager, $productTagManager, $serviceGroupAPiClient, $twigExtension)
    {
        parent::__construct($entityManager, $request, $session, $serviceContainer, $countries, $languages, $coreManager, $productTagManager, $serviceGroupAPiClient, $translatorService, $twigExtension);


        $this->conditionAry = $this->getConditionArray();
        $this->conditionMutlipleValueAry = $this->getConditionMultipleValueList();
        $this->cultureList = $this->getCultureList();

        $this->actionTypes = $this->getActionTypes();
        $this->actionLimitPer = $this->getActionLimitPer();
        $this->actionRuleTypes = $this->getActionRuleTypes();
        $this->actionChargeTypes = $this->getActionChargeTypes();
        $this->actionAmountTypes = $this->getActionAmountTypes();
        $this->actionRuleStatus = $this->getRuleStatus();

        $this->translatorService = $translatorService;

        $this->recordsPerPage = $this->projectSetting['configuration_rule']['promo_discount']['option']['rule_mapping']['option']['record_per_page'];

        $this->serviceRuleMappingRulesRepository = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingRules')
                                                    ->setProjectSetting($this->projectSetting);

        $this->serviceRuleChargesEquationRepository = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleChargesEquation');
                                                    //->setProjectSetting($this->projectSetting);
    }

    public function __destruct()
    {
        unset($this->conditionAry);
        unset($this->conditionMutlipleValueAry);
        unset($this->cultureList);
        unset($this->actionTypes);
        unset($this->actionLimitPer);
        unset($this->actionRuleTypes);
        unset($this->actionChargeTypes);
        unset($this->actionAmountTypes);
        unset($this->actionRuleStatus);
        unset($this->translatorService);
        unset($this->recordsPerPage);
        unset($this->serviceRuleMappingRulesRepository);
        unset($this->serviceRuleMappingMasterRepository);
    }


    
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getTotalPriceChargesForDetailPage
     * To get total of product price and all charges For product Detail Page
     */
    public function getAllAppliedChargesAndPriceTotal($inputDetail, $productDetail, $allCharges=array())
    {
        $totalQtySelected = 0;
        if (isset($inputDetail['shipping_method']['quantity_detail']) && is_array($inputDetail['shipping_method']['quantity_detail'])) {
            foreach ($inputDetail['shipping_method']['quantity_detail'] as $qtyCharge) {
                foreach ($qtyCharge['quantity'] as $qty) {
                    $totalQtySelected += $qty;
                }
            }
        } else {
            $totalQtySelected = isset($inputDetail['total_qty']) ? $inputDetail['total_qty'] : 0;
        }

        $apiVersion =  $this->serviceContainer->getParameter('api.available_call_to_override');

        if ($apiVersion['view_product'] == 'v2' && isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];

            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {

                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];

                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productPricing = $productImprintInformation[$imprintMethodId]['price']['pricing'];
                    
                    if(isset($inputDetail['order_type']) && $inputDetail['order_type']!='')	$priceType = $inputDetail['order_type'];
                    else $priceType = "decorative";

                    if($priceType=='decoration')	$priceType = "decorative";
                     
                    if (!isset($productPricing[$priceType]) && isset($productPricing['blank']) && !empty($productPricing['blank'])) {
                        $priceType = "blank";
                    }

                    //for infinite loop for any number of qty
                    $priceOrig =  $this->infiniteQtyLoopForQtyRate($productPricing[$priceType], $totalQtySelected);
                }
            }
        } else {
            $productPricing = $productDetail['pricing'];
            
            if(isset($inputDetail['order_type']) && $inputDetail['order_type']!='')	$priceType = $inputDetail['order_type'];
            else $priceType = "decorative";

            if($priceType=='decoration')	$priceType = "decorative";
             
            
            if (!isset($productPricing[$priceType]) && isset($productPricing['blank']) && !empty($productPricing['blank'])) {
                $priceType = "blank";
            }

            //for infinite loop for any number of qty
            $priceOrig =  $this->infiniteQtyLoopForQtyRate($productPricing[$priceType], $totalQtySelected);
        }
        
        $priceOrig = $this->TwigExtension->priceFilter($priceOrig);
        
        $totalCharge = 0;
        if (count($allCharges) > 0) {
            foreach ($allCharges as $charge) {
                $totalCharge += $charge['charges_amount'];
            }
        }
        $productTotalPrice = ($priceOrig * $totalQtySelected);
        $totalPrice = $productTotalPrice + $totalCharge;
        

        $totalPriceArray["product_price"]= $this->TwigExtension->currencyFilter($productTotalPrice);
        $totalPriceArray["product_price_js"]= $this->TwigExtension->priceFilter($productTotalPrice);
        $totalPriceArray["product_price_label"]= $this->translatorService->trans('admin.service_group_manager.charge_type.product_price');
        $totalPriceArray['currency_symbol'] = $productDetail['currency']['symbol'];
        $totalPriceArray["product_price_charge_total"]= $this->TwigExtension->currencyFilter($totalPrice);
        $totalPriceArray["product_price_charge_total_js"]= $this->TwigExtension->priceFilter($totalPrice);
        $totalPriceArray["product_price_total_label"]= $this->translatorService->trans('admin.service_group_manager.charge_type.product_price_total');

        // return total price aaray
        return $totalPriceArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Calculate charges as per request
     *
     * @param 1 : inputDetail
     * @param 2 : productDetail
     *
     * @return type : chargesArray
     *
     * @throws Exception: Null
     */
    public function applyRuleCharges($inputDetail, $productDetail)
    {
        $charges = array();

        /*$a1 = array(
        		'0'=> array(
        				'from' => 0,
        				'to' => 9,
        				'rate' => 0
        		),
        		'1'=> array(
        				'from' => 10,
        				'to' => 24,
        				'rate' => 0
        		),
        		'2'=> array(
        				'from' => 25,
        				'to' => 49,
        				'rate' => 0
        		),
        		'3'=> array(
        				'from' => 50,
        				'to' => 99,
        				'rate' => 0
        		),
        		'4'=> array(
        				'from' => 100,
        				'to' => 249,
        				'rate' => 0
        		),
        		'5'=> array(
        				'from' => 250,
        				'to' => 499,
        				'rate' => 0
        		),
        		'6'=> array(
        				'from' => 500,
        				'to' => 999,
        				'rate' => 0
        		),
        		'7'=> array(
        				'from' => 1000,
        				'to' => 2499,
        				'rate' => 0
        		),
        		'8'=> array(
        				'from' => 2500,
        				'to' => 4999,
        				'rate' => 0
        		),
        		'9'=> array(
        				'from' => 5000,
        				'to' => 9999,
        				'rate' => 0
        		),
        );
        
        $a2 = array(
        		
        		'0'=> array(
        				'from' => 10,
        				'to' => 24,
        				'rate' => 2
        		),
        		'1'=> array(
        				'from' => 25,
        				'to' => 49,
        				'rate' => 3
        		),
        		'2'=> array(
        				'from' => 50,
        				'to' => 99,
        				'rate' => 4
        		),
        		'3'=> array(
        				'from' => 100,
        				'to' => 249,
        				'rate' => 5
        		),
        		'4'=> array(
        				'from' => 250,
        				'to' => 499,
        				'rate' => 6
        		),
        		'5'=> array(
        				'from' => 500,
        				'to' => 999,
        				'rate' => 30
        		),
        		'6'=> array(
        				'from' => 1000,
        				'to' => 2499,
        				'rate' => 50
        		),
        		
        );
        $i=0;
        foreach ($a1 as $a){
        	foreach ($a2 as $b){
        		if($b['from']==$a['from'])
        			$a1[$i]['rate'] = $b['rate'];
        	}
        	$i++;
        }
        
        echo '<pre>'; print_r($a1); die;*/
        
        //calculate Imprint charges
        if ($charge = $this->calculateImprintCharge($inputDetail, $productDetail)) {
            $charges = array_merge($charges, $charge);
        }

        return $charges;
    }

    protected function calculateImprintCharge($inputDetail, $productDetail)
    {
        $allCharges = $allChargesList = array();


    	if ($this->serviceContainer->hasParameter('all_charges_list') && is_array($this->serviceContainer->getParameter('all_charges_list'))) {
            $allChargesList = array_merge($allChargesList, $this->serviceContainer->getParameter('all_charges_list'));
        }

        $totalQtySelected = 0;
        if (isset($inputDetail['shipping_method']['quantity_detail']) && is_array($inputDetail['shipping_method']['quantity_detail'])) {
            foreach ($inputDetail['shipping_method']['quantity_detail'] as $qtyCharge) {
                foreach ($qtyCharge['quantity'] as $qty) {
                    $totalQtySelected += $qty;
                }
            }
        } else {
            $totalQtySelected = isset($inputDetail['total_qty']) ? $inputDetail['total_qty'] : 0;
        }

        $totalPMSColorSelected = 0;
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            foreach ($inputDetail['imprint'] as $locationId=>$colorInformation) {
                if (isset($colorInformation['selected_colors'])) {
                    foreach ($colorInformation['selected_colors'] as $colors) {
                        if ($colors['is_pms'] == 1) {
                            $totalPMSColorSelected++;
                        }
                    }
                }
            }
        }

        //check is qty 1 or more
        if ($totalQtySelected <= 0) {
            return $allCharges;
        }

        //check is user logged in
        $userSettings = $this->request->get('project_user_setting');
        $userServiceGroupId = null;

        if (isset($userSettings['user_data']) && $userSettings['user_data'] && $userSettings['user_data']->getServiceGroup()) {
            $userServiceGroupId = $userSettings['user_data']->getServiceGroup()->getId();
        } else {
            $defaultGroup = $this->serviceGroupRepository->getServiceDefaultGroupData($this->countryId);
            $userServiceGroupId = $defaultGroup->getId();
        }

        $chargeIndex = 0;

        foreach ($allChargesList as $keyCharge => $oneCharge) {
            if ($keyCharge=='2D_DIE_CHARGE') {
                $keyCharge='DIE_2D_CHARGE';
            }
            if ($keyCharge=='3D_DIE_CHARGE') {
                $keyCharge='DIE_3D_CHARGE';
            }

            $funcionName = $keyCharge.'_CALCULATION';
            if (method_exists($this,  $funcionName)) {
                $chargeData = $this->$funcionName($inputDetail, $productDetail, $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId);
                if (isset($chargeData['charges_amount'])) {
                    $allCharges[$chargeIndex] = $chargeData;
                    $allCharges[$chargeIndex]['currency_symbol'] = $productDetail['currency']['symbol'];
                    $chargeIndex++;
                }elseif (isset($chargeData[0]['charges_amount'])) {
                    foreach ($chargeData as $c){
                    	if (isset($c['charges_amount'])) {
	                    	$allCharges[$chargeIndex] = $c;
	                    	$allCharges[$chargeIndex]['currency_symbol'] = $productDetail['currency']['symbol'];
	                    	$chargeIndex++;
                    	}	
                    }
                }
            }
        }
        $chargeData = $this->FREIGHT_CALCULATION($inputDetail, $productDetail, $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId);
        if (isset($chargeData['charges_amount'])) {
            $allCharges[$chargeIndex] = $chargeData;
            $allCharges[$chargeIndex]['currency_symbol'] = $productDetail['currency']['symbol'];
        }

        return $allCharges;
    }
    
    




    public function LTM_CHARGE_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $ltmCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint']) && $totalQtySelected < $productDetail['minimum_quantity']) {
            $imprintDetails = $inputDetail['imprint'];
            $ltmChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
    
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
    
                    if (isset($productCharges['LTM_CHARGE']['charge']) && $productCharges['LTM_CHARGE']['charge'] > 0) {
                        $LTMCharge = $productCharges['LTM_CHARGE']['charge'];
                        $LTMChargeRate = 0;
                        if (is_array($LTMCharge)) {
                            //column wise ltm charge
    
                            $LTMChargeRate =  $this->infiniteQtyLoopForQtyRate($LTMCharge, $totalQtySelected);
                        } else {
                            // same on all column ltm charge
                            $LTMChargeRate = $LTMCharge;
                        }
    
                        $ltmChargeTotal += eval('return '.$LTMChargeRate * $totalQtySelected .' / 100;'); // %per selected qty
                    }
                }
            }
    
            if ($ltmChargeTotal > 0) {
                $ltmCharges["charges_amount"]= $this->TwigExtension->priceFilter($ltmChargeTotal);
                $ltmCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($ltmChargeTotal);
                $ltmCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.ltm');
            }
        }
        return $ltmCharges;
    }
    
    
    public function PMS_CHARGE_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $pmsCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint']) && $totalPMSColorSelected > 0) {
            $imprintDetails = $inputDetail['imprint'];
            $pmsChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
    
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
    
                    if (isset($productCharges['PMS_CHARGE']['charge']) && $productCharges['PMS_CHARGE']['charge'] > 0) {
                        $PMSColorCharge = $productCharges['PMS_CHARGE']['charge'];
                        $PMSColorChargeRate = 0;
    
    
                        if (is_array($PMSColorCharge)) {
                            //column wise pms color charge
    
                            $PMSColorChargeRate =  $this->infiniteQtyLoopForQtyRate($PMSColorCharge, $totalQtySelected);
                        } else {
                            //same on all column pms color charge
                            $PMSColorChargeRate = $PMSColorCharge;
                        }
    
                        $pmsChargeTotal += $this->applyPMSColorChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $PMSColorChargeRate, $totalPMSColorSelected, $userServiceGroupId);
                        
                        //$pmsChargeTotal += $PMSColorChargeRate * $totalPMSColorSelected;
                    }
                }
            }
    
            if ($pmsChargeTotal > 0) {
                $pmsCharges["charges_amount"]= $this->TwigExtension->priceFilter($pmsChargeTotal);
                $pmsCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($pmsChargeTotal);
                $pmsCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.pms');
            }
        }
        return $pmsCharges;
    }
    
    public function SETUP_CHARGE_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $setupCharges = array();
        
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $setupChargeTotal = 0;
            $imprintDetails = $inputDetail['imprint'];
            $noOfSelectedLocation = count($imprintDetails);
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
    
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
    
                    if (isset($productCharges['SETUP_CHARGE']['charge']) && $productCharges['SETUP_CHARGE']['charge'] > 0) {
                        $setupCharge = $productCharges['SETUP_CHARGE']['charge'];
                        $setupChargeRate = 0;
    
                        if (isset($imprintMethodLocationArray['no_of_color'])) {
                            $noOfSelectedColor = $imprintMethodLocationArray['no_of_color'];
                        } else {
                            $noOfSelectedColor = 0;
                        }
                        
                        //check is selected colors are free
    
                        if (is_array($setupCharge)) {
                            //column wise setup charge
    
                            $setupChargeRate =  $this->infiniteQtyLoopForQtyRate($setupCharge, $totalQtySelected);
                        } else {
                            //same on all column setup charge
                            $setupChargeRate = $setupCharge;
                        }
    
                        if (isset($productDetail['matrix_details']) && count($productDetail['matrix_details']) > 0 && $this->configurationRule['option']['apply_matrix']['status']==1) {
                            if ($noOfSelectedColor==0) {
                                $noOfSelectedColor=1;
                            }
                            $setupChargeTotal += $this->applyMatrixSetupChargeRate($setupChargeRate, $noOfSelectedColor);
                        } elseif ($noOfSelectedColor > 0 || $noOfSelectedLocation > 0) {
                        	$freeColors = $productImprintInformation[$imprintMethodId]['color_included_in_price'];
                        	$freeLocation = $productImprintInformation[$imprintMethodId]['location_included_in_price'];
                        	
                        	/*if($noOfSelectedLocation > $freeLocation)	$noOfSelectedLocation = $noOfSelectedLocation - $freeLocation;
                        	else $noOfSelectedLocation = 1;
                        	
                        	if($noOfSelectedColor > $freeColors)	$noOfSelectedColor = $noOfSelectedColor - $freeColors;
                        	else $noOfSelectedColor = 1;*/
                        	
                            $setupChargeTotal += $this->applySetupChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $setupChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation);
                        }
                    }
                }
            }
    
    
            if ($setupChargeTotal > 0) {
                $setupCharges["charges_amount"]= $this->TwigExtension->priceFilter($setupChargeTotal);
                $setupCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($setupChargeTotal);
                $setupCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.setup');
            }
        }
        return $setupCharges;
    }
    
    public function ADDITIONAL_LOCATION_CHARGE_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $additionalLocationCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            
            $additionalLocationChargeTotal = 0;
            //$noOfSelectedLocation = count($imprintDetails);
            $imprintArray = array();
             
            
            
            	foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
	    
	                //Is available imprint method in product
	                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
	                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
	                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
	                    if (!isset($productImprintInformation[$imprintMethodId])) {
	                        continue;
	                    }
	                    
	                    if(isset($imprintArray[$imprintMethodId]))
	                    	$imprintArray[$imprintMethodId]['selected_location'] += 1;
	                    else{	
	                    
		                    $freeLocation = $productImprintInformation[$imprintMethodId]['location_included_in_price'];
		                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
	    
		                    if (isset($productCharges['ADDITIONAL_LOCATION_CHARGE']['charge']) && $productCharges['ADDITIONAL_LOCATION_CHARGE']['charge'] > 0) {
		                        $additionalLocationCharge = $productCharges['ADDITIONAL_LOCATION_CHARGE']['charge'];
		                        $additionalLocationChargeRate = 0;
		    
		    
		                        //check is selected location
		    
		                        if (is_array($additionalLocationCharge)) {
		                            //column wise additional location charge
		    
		                            $additionalLocationChargeRate =  $this->infiniteQtyLoopForQtyRate($additionalLocationCharge, $totalQtySelected);
		                        } else {
		                            //same on all column additional location charge
		                            $additionalLocationChargeRate = $additionalLocationCharge;
		                        }
		                        $imprintArray[$imprintMethodId]['imprint_location'] = $imprintLocation;
		                        $imprintArray[$imprintMethodId]['imprint_method_location_array'] = $imprintMethodLocationArray;
		                        $imprintArray[$imprintMethodId]['rate'] = $additionalLocationChargeRate;
		                        $imprintArray[$imprintMethodId]['free_location'] = $productImprintInformation[$imprintMethodId]['location_included_in_price'];
		                        $imprintArray[$imprintMethodId]['selected_location'] = 1;
		                        
		                    }
		                    
	                    }
	                }
	            }
	            
	            
	            foreach ($imprintArray as $imp){
	            	if($imp['selected_location'] > $imp['free_location']){
	            		$noOfSelectedLocation = $imp['selected_location'] - $imp['free_location'];
	            		$additionalLocationChargeTotal += $this->applyAdditionalLocationChargeRule($productDetail, $imp['imprint_location'] , $imp['imprint_method_location_array'] , $imp['rate'], $totalQtySelected, 'location', $userServiceGroupId, $noOfSelectedLocation);
	            	}	
	            }
	            
	            
        	
            if ($additionalLocationChargeTotal > 0) {
                $additionalLocationCharges["charges_amount"]= $this->TwigExtension->priceFilter($additionalLocationChargeTotal);
                $additionalLocationCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($additionalLocationChargeTotal);
                $additionalLocationCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.location');
            }
        }
        return $additionalLocationCharges;
    }
    
    
    public function ADDITIONAL_COLOR_CHARGE_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $additionalColorCharges = array();
        $additionalColorCharge = 0;
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $additionalColorChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
                    $freeColors = $productImprintInformation[$imprintMethodId]['color_included_in_price'];
    
                    //check is selected color
                    $imprintMatrix = $productDetail['imprint_information']['imprint_method_information'][$imprintMethodLocationArray['imprint_method_id']];
    
                    if (isset($imprintMethodLocationArray['no_of_color'])) {
                        $noOfSelectedColor = $imprintMethodLocationArray['no_of_color'];
                    } else {
                        $noOfSelectedColor = 0;
                    }
    
                    if (isset($productCharges['ADDITIONAL_COLOR_CHARGE']['charge']) && $productCharges['ADDITIONAL_COLOR_CHARGE']['charge'] > 0) {
                        $additionalColorCharge = $productCharges['ADDITIONAL_COLOR_CHARGE']['charge'];
                        $additionalColorChargeRate = 0;
                    }
                    if (isset($imprintMatrix['imprint_matrix']) && isset($imprintMatrix['imprint_matrix']['values']) && count($imprintMatrix['imprint_matrix']['values']) > 0 && $this->configurationRule['option']['apply_matrix']['status']==1) {
                        $additionalColorChargeRate = 0;
                        if ($noOfSelectedColor==0) {
                            $noOfSelectedColor = 1;
                        }
                        if ($noOfSelectedColor > $freeColors) {
                            $additionalColorChargeTotal += $this->applyMatrixCalulation($productDetail, $additionalColorChargeRate, $totalQtySelected, $noOfSelectedColor, $imprintMatrix);
                        }
                    } elseif ($additionalColorCharge && $noOfSelectedColor > $freeColors) {
                        if (is_array($additionalColorCharge)) {
                            //column wise additional color charge
    
                            $additionalColorChargeRate =  $this->infiniteQtyLoopForQtyRate($additionalColorCharge, $totalQtySelected);
                        } else {
                            //same on all column additional color charge
                            $additionalColorChargeRate = $additionalColorCharge;
                        }
                        
                        $noOfSelectedColor = $noOfSelectedColor - $freeColors;
                        $additionalColorChargeTotal += $this->applyAdditionalColorChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $additionalColorChargeRate, $totalQtySelected, 'color', $userServiceGroupId, $noOfSelectedColor);
                    } else {
                        $additionalColorChargeTotal += 0;
                    }
                }
            }
    
            if ($additionalColorChargeTotal > 0) {
                $additionalColorCharges["charges_amount"]= $this->TwigExtension->priceFilter($additionalColorChargeTotal);
                $additionalColorCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($additionalColorChargeTotal);
                $additionalColorCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.color');
            }
        }
        return $additionalColorCharges;
    }
    
    
    public function EMBROIDERY_CHARGES_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $EmbroideryCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $noOfSelectedLocation = count($imprintDetails);
            $EmbroideryChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
                    $freeColors = $productImprintInformation[$imprintMethodId]['color_included_in_price'];
    
                    if (isset($productCharges['EMBROIDERY_CHARGE']['charge']) && $productCharges['EMBROIDERY_CHARGE']['charge'] > 0) {
                        $EmbroideryCharge = $productCharges['EMBROIDERY_CHARGE']['charge'];
                        $EmbroideryChargeRate = 0;
                        if (isset($imprintMethodLocationArray['no_of_color'])) {
                        	$noOfSelectedColor = $imprintMethodLocationArray['no_of_color'];
                        } else {
                        	$noOfSelectedColor = 0;
                        }
    
                        //check is embroidery charge available
                        if (false) { // TODO: add selected location no. conditions
                            if (is_array($EmbroideryCharge)) {
                                //column wise embroidery charge
    
                                $EmbroideryChargeRate =  $this->infiniteQtyLoopForQtyRate($EmbroideryCharge, $totalQtySelected);
                            } else {
                                //same on all column embroidery charge
                                $EmbroideryChargeRate = $EmbroideryCharge;
                            }
                        }
    
                        $EmbroideryChargeTotal = $this->applyEmbroideryChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $EmbroideryChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation);
                    }
                }
            }
    
            if ($EmbroideryChargeTotal > 0) {
                $EmbroideryCharges["charges_amount"]= $this->TwigExtension->priceFilter($EmbroideryChargeTotal);
                $EmbroideryCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($EmbroideryChargeTotal);
                $EmbroideryCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.color');
            }
        }
        return $EmbroideryCharges;
    }
    
    public function PAPER_PROOF_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $paperCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $PaperProofChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
    
                    if (isset($productCharges['PAPER_PROOF']['charge']) && $productCharges['PAPER_PROOF']['charge'] > 0 && isset($inputDetail['paper_proof']['status']) && $inputDetail['paper_proof']['status']==1) {
                        $PaperProofCharge = $productCharges['PAPER_PROOF']['charge'];
                        $PaperProofChargeRate = 0;
    
                        if (is_array($PaperProofCharge)) {
                            //column wise paper proof charge
    
                            $PaperProofChargeRate =  $this->infiniteQtyLoopForQtyRate($PaperProofCharge, $totalQtySelected);
                        } else {
                            //same on all column paper proof charge
                            $PaperProofChargeRate = $PaperProofCharge;
                        }
    
                        $PaperProofChargeTotal += $PaperProofChargeRate;
                    }
                }
            }
    
            if ($PaperProofChargeTotal > 0) {
                $paperCharges["charges_amount"]= $this->TwigExtension->priceFilter($PaperProofChargeTotal);
                $paperCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($PaperProofChargeTotal);
                $paperCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.paper_proof');
            }
        }
    
        return $paperCharges;
    }
    
    public function FAX_PROOF_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $faxCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $FaxProofChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
    
                    if (isset($productCharges['FAX_PROOF']['charge']) && $productCharges['FAX_PROOF']['charge'] > 0 && isset($inputDetail['fax_proof']['status']) && $inputDetail['fax_proof']['status']==1) {
                        $FaxProofCharge = $productCharges['FAX_PROOF']['charge'];
                        $FaxProofChargeRate = 0;
    
                        if (is_array($FaxProofCharge)) {
                            //column wise fax proof charge
    
                            $FaxProofChargeRate =  $this->infiniteQtyLoopForQtyRate($FaxProofCharge, $totalQtySelected);
                        } else {
                            //same on all column fax proof charge
                            $FaxProofChargeRate = $FaxProofCharge;
                        }
                        $FaxProofChargeTotal += $FaxProofChargeRate;
                    }
                }
            }
    
            if ($FaxProofChargeTotal > 0) {
                $faxCharges["charges_amount"]= $this->TwigExtension->priceFilter($FaxProofChargeTotal);
                $faxCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($FaxProofChargeTotal);
                $faxCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.fax_proof');
            }
        }
    
        return $faxCharges;
    }
    
    public function PRODUCT_PROOF_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $proofCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $ProductProofChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
    
                    if (isset($productCharges['PRODUCT_PROOF']['charge']) && $productCharges['PRODUCT_PROOF']['charge'] > 0 && isset($inputDetail['product_proof']['status']) && $inputDetail['product_proof']['status']==1) {
                        $ProductProofCharge = $productCharges['PRODUCT_PROOF']['charge'];
                        $ProductProofChargeRate = 0;
    
    
                        if (is_array($ProductProofCharge)) {
                            //column wise Product proof charge
    
                            $ProductProofChargeRate =  $this->infiniteQtyLoopForQtyRate($ProductProofCharge, $totalQtySelected);
                        } else {
                            //same on all column Product proof charge
                            $ProductProofChargeRate = $ProductProofCharge;
                        }
    
                        $ProductProofChargeTotal += $ProductProofChargeRate;
                    }
                }
            }
    
            if ($ProductProofChargeTotal > 0) {
                $proofCharges["charges_amount"]= $this->TwigExtension->priceFilter($ProductProofChargeTotal);
                $proofCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($ProductProofChargeTotal);
                $proofCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.product_proof');
            }
        }
    
        return $proofCharges;
    }
    
    public function ONLINE_EMAIL_PROOF_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $proofCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $EmailProofChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
    
                    if (isset($productCharges['ONLINE_EMAIL_PROOF']['charge']) && $productCharges['ONLINE_EMAIL_PROOF']['charge'] > 0 && isset($inputDetail['email_proof']['status']) && $inputDetail['email_proof']['status']==1) {
                        $EmailProofCharge = $productCharges['ONLINE_EMAIL_PROOF']['charge'];
                        $EmailProofChargeRate = 0;
    
    
                        if (is_array($EmailProofCharge)) {
                            //column wise Email proof charge
    
                            $EmailProofChargeRate =  $this->infiniteQtyLoopForQtyRate($EmailProofCharge, $totalQtySelected);
                        } else {
                            //same on all column Email proof charge
                            $EmailProofChargeRate = $EmailProofCharge;
                        }
    
                        $EmailProofChargeTotal += $EmailProofChargeRate;
                    }
                }
            }
    
            if ($EmailProofChargeTotal > 0) {
                $proofCharges["charges_amount"]= $this->TwigExtension->priceFilter($EmailProofChargeTotal);
                $proofCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($EmailProofChargeTotal);
                $proofCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.email_proof');
            }
        }
    
        return $proofCharges;
    }
    
    public function FREIGHT_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $freightCharges = array();
    
        if (isset($productDetail['matrix_details']) && isset($productDetail['matrix_details']['freight']) && count($productDetail['matrix_details']['freight']['values']) > 0 && $this->configurationRule['option']['apply_matrix']['status']==1) {
            $FreightCharge = $productDetail['matrix_details']['freight']['values'];
            $FreightChargeRate = 0;
            if (is_array($FreightCharge)) {
                //column wise metal corner charge
            	$FreightChargeRate = $this->infiniteQtyLoopForMatrixQtyRate($FreightCharge, $totalQtySelected);
                
            } else {
                //same on all column metal corner charge
                $FreightChargeRate = $FreightCharge;
            }
    
    
    
            $apiVersion =  $this->serviceContainer->getParameter('api.available_call_to_override');
    
            if ($apiVersion['view_product'] == 'v2' && isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
                $imprintDetails = $inputDetail['imprint'];
    
                foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
    
                    //Is available imprint method in product
                    if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                        $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                        $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
    
                        if (!isset($productImprintInformation[$imprintMethodId])) {
                            continue;
                        }
                        $productPricing = $productImprintInformation[$imprintMethodId]['price']['pricing'];
                        if(isset($inputDetail['order_type']) && $inputDetail['order_type']!='')	$priceType = $inputDetail['order_type'];
                    	else $priceType = "decorative";

                    	if($priceType=='decoration')	$priceType = "decorative";
                    	 
                        if (!isset($productPricing[$priceType]) && isset($productPricing['blank']) && !empty($productPricing['blank'])) {
                            $priceType = "blank";
                        }
    
    
                        //for infinite loop for any number of qty
                        $priceOrig =  $this->infiniteQtyLoopForQtyRate($productPricing[$priceType], $totalQtySelected, true);
                    }
                }
            } else {
                $productPricing = $productDetail['pricing'];
                if(isset($inputDetail['order_type']) && $inputDetail['order_type']!='')	$priceType = $inputDetail['order_type'];
                else $priceType = "decorative";

                if($priceType=='decoration')	$priceType = "decorative";
                 
                if (!isset($productPricing[$priceType]) && isset($productPricing['blank']) && !empty($productPricing['blank'])) {
                    $priceType = "blank";
                }
    
                //for infinite loop for any number of qty
                $priceOrig =  $this->infiniteQtyLoopForQtyRate($productPricing[$priceType], $totalQtySelected, true);
            }
            $priceOrig = $this->TwigExtension->priceFilter($priceOrig);
    
    
            $FreightChargeTotal = eval('return '.$FreightChargeRate * $totalQtySelected * $priceOrig .' / 100;'); // per selected qty;
    
            if ($FreightChargeTotal > 0) {
                $freightCharges["charges_amount"]= $this->TwigExtension->priceFilter($FreightChargeTotal);
                $freightCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($FreightChargeTotal);
                $freightCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.freight_charge');
            }
        }
        return $freightCharges;
    }
    

    

    public function DIGITIZING_FEE_CHARGE_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId)
    {
        $digitizingCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $noOfSelectedLocation = count($imprintDetails);
            $digitizingChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id']) && in_array($imprintMethodLocationArray['imprint_method_id'],$this->embroideryMethods)) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
                    $freeColors = $productImprintInformation[$imprintMethodId]['color_included_in_price'];
    
                    if (isset($productCharges['DIGITIZING']['charge']) && $productCharges['DIGITIZING']['charge'] > 0) {
                        $digitizingCharge = $productCharges['DIGITIZING']['charge'];
                        $digitizingChargeRate = 0;
                        if (isset($imprintMethodLocationArray['no_of_color'])) {
                        	$noOfSelectedColor = $imprintMethodLocationArray['no_of_color'];
                        } else {
                        	$noOfSelectedColor = 0;
                        }
                        //check is Digitizing charge availablea
                            if (is_array($digitizingCharge)) {
                                //column wise Digitizing charge
    
                                $digitizingChargeRate =  $this->infiniteQtyLoopForQtyRate($digitizingCharge, $totalQtySelected);
                            } else {
                                //same on all column Digitizing charge
                                $digitizingChargeRate = $digitizingCharge;
                            }
                        $digitizingChargeTotal = $this->applyDigitizingChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $digitizingChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation);
                    }
                }
            }
    
            if ($digitizingChargeTotal > 0) {
                $digitizingCharges["charges_amount"]= $this->TwigExtension->priceFilter($digitizingChargeTotal);
                $digitizingCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($digitizingChargeTotal);
                $digitizingCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.digitizing');
            }
        }
        return $digitizingCharges;
    }
    

    public function PROOF_SWATCH_CHARGE_CALCULATION($inputDetail, $productDetail,  $totalQtySelected, $totalPMSColorSelected, $userServiceGroupId){
    	
        $swatchProofCharges = array();
    
        if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
            $imprintDetails = $inputDetail['imprint'];
            $noOfSelectedLocation = count($imprintDetails);
            $swatchProofChargeTotal = 0;
            foreach ($imprintDetails as $imprintLocation=>$imprintMethodLocationArray) {
                //Is available imprint method in product
                if (isset($imprintMethodLocationArray['imprint_method_id'])) {
                    $imprintMethodId = $imprintMethodLocationArray['imprint_method_id'];
                    $productImprintInformation = $productDetail['imprint_information']['imprint_method_information'];
                    if (!isset($productImprintInformation[$imprintMethodId])) {
                        continue;
                    }
                    $productCharges = $productImprintInformation[$imprintMethodId]['charges'];
                    
                    $freeColors = $productImprintInformation[$imprintMethodId]['color_included_in_price'];
    
                    if (isset($productCharges['PROOF_SWATCH_CHARGE']['charge']) && $productCharges['PROOF_SWATCH_CHARGE']['charge'] > 0 && isset($inputDetail['swatch_proof']['status']) && $inputDetail['swatch_proof']['status']==1) {
                        $swatchProofCharge = $productCharges['PROOF_SWATCH_CHARGE']['charge'];
                        $swatchProofChargeRate = 0;
                        if (isset($imprintMethodLocationArray['no_of_color'])) {
                        	$noOfSelectedColor = $imprintMethodLocationArray['no_of_color'];
                        } else {
                        	$noOfSelectedColor = 0;
                        }
                        //check is PROOF_SWATCH_CHARGE charge availablea
                            if (is_array($swatchProofCharge)) {
                                //column wise PROOF_SWATCH_CHARGE charge
    
                                $swatchProofChargeRate =  $this->infiniteQtyLoopForQtyRate($swatchProofCharge, $totalQtySelected);
                            } else {
                                //same on all column PROOF_SWATCH_CHARGE charge
                                $swatchProofChargeRate = $swatchProofCharge;
                            }
                        $swatchProofChargeTotal = $this->applySwatchProofChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $swatchProofChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation);
                    }
                }
            }
    
            if ($swatchProofChargeTotal > 0) {
                $swatchProofCharges["charges_amount"]= $this->TwigExtension->priceFilter($swatchProofChargeTotal);
                $swatchProofCharges["charges_amount_js"]= $this->TwigExtension->currencyFilter($swatchProofChargeTotal);
                $swatchProofCharges["charges_type"]= $this->translatorService->trans('admin.service_group_manager.charge_type.swatch_proof');
            }
        }
        return $swatchProofCharges;
    }
    public function applySwatchProofChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $SwatchProofChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation)
    {
    	$finalSwatchProofCharge = $SwatchProofChargeRate;
    
    	if ($SwatchProofChargeRate > 0) {
    		//Rule information
    		//setup charge id 1
    
    		$serviceRuleChargeProductPriceArray = $this->serviceRuleChargeProductPriceRepository->findByProductIdAndType($productDetail['product_id'], 'SwatchProof', $userServiceGroupId);
    
    		if (!$serviceRuleChargeProductPriceArray) {
    			//return $finalSwatchProofCharge;
    			return $SwatchProofChargeRate;
    		}
    
    		foreach ($serviceRuleChargeProductPriceArray as $serviceRuleChargeProductPrice) {
    			//get service Rule Master
    			$serviceRuleMappingMaster = $serviceRuleChargeProductPrice->getRuleMappingId();
    
    			//check is SwatchProof charge rule satisfied or not
    			if (!$this->checkRuleForCharges($serviceRuleMappingMaster, $imprintLocation, $imprintMethodLocationArray)) {
    				return $finalSwatchProofCharge;
    			}
    
    			//get service rule charge equation array
    			$serviceRuleChargesEquationArray = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();
    
    			if ($serviceRuleChargesEquationArray && $serviceRuleChargesEquationArray->count() > 0) {
    				//check all realted equations
    				foreach ($serviceRuleChargesEquationArray as $serviceRuleChargesEquation) {
    					//TODO: overwrite base SwatchProof charge if in rule equation
    					//$baseCharge = ($serviceRuleChargesEquation->getBaseCharge1()) ? $serviceRuleChargesEquation->getBaseCharge1() : $SwatchProofChargeRate;
    					$firstOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator1());
    					$secoundOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator2());
    					$amountToCalculate = ($serviceRuleChargesEquation->getAmountType() === 1) ? $serviceRuleChargesEquation->getAmount() : $serviceRuleChargesEquation->getAmount()/100;
    
    					//make equation based on SwatchProof charge rule
    					$finalSwatchProofCharge += eval('return '.$SwatchProofChargeRate . $firstOperator .  $SwatchProofChargeRate . $secoundOperator . $amountToCalculate.';');
    				}
    			}
    		}
    	}
    	return $finalSwatchProofCharge;
    }
     
    
    
    public function applySetupChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $setupChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation)
    {
        $finalSetupCharge = 0;
    
        if ($setupChargeRate > 0) {
            //Rule information
            //setup charge id 1
        	$screenPrintMethods = $this->embroideryMethods = array();
        	
        	
        	if ($this->serviceContainer->hasParameter('screen_printing_method_id') && is_array($this->serviceContainer->getParameter('screen_printing_method_id'))) {
        		$screenPrintMethods = array_merge($screenPrintMethods, $this->serviceContainer->getParameter('screen_printing_method_id'));
        	}
        	
        	if ($this->serviceContainer->hasParameter('embroidery_method_id') && is_array($this->serviceContainer->getParameter('embroidery_method_id'))) {
        		$this->embroideryMethods = array_merge($this->embroideryMethods, $this->serviceContainer->getParameter('embroidery_method_id'));
        	}
        	
        	
            $serviceRuleChargeProductPriceArray = $this->serviceRuleChargeProductPriceRepository->findByProductIdAndType($productDetail['product_id'], 'setup', $userServiceGroupId);
    
            if (!$serviceRuleChargeProductPriceArray || in_array($imprintMethodLocationArray['imprint_method_id'], $this->embroideryMethods)) {
               // return $finalSetupCharge;
            	if(in_array($imprintMethodLocationArray['imprint_method_id'], $screenPrintMethods))
            		return $setupChargeRate * $noOfSelectedColor ; //* $noOfSelectedLocation;
            	else 
            		return $setupChargeRate; //* $noOfSelectedColor * $noOfSelectedLocation;
            }
    
            foreach ($serviceRuleChargeProductPriceArray as $serviceRuleChargeProductPrice) {
                //get service Rule Master
                $serviceRuleMappingMaster = $serviceRuleChargeProductPrice->getRuleMappingId();
    
                //check is setup charge rule satisfied or not
                if (!$this->checkRuleForCharges($serviceRuleMappingMaster, $imprintLocation, $imprintMethodLocationArray)) {
                    return $finalSetupCharge;
                }
    
                //get service rule charge equation array
                $serviceRuleChargesEquationArray = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();
    
                if ($serviceRuleChargesEquationArray && $serviceRuleChargesEquationArray->count() > 0) {
                    //check all realted equations
                    foreach ($serviceRuleChargesEquationArray as $serviceRuleChargesEquation) {
                        //TODO: overwrite base setup charge if in rule equation
                        //$baseCharge = ($serviceRuleChargesEquation->getBaseCharge1()) ? $serviceRuleChargesEquation->getBaseCharge1() : $setupChargeRate;
                        $firstOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator1());
                        $secoundOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator2());
                        $amountToCalculate = ($serviceRuleChargesEquation->getAmountType() === 1) ? $serviceRuleChargesEquation->getAmount() : $serviceRuleChargesEquation->getAmount()/100;
    
                        //make equation based on setup charge rule
                        $finalSetupCharge += eval('return '.$setupChargeRate . $firstOperator .  $setupChargeRate . $secoundOperator . $amountToCalculate.';');
                    }
                }
            }
        }
        if(in_array($imprintMethodLocationArray['imprint_method_id'], $screenPrintMethods))
        	return $finalSetupCharge * $noOfSelectedColor ; //* $noOfSelectedLocation;
        else
        	return $finalSetupCharge;
    }
    
    public function applyAdditionalColorChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $setupChargeRate, $totalQtySelected, $chargeType, $userServiceGroupId, $noOfSelectedLocationColor)
    {
        $finalAdditionalLocationCharge = 0;
        if ($setupChargeRate > 0) {
            //Rule information
            //setup charge id 1
            $serviceRuleChargeProductPriceArray = $this->serviceRuleChargeProductPriceRepository->findByProductIdAndType($productDetail['product_id'], $chargeType, $userServiceGroupId);
            if (!$serviceRuleChargeProductPriceArray) {
                //return $finalAdditionalLocationCharge;
            	return $setupChargeRate * $noOfSelectedLocationColor * $totalQtySelected;
            }
    
            foreach ($serviceRuleChargeProductPriceArray as $serviceRuleChargeProductPrice) {
                //get service Rule Master
                $serviceRuleMappingMaster = $serviceRuleChargeProductPrice->getRuleMappingId();
                //check is setup charge rule satisfied or not
                if (!$this->checkRuleForCharges($serviceRuleMappingMaster, $imprintLocation, $imprintMethodLocationArray)) {
                    return $finalAdditionalLocationCharge;
                }
                //get service rule charge equation array
                $serviceRuleChargesEquationArray = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();
    
                if ($serviceRuleChargesEquationArray && $serviceRuleChargesEquationArray->count() > 0) {
                    //check all realted equations
                    foreach ($serviceRuleChargesEquationArray as $serviceRuleChargesEquation) {
                        //TODO: overwrite base setup charge if in rule equation
                        //$baseCharge = ($serviceRuleChargesEquation->getBaseCharge1()) ? $serviceRuleChargesEquation->getBaseCharge1() : $setupChargeRate;
                        
                    	$firstOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator1());
                    	$secoundOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator2());
                    	$amountToCalculate = ($serviceRuleChargesEquation->getAmountType() === 1) ? $serviceRuleChargesEquation->getAmount() : $serviceRuleChargesEquation->getAmount()/100;
                    	
                    	//make equation based on setup charge rule
                    	$finalAdditionalLocationCharge += eval('return '.$setupChargeRate . $firstOperator .  $setupChargeRate . $secoundOperator . $amountToCalculate.';');
                    	
                    }
                    
                    $finalAdditionalLocationCharge = $finalAdditionalLocationCharge * $noOfSelectedLocationColor * $totalQtySelected;
                    
                }else{
                	$finalAdditionalLocationCharge = $setupChargeRate * $noOfSelectedLocationColor * $totalQtySelected;
                }
            }
        }
    	return $finalAdditionalLocationCharge;
    }
    
    
    public function applyAdditionalLocationChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $setupChargeRate, $totalQtySelected, $chargeType, $userServiceGroupId, $noOfSelectedLocationColor)
    {
    	$finalAdditionalLocationCharge = 0;
    	if ($setupChargeRate > 0) {
    		//Rule information
    		//setup charge id 1
    		$serviceRuleChargeProductPriceArray = $this->serviceRuleChargeProductPriceRepository->findByProductIdAndType($productDetail['product_id'], $chargeType, $userServiceGroupId);
    		if (!$serviceRuleChargeProductPriceArray) {
    			//return $finalAdditionalLocationCharge;
    			return $setupChargeRate * $noOfSelectedLocationColor * $totalQtySelected;
    		}
    
    		foreach ($serviceRuleChargeProductPriceArray as $serviceRuleChargeProductPrice) {
    			//get service Rule Master
    			$serviceRuleMappingMaster = $serviceRuleChargeProductPrice->getRuleMappingId();
    			//check is setup charge rule satisfied or not
    			if (!$this->checkRuleForCharges($serviceRuleMappingMaster, $imprintLocation, $imprintMethodLocationArray)) {
    				return $finalAdditionalLocationCharge;
    			}
    			//get service rule charge equation array
    			$serviceRuleChargesEquationArray = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();
    
    			if ($serviceRuleChargesEquationArray && $serviceRuleChargesEquationArray->count() > 0) {
    				//check all realted equations
    				foreach ($serviceRuleChargesEquationArray as $serviceRuleChargesEquation) {
    					//TODO: overwrite base setup charge if in rule equation
    					//$baseCharge = ($serviceRuleChargesEquation->getBaseCharge1()) ? $serviceRuleChargesEquation->getBaseCharge1() : $setupChargeRate;
    
    					$firstOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator1());
    					$secoundOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator2());
    					$amountToCalculate = ($serviceRuleChargesEquation->getAmountType() === 1) ? $serviceRuleChargesEquation->getAmount() : $serviceRuleChargesEquation->getAmount()/100;
    					 
    					//make equation based on setup charge rule
    					$finalAdditionalLocationCharge += eval('return '.$setupChargeRate . $firstOperator .  $setupChargeRate . $secoundOperator . $amountToCalculate.';');
    					 
    				}
    
    				$finalAdditionalLocationCharge = $finalAdditionalLocationCharge * $noOfSelectedLocationColor * $totalQtySelected;
    
    			}else{
    				$finalAdditionalLocationCharge = $setupChargeRate * $noOfSelectedLocationColor * $totalQtySelected;
    			}
    		}
    	}
    	return $finalAdditionalLocationCharge;
    }
    
    public function applyMatrixCalulation($productDetail, $colorChargeRate, $totalQtySelected, $noOfSelectedColor, $imprintMatrix)
    {
        $charge = 0;
    
        if (isset($imprintMatrix['imprint_matrix']['values'][$noOfSelectedColor]['values'])) {
        	
        	$charge =  $this->infiniteQtyLoopForMatrixQtyRate($imprintMatrix['imprint_matrix']['values'][$noOfSelectedColor]['values'], $totalQtySelected);
        }
    
        //$charge =  infiniteQtyLoopForMatrixQtyRate($imprintMatrix['imprint_matrix']['values'][$noOfSelectedColor]['values'], $totalQtySelected); //$MatrixChargeRate; //($colorChargeRate *
    
        return  $charge * $totalQtySelected;
    }
    
    public function applyMatrixSetupChargeRate($setupChargeRate, $noOfSelectedColor)
    {
        return $setupChargeRate * $noOfSelectedColor;
    }
    
    
    public function applyPMSColorChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $PMSColorChargeRate, $totalPMSColorSelected, $userServiceGroupId)
    {
        
    	$finalPMSCharge = 0;
    	if ($PMSColorChargeRate > 0) {
    		//Rule information
    		//setup charge id 1
    		$serviceRuleChargeProductPriceArray = $this->serviceRuleChargeProductPriceRepository->findByProductIdAndType($productDetail['product_id'], 'pms', $userServiceGroupId);
    		if (!$serviceRuleChargeProductPriceArray) {
    			//return $finalPMSCharge;
    			return $PMSColorChargeRate * $totalPMSColorSelected;
    		}
    	
    		foreach ($serviceRuleChargeProductPriceArray as $serviceRuleChargeProductPrice) {
    			//get service Rule Master
    			$serviceRuleMappingMaster = $serviceRuleChargeProductPrice->getRuleMappingId();
    			
    			/* if (!$this->checkRuleForCharges($serviceRuleMappingMaster, $imprintLocation, $imprintMethodLocationArray)) {
    				return $finalPMSCharge;
    			} */
    			//get service rule charge equation array
    			$serviceRuleChargesEquationArray = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();
    	
    			if ($serviceRuleChargesEquationArray && $serviceRuleChargesEquationArray->count() > 0) {
    				//check all realted equations
    				foreach ($serviceRuleChargesEquationArray as $serviceRuleChargesEquation) {
    					//TODO: overwrite base setup charge if in rule equation
    					//$baseCharge = ($serviceRuleChargesEquation->getBaseCharge1()) ? $serviceRuleChargesEquation->getBaseCharge1() : $PMSColorChargeRate;
    	
    					$firstOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator1());
    					$secoundOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator2());
    					$amountToCalculate = ($serviceRuleChargesEquation->getAmountType() === 1) ? $serviceRuleChargesEquation->getAmount() : $serviceRuleChargesEquation->getAmount()/100;
    					 
    					//make equation based on setup charge rule
    					$finalPMSCharge += eval('return '.$PMSColorChargeRate . $firstOperator .  $PMSColorChargeRate . $secoundOperator . $amountToCalculate.';');
    					 
    				}
    	
    				$finalPMSCharge = $finalPMSCharge * $totalPMSColorSelected;
    	
    			}else{
    				$finalPMSCharge = $PMSColorChargeRate * $totalPMSColorSelected;
    			}
    		}
    	}
    	return $finalPMSCharge;
    	//return $PMSColorChargeRate * $totalQtySelected * $totalPMSColorSelected;
    }
    
    public function applyEmbroideryChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $EmbroideryChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation)
    {
        $finalEmbroideryCharge = 0;
    
        if ($EmbroideryChargeRate > 0) {
            //Rule information
            //setup charge id 1
    		
            $serviceRuleChargeProductPriceArray = $this->serviceRuleChargeProductPriceRepository->findByProductIdAndType($productDetail['product_id'], 'embroidery', $userServiceGroupId);
    
            if (!$serviceRuleChargeProductPriceArray) {
                //return $finalEmbroideryCharge;
            	return $EmbroideryChargeRate * $noOfSelectedColor * $noOfSelectedLocation;
            }
    
            foreach ($serviceRuleChargeProductPriceArray as $serviceRuleChargeProductPrice) {
                //get service Rule Master
                $serviceRuleMappingMaster = $serviceRuleChargeProductPrice->getRuleMappingId();
    
                //check is Embroidery charge rule satisfied or not
                if (!$this->checkRuleForCharges($serviceRuleMappingMaster, $imprintLocation, $imprintMethodLocationArray)) {
                    return $finalEmbroideryCharge;
                }
    
                //get service rule charge equation array
                $serviceRuleChargesEquationArray = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();
    
                if ($serviceRuleChargesEquationArray && $serviceRuleChargesEquationArray->count() > 0) {
                    //check all realted equations
                    foreach ($serviceRuleChargesEquationArray as $serviceRuleChargesEquation) {
                        //TODO: overwrite base Embroidery charge if in rule equation
                        //$baseCharge = ($serviceRuleChargesEquation->getBaseCharge1()) ? $serviceRuleChargesEquation->getBaseCharge1() : $EmbroideryChargeRate;
                        $firstOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator1());
                        $secoundOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator2());
                        $amountToCalculate = ($serviceRuleChargesEquation->getAmountType() === 1) ? $serviceRuleChargesEquation->getAmount() : $serviceRuleChargesEquation->getAmount()/100;
    
                        //make equation based on Embroidery charge rule
                        $finalEmbroideryCharge += eval('return '.$EmbroideryChargeRate . $firstOperator .  $EmbroideryChargeRate . $secoundOperator . $amountToCalculate.';');
                    }
                }
            }
        }
    
        return $finalEmbroideryCharge;
    }
    
    public function applyDigitizingChargeRule($productDetail, $imprintLocation, $imprintMethodLocationArray, $digitizingChargeRate, $userServiceGroupId, $noOfSelectedColor, $noOfSelectedLocation)
    {
    	$finalDigitizingCharge = $digitizingChargeRate;
    
    	if ($digitizingChargeRate > 0) {
    		//Rule information
    		//setup charge id 1
    
    		$serviceRuleChargeProductPriceArray = $this->serviceRuleChargeProductPriceRepository->findByProductIdAndType($productDetail['product_id'], 'digitizing', $userServiceGroupId);
    
    		if (!$serviceRuleChargeProductPriceArray) {
    			//return $finalDigitizingCharge;
    			return $digitizingChargeRate;
    		}
    
    		foreach ($serviceRuleChargeProductPriceArray as $serviceRuleChargeProductPrice) {
    			//get service Rule Master
    			$serviceRuleMappingMaster = $serviceRuleChargeProductPrice->getRuleMappingId();

    			//check is Digitizing charge rule satisfied or not
    			if (!$this->checkRuleForCharges($serviceRuleMappingMaster, $imprintLocation, $imprintMethodLocationArray)) {
    				return $finalDigitizingCharge;
    			}
    
    			//get service rule charge equation array
    			$serviceRuleChargesEquationArray = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();
    
    			if ($serviceRuleChargesEquationArray && $serviceRuleChargesEquationArray->count() > 0) {
    				//check all realted equations
    				foreach ($serviceRuleChargesEquationArray as $serviceRuleChargesEquation) {
    					//TODO: overwrite base Digitizing charge if in rule equation
    					//$baseCharge = ($serviceRuleChargesEquation->getBaseCharge1()) ? $serviceRuleChargesEquation->getBaseCharge1() : $digitizingChargeRate;
    					$firstOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator1());
    					$secoundOperator = $this->getConditionOperator($serviceRuleChargesEquation->getConditionOperator2());
    					$amountToCalculate = ($serviceRuleChargesEquation->getAmountType() === 1) ? $serviceRuleChargesEquation->getAmount() : $serviceRuleChargesEquation->getAmount()/100;
    
    					//make equation based on Digitizing charge rule
    					$finalDigitizingCharge += eval('return '.$digitizingChargeRate . $firstOperator .  $digitizingChargeRate . $secoundOperator . $amountToCalculate.';');
    				}
    			}
    		}
    	}
    	return $finalDigitizingCharge;
    }
    
    
    public function infiniteQtyLoopForQtyRate($priceArray, $totalQtySelected, $isOrig=false)
    {
        $priceOrig = 0;
        if (isset($priceArray[count($priceArray)-1]['to']) && !empty($priceArray[count($priceArray)-1]['to'])) {
            $lastQty = $priceArray[count($priceArray)-1]['to'];
        } else {
            $lastQty = $priceArray[count($priceArray)-1]['from'];
        }
            
        if (isset($priceArray[0]['rate']) && (count($priceArray)==1) || (isset($priceArray[0]['from']) && $totalQtySelected <= $priceArray[0]['from'])) {
            if ($isOrig && isset($priceArray[0]['rate_orig'])) {
                $priceOrig += $priceArray[0]['rate_orig'];
            } else {
                $priceOrig += $priceArray[0]['rate'];
            }
        } elseif ($totalQtySelected >= $lastQty) {
            if ($isOrig && isset($priceArray[count($priceArray)-1]['rate_orig'])) {
                $priceOrig += $priceArray[count($priceArray)-1]['rate_orig'];
            } else {
                $priceOrig += $priceArray[count($priceArray)-1]['rate'];
            }
        } elseif ($totalQtySelected > 0) {
            for ($index=0;;$index++) {
                if (isset($priceArray[$index]['code']) || isset($priceArray[$index]['from'])) {
                    $from = $priceArray[$index]['from'];
                    if (isset($priceArray[$index]['to']) && !empty($priceArray[$index]['to'])) {
                        $to = $priceArray[$index]['to'];
                    } else {
                        $to = $priceArray[$index]['from'];
                    }
                    if (($totalQtySelected >= $from && $totalQtySelected <= $to)) {
                        if ($isOrig && isset($priceArray[$index]['rate_orig'])) {
                            $priceOrig += $priceArray[$index]['rate_orig'];
                        } else {
                            $priceOrig += $priceArray[$index]['rate'];
                        }
            
                                //TODO: calculate discount code if applicable
                    }
                } else {
                    //if nomore qty than break infinite loop
                        break;
                }
            }
        }
        return $priceOrig;
    }
    
    public function infiniteQtyLoopForMatrixQtyRate($priceArray, $totalQtySelected)
    {
    	$priceOrig = 0;
    	if (isset($priceArray[count($priceArray)-1]['to_qty']) && !empty($priceArray[count($priceArray)-1]['to_qty'])) {
    		$lastQty = $priceArray[count($priceArray)-1]['to_qty'];
    	} else {
    		$lastQty = $priceArray[count($priceArray)-1]['from_qty'];
    	}
    
    	if (isset($priceArray[0]['rate']) && (count($priceArray)==1) || (isset($priceArray[0]['from_qty']) && $totalQtySelected <= $priceArray[0]['from_qty'])) {
    		$priceOrig += $priceArray[0]['rate'];
    		
    	} elseif ($totalQtySelected >= $lastQty) {
    		$priceOrig += $priceArray[count($priceArray)-1]['rate'];
    		
    	} elseif ($totalQtySelected > 0) {
    		for ($index=0;;$index++) {
    			if (isset($priceArray[$index]['code']) || isset($priceArray[$index]['from_qty'])) {
    				$from = $priceArray[$index]['from_qty'];
    				if (isset($priceArray[$index]['to_qty']) && !empty($priceArray[$index]['to_qty'])) {
    					$to = $priceArray[$index]['to_qty'];
    				} else {
    					$to = $priceArray[$index]['from_qty'];
    				}
    				if (($totalQtySelected >= $from && $totalQtySelected <= $to)) {
    					$priceOrig += $priceArray[$index]['rate'];
    					
    
    					//TODO: calculate discount code if applicable
    				}
    			} else {
    				//if nomore qty than break infinite loop
    				break;
    			}
    		}
    	}
    	return $priceOrig;
    }
}
