<?php
/***************************************************************************
 *																		  *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *																		  *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.
 *																		  *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED W
 ITH THIS DISTRIBUTION PACKAGE.			*
 ****************************************************************************/ //
//$Id: ProductModel.php, v 1.0 2011/06/14 20:52:11
//
class ProductModel extends Model {
    public function getPageLayout($params = array()) {
        extract($params);
        $currentDate = date('Y-m-d');
        $sql         = "
			SELECT
				tplName AS pageLayout
			FROM
					" . DB_PREFIX . "products AS product
				INNER JOIN
					" . DB_PREFIX . "catalog_page_layout AS catPagLay
						ON	(
							product.productDetailsLayout =  catPagLay.pageLayoutID
						)
			WHERE
				pageLayoutType='details'
				AND
				productID='" . $productID . "'
				AND
					(
					'" . $currentDate . "' BETWEEN layoutActiveFrom AND layoutActiveTo 
					OR
					layoutActiveFrom='0000-00-00' AND layoutActiveTo='0000-00-00'
					)
			LIMIT 1
		";
        return $this->ObjDatabase->readValueSlave($sql);
    }

     public function getProductIDs($productID) {
        $sql    = "
           SELECT buyboxID FROM dp_buybox_details WHERE productID='" .(int) $productID . "'
		";
         $res= $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
         $buyboxID=$res['buyboxID'];
            $sqlre="SELECT MIN( pdtOpt.productOptionProductPrice ) as price FROM " . DB_PREFIX . "product_options AS pdtOpt
                    INNER JOIN  " . DB_PREFIX . "buybox_details AS buyDet 
              ON  buyDet.productID= pdtOpt.productID WHERE buyDet.buyboxID = '" . (int)$buyboxID . "'";   
            $price= $this->ObjDatabase->readValue($sqlre, MYSQLI_ASSOC);
            return $price;
    }
    //FUNCTION TO GET PRODUCT KEY
    public function getProductUrl($productID = "") {
        $sql    = "
		SELECT
				product.productUrl
		FROM
				" . DB_PREFIX . "products as product
		WHERE
				product.productID='" . (int) $productID . "'";
        $result = $this->ObjDatabase->readValueSlave($sql, MYSQLI_ASSOC);
        return $result['productUrl'];
    }
    
    public function getProductOptionBusCount($productOptionID){
        $sqlSelect         =  "SELECT productOptionQuantity,productQuantityUnlimited 
                                                    FROM ".DB_PREFIX."products_options_business
                                                    WHERE productOptionID = '".$productOptionID."'
                                                    AND businessOptionDefault = 'Yes'";
        $result            =   $this->ObjDatabase->readValueSlave($sqlSelect, MYSQLI_ASSOC);
        $optCount          =   0;
        if($result['productQuantityUnlimited']==1){
            $optCount      =   1;
        }else{
            $optCount      =   $result['productOptionQuantity'];
        }
        return $optCount;
    }
    //FETCHING PRODUCT FOR HOME PAGE
    public function getProductDetails($params) {
        extract($params);
        $currentLanguageID = $languageIDs['Current'];
        $limitFrom         = (isset($limitFrom) && $limitFrom > 0) ? $limitFrom : 0;
        $inclCalcRows      = (isset($limitTo) && $limitTo >= '0') ? "SQL_CALC_FOUND_ROWS" : "";
        $currDateTime      = isset($currDateTime) ? $currDateTime : '';
        $currDateTime      = ($currDateTime == "") ? "'" . date('Y-m-d') . "'" : "'" . $currDateTime . "'";
        $view              = isset($view) ? $view : '';
        $sellersCount      = isset($sellersCount) ? $sellersCount : '';
        $freeProducts      = isset($freeProducts) ? $freeProducts : '';
        $bundleProd        = isset($bundleProd) ? $bundleProd : '';
        $selectProductOpID = isset($selectProductOpID) ? $selectProductOpID : 0;
		$showAllProducts   = !empty($showAllProducts)?$showAllProducts:'';
        $currTime          = date('Y-m-d H:i:00');
        if($sellersCount=='Yes' && $selectedProductID>0){
            $sellerCount    =   $this->getBuyboxProductCount($selectedProductID);
        }else{
            $sellerCount    =   0;
        }
         if($showAllProducts=='Yes') {
			$updprodstatus = " IN ('Active','Inactive') ";
			$updprodcombstatus = " IN ('A','I') ";
		} else {
			$updprodstatus = " = 'Active' ";	
			$updprodcombstatus = " = 'A' ";
		}
        $prodOptBusCount        =           0;
        if($selectProductOpID>0){
            $prodOptBusCount    =           $this->getProductOptionBusCount($selectProductOpID);
        }
        
        if($bundleProd=="Yes" && $prodOptBusCount<=0){
            $sqlProdBusinessID          = "prodOptBus.businessID,";
            $sqlProdOptBusiness         = " AND (IF(product.InventoryTrackLevel='No',
                                                                    prodOptBus.businessOptionDefault='Yes',
                                                                    prodOptBus.productOptionQuantity>0))";
        }else{
            $sqlProdBusinessID          = "product.businessID,";
            $sqlProdOptBusiness         = " AND prodOptBus.businessOptionDefault='Yes'";
        }
                
        $sql               = "
				SELECT " . $inclCalcRows . " ";
        if ($view == '') {
            if (isset($productType['productTypeKey'])) {
                $sql .= "'" . $productType['productTypeKey'] . "' AS productTypeKey ,";
            }
            if (isset($productType['productTypeKey'])) {
                $sql .= "'" . $productType['productTypeKey'] . "' AS productType ,";
            }
            if (isset($productType['productTypeUrlKey'])) {
                $sql .= "'" . $productType['productTypeUrlKey'] . "' AS productTypeUrlKey ,";
            }
            if (isset($productType['productTypeName'])) {
                $sql .= "'" . $productType['productTypeName'] . "' AS productTypeName, ";
            }
            $sql .= " 					
						product.productID,
						product.productTypeID,
						product.isProductDeal,
						product.dealStartTime,
						DATE_ADD(product.dealEndTime,INTERVAL 1 DAY) AS dealEndTime,
						product.productUrl,
						product.attributeSetID,						
						product.productStartTime,
						product.productEndTime,
						product.productDefaultCurrency,
						product.productMinBuyLimit,
						product.productMaxBuyLimit,
						product.productMaxGiftBuy,
						product.dealMaxBuyLimit,
						ROUND(product.dealDiscount) as dealDiscount,
						product.productMinQntyReqToTipp,							
						product.productCommissionRate,
						product.multiOptionsAvailable,
						product.productServiceFee,
						product.featuredStatus,
						product.productImage,
						product.productShowNosBought,	
						product.showCountTimer,
						productDet.productTitle,
						brand.brandID,
						brand.brandIcon,
						brand.brandKey,
						brandDet.brandName,
						$sqlProdBusinessID
						attrSet.comparable,
						product.productStatus,
						product.showQuantityAvailable,
						productDet.productShortDescription,
						finance.detailedDescription as financeDesc,
						finance.shortDescription,
                                                product.enableSizeChart,
                                                productDet.productSizeChart as sizeChart,
                                                product.enableBuybox,
                                                product.sellAsBatch,
                                                product.batchType,
                                                product.qtyPerBatch,
                                                product.financeAvail,
                                                product.leaseAvail,
                                                product.bodyStyle,                                                
                                                prodOptBus.monthlyInstallment,
                                                (SELECT MIN(withoutTrp36) FROM dp_product_lease_price plp
                                                LEFT JOIN dp_product_options pdtopt ON pdtopt.optionSKU = plp.variantCode WHERE productID = '" . (int) $selectedProductID . "'
                                                    ) as leasePrice,
						";
        }
        $sql .= "bus.businessKey,buybox.baseProductID,buyboxPar.baseProductID as parentProductID,product.freeProductsCount";
        
        if ($view) {
            $sql .= ",product.*,ROUND(product.dealDiscount) as dealDiscount,					
                $sellerCount as sellerCount,
						productDet.productTitle,
						productDet.productFinePrint,
						productDet.productHighlights,
						productDet.productDescription,
                                                productDet.productShortDescription,
						brand.brandID,
						brand.brandIcon,
						brand.brandKey,
						brandDet.brandName,
						productDet.searchTags,
						productDet.productMetaTitle,
						productDet.productMetaDescription,
						productDet.productMetaKeywords,
                                                productDet.productSizeChart as sizeChart,
						catPagLay.tplLabel,	
						(SELECT 
							count(distinct productID) 
						FROM  " . DB_PREFIX . "products product 					
						WHERE product.productStatus ".$updprodstatus." AND
							product.productID <> '" . (int) $selectedProductID . "'
								) 
						AS relatedProductCount";
        }
        $sql .= ",taxClassName";
        if ($view == '') {
            $sql .= ",productOpt.productOptionID,
                                                                        productOpt.optionSKU,
									prodOptBus.productOptionProductPrice,
									prodOptBus.productOptionRegularPrice,
                                                                        productOpt.productOptionCashBack,
                                                                        prodOptBus.dealPrice,
									prodOptBus.productOptionQuantity,
									LEAST(
										COALESCE(
											varOffPri.offerPrice,
											prodOptBus.productOptionProductPrice
										),
										COALESCE(
											varGroPri.specialPrice,
											prodOptBus.productOptionProductPrice
										) 
									)
									AS offerPrice,
									ROUND(
										(
											(
												(
												prodOptBus.productOptionRegularPrice-
													LEAST(
														COALESCE(
															varOffPri.offerPrice,
															prodOptBus.productOptionProductPrice
														),
														COALESCE(
															varGroPri.specialPrice,
															prodOptBus.productOptionProductPrice
														) 
													)
												)*100
											)/prodOptBus.productOptionRegularPrice
										),2
									) AS productOptionOfferDiscount,
									IF(product.InventoryTrackLevel = 'No',1,0) as productQuantityUnlimited,
									'" . $currTime . "' as timeZoneConverted,
									product.InventoryTrackLevel,
									IF(product.InventoryTrackLevel = 'Product',
									SUM(prodOptBus.productOptionQuantity),
									SUM(proComBus.businessCombQuantity)) AS productOptionQuantitySum, 
									IF(product.InventoryTrackLevel = 'Product',
									prodOptBus.productOptionQuantity,
									SUM(proComBus.businessCombQuantity)) AS productOptionQuantity, 
									(
									SELECT 
										COUNT(productOptionID)
									FROM 
										" . DB_PREFIX . "product_options
									WHERE
										productID=product.productID
										AND
										productOptionStatus ".$updprodstatus."
									) AS productOptionCount ";
        }
        $sql .= " FROM 
										" . DB_PREFIX . "products   AS product 
									LEFT JOIN 
										" . DB_PREFIX . "brands AS brand 
										ON (
											brand.brandID = product.brandID 
											AND 
											status!='D'
										)
									LEFT JOIN 
										" . DB_PREFIX . "brand_details AS brandDet 
										ON (
											brandDet.brandID = brand.brandID 
											AND
											brandDet.languageID = " . $currentLanguageID . "
										)
									LEFT JOIN 
										" . DB_PREFIX . "tax_classes AS tax
										ON (
											tax.taxClassID = product.taxClassID 
										)	
									INNER JOIN 
										" . DB_PREFIX . "product_details 	AS productDet 
									ON (
										product.productID = productDet.productID 
										AND 
										productDet.languageID = " . $currentLanguageID . "
										)
									INNER JOIN 
											" . DB_PREFIX . "business AS bus 
										ON (
											product.businessID = bus.businessID";
        if (!isset($businessStatus))
            $sql .= " AND bus.businessStatus = 'Active'";
        $sql .= ") ";
        if ($view == '') {
            $sql .= " 
							INNER JOIN 
								" . DB_PREFIX . "product_options AS productOpt 
									ON (
										product.productID = productOpt.productID
										AND
										productOpt.productOptionStatus = 'Active' 
										AND 
										productOpt.productOptionDefault = 'Yes'
									) 
							LEFT JOIN
                                                                ".DB_PREFIX."products_options_business AS prodOptBus
                                                                        ON	(
                                                                                prodOptBus.productOptionID = productOpt.productOptionID
                                                                                $sqlProdOptBusiness
                                                                        )
							LEFT JOIN 
										".DB_PREFIX."finance_rate	AS finance 
											ON (
												finance.variantCode = productOpt.optionSKU						
											)       
							LEFT JOIN
								" . DB_PREFIX . "variant_offer_price AS varOffPri
									ON	(
										varOffPri.productOptionID = productOpt.productOptionID
										AND
										varOffPri.userGroupID='" . $userGroupID . "'
                                                                                AND varOffPri.businessID = prodOptBus.businessID
									)
							LEFT JOIN
								" . DB_PREFIX . "variant_group_price AS varGroPri
									ON	(
										varGroPri.productOptionID = productOpt.productOptionID
										AND
										varGroPri.userGroupID='" . $userGroupID . "'
                                                                                AND varGroPri.businessID = prodOptBus.businessID
									)	
							LEFT JOIN 
								" . DB_PREFIX . "product_combination AS proCom 
								ON (
									proCom.productID=product.productID 
									AND 
									proCom.status ".$updprodcombstatus."
								) 
							LEFT JOIN 
								" . DB_PREFIX . "product_combination_business AS proComBus 
								ON (
									proComBus.combinationID=proCom.combinationID 
									AND 
									proComBus.businessID = product.businessID
								) 
							LEFT JOIN 
								" . DB_PREFIX . "product_combination AS proCom1
								ON
								(
									proCom1.productID=product.productID  
									AND 
									proCom1.status ".$updprodcombstatus." AND proCom1.combinationQty=''
								)
							INNER JOIN
								" . DB_PREFIX . "attribute_set AS attrSet
								ON attrSet.attributeSetID = product.attributeSetID";
        }
        $sql .= "	LEFT JOIN
										" . DB_PREFIX . "catalog_page_layout AS catPagLay
									ON
										( catPagLay.pageLayoutID = product.productDetailsLayout
											AND
											catPagLay.pageLayoutType = 'details'
										)
									";
        $sql .=        " LEFT JOIN ".DB_PREFIX."buybox AS buybox ON (buybox.baseProductID = product.productID) 
                                                         LEFT JOIN ".DB_PREFIX."buybox_details AS buyboxDet ON (buyboxDet.productID = product.productID) 
                                                         LEFT JOIN ".DB_PREFIX."buybox AS buyboxPar ON (buyboxPar.buyboxID = buyboxDet.buyboxID)";
        
        if($freeProducts=='Yes') {
            $sql .=        "   INNER JOIN
								" . DB_PREFIX . "product_link_free AS linkFree
									ON	(
										linkFree.freeProductID = product.productID 
										
									)";
        }
        $sql .= " 
							WHERE ";
       
        if ($view == '') {
            $sql .= " product.productTypeID = '" . (isset($productType['productTypeID'])) ? $productType['productTypeID'] : '' . "' ";
        } else {
            $sql .= " 1 ";            
        }
							
        if (isset($productStatus) && $productStatus == 'Active') {
            $sql .= " AND product.productStatus = '" . $productStatus . "'";
        }
        if ($view == '') {
            $sql .= " 
					AND (
							product.productStartTime <= " . $currDateTime . " 
							AND
							(
								product.productEndTime = '0000-00-00'
								OR
								product.productEndTime >=	" . $currDateTime . "
							)
						)";
        }
        
        if($freeProducts=='Yes') {
             $sql .= " AND linkFree.productID = " . (int) $selectedProductID . " ";
        } else {
            $sql .= " AND product.productID = " . (int) $selectedProductID . " ";
        }        
        $sql .= " AND product.productStatus!='Deleted' GROUP BY product.productID";
        //echo $sql;exit;
        if (isset($limitTo) && $limitTo >= '0') {
            $sql .= " LIMIT  " . $limitFrom . "," . $limitTo . " ";
        }
        //echo $sql;exit;
        $resSelectProducts = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);       
        return $resSelectProducts;
    }
    public function getActiveFreeProducts($params) {
        extract($params);
        $currentLanguageID = $languageIDs['Current'];
        $limitFrom         = (isset($limitFrom) && $limitFrom > 0) ? $limitFrom : 0;
        $inclCalcRows      = (isset($limitTo) && $limitTo >= '0') ? "SQL_CALC_FOUND_ROWS" : "";
        $currDateTime      = isset($currDateTime) ? $currDateTime : '';
        $currDateTime      = ($currDateTime == "") ? "'" . date('Y-m-d') . "'" : "'" . $currDateTime . "'";        
        $currTime          = date('Y-m-d H:i:00');
        
        $sql = "SELECT product.productID FROM " . DB_PREFIX . "product_link_free AS linkFree INNER JOIN " . DB_PREFIX . "products   AS product  ON (linkFree.freeProductID = product.productID)
                LEFT JOIN 
                        " . DB_PREFIX . "brands AS brand 
                        ON (
                                brand.brandID = product.brandID 
                                AND 
                                status!='D'
                        )
               
                
                INNER JOIN 
                        " . DB_PREFIX . "product_details 	AS productDet 
                ON (
                        product.productID = productDet.productID 
                        AND 
                        productDet.languageID = " . $currentLanguageID . "
                        )
                INNER JOIN 
                                " . DB_PREFIX . "business AS bus 
                        ON (
                                product.businessID = bus.businessID AND bus.businessStatus = 'Active')";
       
        
        $sql .= " 
                INNER JOIN 
                        " . DB_PREFIX . "product_options AS productOpt 
                                ON (
                                        product.productID = productOpt.productID
                                        AND
                                        productOpt.productOptionStatus = 'Active' 
                                        AND 
                                        productOpt.productOptionDefault = 'Yes'
                                ) 
                
                LEFT JOIN 
                        " . DB_PREFIX . "product_combination AS proCom 
                        ON (
                                proCom.productID=product.productID 
                                AND 
                                proCom.status = 'A'
                        ) 
                
                INNER JOIN
                        " . DB_PREFIX . "attribute_set AS attrSet
                        ON attrSet.attributeSetID = product.attributeSetID";
        
    
        
        
        $sql .= " WHERE product.productStatus = 'Active'";
        $sql .= " AND linkFree.productID = " . (int) $selectedProductID . " ";
             
        $sql .= " AND product.productStatus!='Deleted' GROUP BY product.productID";       
        if (isset($limitTo) && $limitTo >= '0') {
            $sql .= " LIMIT  " . $limitFrom . "," . $limitTo . " ";
        }
        //echo $sql;exit;
        $resSelectProducts = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);       
        return $resSelectProducts;
    }
    //FUNCTION TO CHECK PRODUCT OPTION WITH LANGUAGE ID EXISTS
    function isProductOptionWithLanguageIDExists($languageID, $productOptionID) {
        $sql    = "
		SELECT
				1
		FROM
				`" . DB_PREFIX . "product_option_details`
		WHERE
				`languageID` = '" . $languageID . "' AND `productOptionID` = '" . $productOptionID . "' limit 1";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        if ($result)
            return true;
        else
            return false;
    }
    //END OF FUNCTION
    //FUNCTION TO CHECK PRODUCT LANGUAGE ID EXISTS
    function isProductWithLanguageIDExists($languageID, $productID) {
        $sql    = "
				SELECT
						1
				FROM
						`" . DB_PREFIX . "product_details`
				WHERE
						`languageID` = '" . $languageID . "' AND `productID` = '" . $productID . "' limit 1";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        if ($result)
            return true;
        else
            return false;
    }
    public function getOptionUserGroupPrice($productOptionID, $languageIDs = array()) {
        $sql = "
				SELECT
					varGroPri.userGroupID,
					specialPrice";
        if (!empty($languageIDs)) {
            $sql .= "
					,userGroupName";
        }
        $sql .= "
				FROM
					" . DB_PREFIX . "variant_group_price  AS varGroPri";
        if (!empty($languageIDs)) {
            $sql .= "
					INNER JOIN 
						" . DB_PREFIX . "user_group_details AS usrGroDet
							ON	(
								varGroPri.userGroupID = usrGroDet.userGroupID
								AND 
								languageID ='" . $languageIDs['Content'] . "'
							)
				";
        }
        $sql .= "		
				WHERE 
					productOptionID = '" . $productOptionID . "'
			";
        return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
    }
    public function getOptionTierPrice($productOptionID, $languageIDs = array()) {
        $sql = "
				SELECT
					varTiePri.userGroupID,
					quantity,
					allGroups,
					tierPrice";
        if (!empty($languageIDs)) {
            $sql .= "
					,userGroupName";
        }
        $sql .= "
				FROM
						" . DB_PREFIX . "variant_tier_price AS varTiePri";
        if (!empty($languageIDs)) {
            $sql .= "
					INNER JOIN 
						" . DB_PREFIX . "user_group_details AS usrGroDet
							ON	(
								varTiePri.userGroupID = usrGroDet.userGroupID
								AND 
								languageID ='" . $languageIDs['Content'] . "'
							)
				";
        }
        $sql .= "		
				WHERE 
					productOptionID = '" . $productOptionID . "'
			";
        return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
    }
    //FUNCTION TO List PRODUCT OPTIONS
    public function listProductOptions($languageIDs = NULL, $productID, $status = NULL, $default = NULL, $view = '', $slotID = '', $productOptionID = '', $purpose = "",$businessOptions="No",$selBusinessID=0) {
        $currentLanguageID = $languageIDs['Current'];
        if ($purpose == "basic") {
            $selectFields = "
						productOpt.productOptionID,
						productOpt.optionSKU,
						productOpt.productOptionQuantity,
						productOpt.productOptionRegularPrice,
						productOpt.productOptionProductPrice,
						productOpt.productOptionStatus,
                                                productOpt.bmwCode,
                                                productOpt.modelYear,
						productOptDet.productOptionName";
        } else {
            $selectFields = "
						productOpt.productOptionID,
						productOpt.productOptionID as option_id,
						productOpt.productOptionID as defaultOpion,
						productOptDet.productOptionName,
						productOpt.*,
						productOptDet.productOptionName,
						productOptDet.languageID,
						productOptDet.productOptionDetailsID,
						productOpt.soldQuantity AS optionSoldCount";
        }
        $sql = "
					SELECT
						" . $selectFields . "	
					FROM
						" . DB_PREFIX . "product_options AS productOpt
					LEFT JOIN
						" . DB_PREFIX . "product_option_details AS productOptDet
						ON productOpt.productOptionID=productOptDet.productOptionID
						AND productOptDet.languageID = '" . $currentLanguageID . "'
					WHERE
						productOpt.productID='" . (int) $productID . "'";
        ;
        if ($view != 'list') {
            $sql .= "
						AND (
							CAST(IF(productOpt.productQuantityUnlimited > 0,productOpt.productQuantityUnlimited,0)
					AS UNSIGNED)+(CAST(productOpt.productOptionQuantity AS UNSIGNED))>0
							) ";
        }
        if ($default != '') {
            $sql .= " 
						AND productOpt.productOptionDefault  = '" . $default . "'";
        }
        if ($status) {
            $sql .= " 
						AND productOpt.productOptionStatus  = '" . $status . "'";
        } else {
            $sql .= " 
						AND productOpt.productOptionStatus  != 'Delete'";
        }
        $sql .= "  
					ORDER BY
						productOptionDefault DESC,
						productOpt.productOptionID ";
        
        $result = $this->ObjDatabase->readValuesSlave($sql);
        if($businessOptions=="Yes"){
            $inventotyTrackLevel        =       $this->getInventoryTrackLevel($productID);
            foreach($result as $key=>$resOptions){
                if($inventotyTrackLevel=="Options"){
                    $combinationID          =       $this->getCombinationID($productID);
                }else{
                    $combinationID          =       0;
                }
                $resBusinessOptions = $this->getBusinessOptions($languageIDs,$resOptions['productOptionID'],-1,$inventotyTrackLevel,$combinationID,"",$selBusinessID);
                $result[$key]['businessOptions']  = $resBusinessOptions;
            }   
        }
        return $result;
    }
    
    public function getInventoryTrackLevel($productID,$productOptionID=0){
        if($productOptionID>0){
            $sqlSelect          =       "SELECT productID FROM ".DB_PREFIX."product_options WHERE productOptionID = '".$productOptionID."'";
            $productID          =       $this->ObjDatabase->getField($sqlSelect);
        }
        
        $sqlSelect          =       "SELECT InventoryTrackLevel FROM " . DB_PREFIX . "products WHERE productID = '".$productID."'";
        return $this->ObjDatabase->getField($sqlSelect);
    }
    
     public function getCombinationID($productID){
        $sqlSelect          =       "SELECT combinationID FROM " . DB_PREFIX . "product_combination WHERE productID = '".$productID."'
                                     ORDER BY combinationID ASC LIMIT 1";
        return $this->ObjDatabase->getField($sqlSelect);
    }
    
    public function listProductOptionIds($productID, $status = NULL) {
        $sql = "
				SELECT
						productOpt.productOptionID
				FROM
						" . DB_PREFIX . "product_options AS productOpt
				WHERE
						productOpt.productID='" . $productID . "'";
        if ($status) {
            $sql .= " AND productOpt.productOptionStatus  = '" . $status . "'";
        } else {
            $sql .= " AND productOpt.productOptionStatus  != 'Delete'";
        }
        $sql .= "  ORDER BY productOpt.productOptionID";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        return $result;
    }
	  public function getProductIDBySKU($sku,$type='') {
            if($sku!='') {
                $sqlGet     =   "select proOpt.productID,proOpt.productOptionID,pro.productUrl from dp_product_options proOpt join dp_products pro ON (proOpt.productID=pro.productID) where proOpt.optionSKU='".$sku."' AND proOpt.productOptionStatus!='Delete' and pro.productStatus!='Delete' LIMIT 0,1";                    
                $resGet     =   $this->ObjDatabase->readValue($sqlGet);
                if($type=='')
                    return   !empty($resGet)?$resGet['productID']:0;
                else
                    return $resGet;
            } else {
                return 0;
            }
        }
        public function getProductOptionId($productID) {
			$sql = "
					SELECT
							productOpt.productOptionID
					FROM
							" . DB_PREFIX . "product_options AS productOpt
					WHERE
							productOpt.productID='" . $productID . "'";
			
			$resGet     =   $this->ObjDatabase->readValue($sql);
            return   !empty($resGet)?$resGet['productOptionID']:0;
		}
    public function updateProductDetails($productID,$languageID,$productOptionID,$POST) {
        $productTitle              = $this->escape($POST['productTitle']);
        $productDescription        = $this->escape($POST['productDescription'], FALSE);
        $productShortDescription   = $this->escape($POST['productShortDescription'], FALSE);
        $productMetaTitle          = $this->escape($POST['productMetaTitle']);
        $productMetaDescription    = $this->escape($POST['productMetaDescription']);
        $productMetaKeywords       = $this->escape($POST['productMetaKeywords']);
       
        if ($this->isProductWithLanguageIDExists($languageID, $productID)) {
                $sql = "
		UPDATE
				`" . DB_PREFIX . "product_details`
		SET
				`productTitle`='" . $productTitle . "',
				`productDescription`='" . $productDescription . "',				
				`productMetaTitle`='" . $productMetaTitle . "',
				`productMetaDescription`='" . $productMetaDescription . "',
				`productMetaKeywords`='" . $productMetaKeywords . "',                               
				`productShortDescription`='" . $productShortDescription . "'
		WHERE
				`productID` = '" . $productID . "' AND `languageID`='" . $languageID . "'";
                $res = $this->ObjDatabase->setQuery($sql);
                $sqlUpd = "update `" . DB_PREFIX . "product_option_details` set productOptionName='".$productTitle."' where languageID='".$languageID."' and productOptionID='".$productOptionID."'";
                $resOpt = $this->ObjDatabase->setQuery($sqlUpd);
                return $res;
            } else {
                $productFinePrint  = '';
                $productHighlights = '';
                $productSizeChart  = '';
                $searchTags        = '';
                $sql = "INSERT INTO `" . DB_PREFIX . "product_details` (
			`languageID`,
			`productID`,
			`productTitle`,
			`productFinePrint`,
			`productHighlights`,
			`productDescription`,			
			`productMetaTitle`,
			`productMetaDescription`,
			 `productMetaKeywords`,
                         `productSizeChart`,
			 `searchTags`,
                         `productShortDescription`
		) VALUES (
			'" . $languageID . "',
			'" . $productID . "',
			'" . $productTitle . "',
			'" . $productFinePrint . "',
			'" . $productHighlights . "',
			'" . $productDescription . "',			
			'" . $productMetaTitle . "',
			'" . $productMetaDescription . "',
			'" . $productMetaKeywords . "',
                        '" . $productSizeChart . "',
			'" . $searchTags . "',
                        '" . $productShortDescription . "'
		)";
                $res = $this->ObjDatabase->setQuery($sql);
                $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_option_details`
				 (`productOptionID`,
				  `languageID`,
				  `productOptionName`
				 )
				 VALUES
				 ('" . $productOptionID . "',
				  '" . $languageID . "',
				  '" . $productTitle . "'
				 )");
                return $res;
            }
    }            
    //Check product exists
    //
    //SAVING PRODUCT DETAILS(ADD/EDIT)
    public function saveProduct($languageIDs, $POST, $productID = NULL, $productRequestID = '', $adminApprove = true,$import='',$autoline='') {
        
       
        $ObjReqProduct                = new ProductRequestModel();
        $languageID                   = $languageIDs['Current'];
        $productTypeID                = '1';
        $businessID                   = isset($POST['businessID']) ? $POST['businessID'] :1;
        $brandID                      = $this->escape($POST['brandID']);
        $taxClassID                   = isset($POST['taxClassID'])?$POST['taxClassID']:0;
        $productDefaultCurrency       = $POST['productDefaultCurrency'];
        $productStartTime             = '';
        $productEndTime               = '';
        $appendResetProductTippedDate = '';
        $productTypeKey               = isset($productTypeKey) ? $productTypeKey : '';
        $saveFrom                     = isset($POST['saveFrom']) ? $POST['saveFrom'] : '';
        $bodyStyle                    = isset($POST['bodyStyle']) ? $POST['bodyStyle'] : '';            
        
        if ($taxClassID)
            $isTaxable = "Yes";
        else
            $isTaxable = "No";
        $productTimeZone = $POST['productTimeZone'];
        
        $productStartTime          =       '0000-00-00';
        $productEndTime            =       '0000-00-00';
        $layoutActiveFrom          = (isset($POST['layoutActiveFrom']) && $POST['layoutActiveFrom'] != '') ? date("Y-m-d", strtotime($POST['layoutActiveFrom'])) : '0000-00-00';
        $layoutActiveTo            = (isset($POST['layoutActiveTo']) && $POST['layoutActiveTo'] != '') ? date("Y-m-d", strtotime($POST['layoutActiveTo'])) : '0000-00-00';
        $productDetailsLayout      = (isset($POST['productDetailsLayout'])) ? $POST['productDetailsLayout'] : '';
        $productMinBuyLimit        = $POST['productMinBuyLimit'];
        $productMaxBuyLimit        = (!empty($POST['productMaxBuyLimit'])) ? $POST['productMaxBuyLimit'] : 'NULL';
        $productMinQntyReqToTipp   = isset($POST['productMinQntyReqToTipp']) ? $POST['productMinQntyReqToTipp'] : '';
        $productCommissionRate     = (isset($POST['productCommissionRate'])) ? $POST['productCommissionRate'] : '';
        $productUseGlobalCommision = isset($_POST['productUseGlobalCommision']) ? $_POST['productUseGlobalCommision'] : '';
        $productServiceFee         = (isset($POST['productServiceFee'])) ? $POST['productServiceFee'] : '';
        $measurementLength         = $POST['measurementLength'];
        $measurementWeight         = $POST['measurementWeight'];
        $productQuantityNotifyAt   = (!empty($POST['productQuantityNotifyAt'])) ? $POST['productQuantityNotifyAt'] : 1;
        $productImage              = $POST['productImage'];
        $productShowNosBought      = isset($POST['productShowNosBought']) ? $POST['productShowNosBought'] : '';
        $baseProduct               = isset($POST['baseProduct'])?$POST['baseProduct']:'No';
        $productStatus             = isset($POST['productStatus']) ? $POST['productStatus'] : 'Active'; 
        $inventoryTrackLevel       = $POST['InventoryTrackLevel'];
        $productMaxGiftBuy         = isset($POST['productMaxGiftBuy']) ? $POST['productMaxGiftBuy'] : 'NULL';
        $productTitle              = $this->escape(preg_replace('/\s+/', ' ', $POST['productTitle']));
        $productFinePrint          = isset($POST['productFinePrint']) ? $this->escape($POST['productFinePrint'], FALSE) : '';
        $productHighlights         = $this->escape($POST['productHighlights'], FALSE);
        $productDescription        = $this->escape($POST['productDescription'], FALSE);
        $productShortDescription   = $this->escape($POST['productShortDescription'], FALSE);
        $productMetaTitle          = $this->escape($POST['productMetaTitle']);
        $productMetaDescription    = $this->escape($POST['productMetaDescription']);
        $productMetaKeywords       = $this->escape($POST['productMetaKeywords']);
        $productUrl                = $this->escape($POST['productUrl']);
        $taxPayableToBusiness      = isset($POST['taxToBusiness']) ? $POST['taxToBusiness'] : '';
        $outofStockStatus          = isset($POST['outofStockStatus']) ? $POST['outofStockStatus'] : '';
        $showCountTimer            = isset($POST['showCountTimer']) ? $this->escape($POST['showCountTimer']) : '';
        $enableSizeChart           = (isset($POST['enableSizeChart']) && !empty($POST['enableSizeChart'])) ? $this->escape($POST['enableSizeChart']) : 'No';
        $enableBoyBoxSel           = (isset($POST['enableBoyBoxSel']) && !empty($POST['enableBoyBoxSel'])) ? $this->escape($POST['enableBoyBoxSel']) : 'No';
        $businessOptionsGroup      = (isset($POST['businessOptionsGroup']) && !empty($POST['businessOptionsGroup'])) ? $POST['businessOptionsGroup'] : array();
		$productSizeChart            = isset($POST['productSizeChart']) ? $this->escape($POST['productSizeChart']) : '';
        $setAsProductDeal            = (isset($POST['setAsProductDeal']) && !empty($POST['setAsProductDeal'])) ? $this->escape($POST['setAsProductDeal']) : 'No';        
        $sellAsBatch            = (isset($POST['sellAsBatch']) && !empty($POST['sellAsBatch'])) ? $this->escape($POST['sellAsBatch']) : 'No';
        if($sellAsBatch!='No'){
            $batchType = (isset($POST['batchType']) && !empty($POST['batchType'])) ? $this->escape($POST['batchType']) : '';
            $qtyPerBatch = (isset($POST['qtyPerBatch']) && !empty($POST['qtyPerBatch'])) ? $this->escape($POST['qtyPerBatch']) : '';
        }else{
            $batchType = '';
            $qtyPerBatch = '';
        }
        if($POST['isProductDeal']=='Yes'){
            $showCountTimer='Yes';
        }
        $currDate = date('m/d/Y');
       
        if($setAsProductDeal == "Yes" && (strtotime($POST['dealStartTime'])<=strtotime($currDate)) && (strtotime($POST['dealEndTime'])>=strtotime($currDate)))
        {
            $isProductDeal = "Yes";
        }else{
            $isProductDeal = "No";
        }
        if($setAsProductDeal!="Yes"){
            $dealStartTime          =       '0000-00-00';
            $dealEndTime            =       '0000-00-00';
            $dealDiscountType       =       '';
            $dealDiscount           =       '';
            $dealMaxBuyLimit        =       'NULL';
            $dealSetBy              =       '';
        }else{
            if ($POST['dealStartTime']) {
                $dealStartTime      =       date("Y-m-d", strtotime($POST['dealStartTime']));
            }
            if ($POST['dealEndTime']){
                $dealEndTime        =       date("Y-m-d", strtotime($POST['dealEndTime']));
            }
            $dealDiscountType       =       isset($POST['dealDiscountType'])?$this->escape($POST['dealDiscountType']):'';
            $dealDiscount           =       isset($POST['dealDiscount'])?$this->escape($POST['dealDiscount']):'';
            $dealMaxBuyLimit        =       (isset($POST['dealMaxBuyLimit']) && $POST['dealMaxBuyLimit']!='')?$POST['dealMaxBuyLimit']:'NULL';
            if(isset($POST['prevDealSetBy']) && $POST['prevDealSetBy']!=""){
                $dealSetBy          =       $POST['prevDealSetBy'];
            }else{
                $dealSetBy          =       'products';
            }
            
        }
        		
        $featuredStatus            = isset($POST['featuredStatus']) ? $this->escape($POST['featuredStatus']) : '';
        $financeAvail              = isset($POST['financeAvail']) ? $this->escape($POST['financeAvail']) : '';
        $leaseAvail                = isset($POST['leaseAvail']) ? $this->escape($POST['leaseAvail']) : '';
        $searchTags                = (isset($_POST['as_values_searchTags'])) ? $this->escape(substr($_POST['as_values_searchTags'], 2, -1)) : '';
        if (isset($POST['searchTags'])) {
            $tagsArray = @explode(',', $searchTags);
            if (!in_array($POST['searchTags'], $tagsArray))
                $searchTags .= (!empty($searchTags)) ? ',' . $POST['searchTags'] : $POST['searchTags'];
        }
        $shippingSetting       = isset($POST['shippingSetting']) ? $this->escape($POST['shippingSetting']) : '';
        $shippingOrigin        = isset($POST['shippingOrigin']) ? $this->escape($POST['shippingOrigin']) : '';
        $attributeSetID        = isset($POST['attributeSetID']) ? $this->escape($POST['attributeSetID']) : 1;
        $showQuantityAvailable = $this->escape($POST['showQuantityAvailable']);
        $purchasePopularity    = isset($POST['purchasePopularity']) ? $this->escape($POST['purchasePopularity']) : '';
        $popularity            = isset($POST['popularity']) ? $this->escape($POST['popularity']) : '';
        if (isset($POST['productAddedBy']) || $productRequestID > 0) {
            $productAddedBy = '1';
        } else {
            $productAddedBy = '0';
        }
        if (isset($POST['enableMultipleOptions']) && $POST['enableMultipleOptions'] == 'Yes') {
            $enableMultipleOptions = 'Yes';
        } else {
            $enableMultipleOptions = 'No';
        }
        if (isset($POST['taxToBusiness']) && $POST['taxToBusiness'] == 'Yes')
            $taxPayableToBusiness = 'Yes';
        else
            $taxPayableToBusiness = 'No';
        $hidshippingStatus     = $POST['hidshippingStatus'];
        $productOptionQuantity = isset($POST['productOptionQuantity']) ? $POST['productOptionQuantity'] : '';
        if ($productOptionQuantity == "")
            $productQuantityUnlimited = "1";
        else
            $productQuantityUnlimited = "0";
        if (!empty($productRequestID)) {
            //$attributeSetID = $POST['hidAttrSetID'];
            $reqLangIDs     = $ObjReqProduct->get_request_langIDs($productRequestID);
            $contentLang    = $languageIDs['Content'];
            $reqFetchLang   = array_diff($reqLangIDs, array(
                $contentLang
            ));
        } 
        
        if (isset($POST['productReturnable']) && $POST['productReturnable'] == 'Yes') {
            $productReturnable   = 'Yes';
            $productReturnPeriod = $POST['returnPeriod'];
        } else {
            $productReturnable   = 'No';
            $productReturnPeriod = '';
        }
        $productDispatchTime = isset($POST['productDispatchTime']) ? $POST['productDispatchTime'] : '';
        if (!$productID) {
            $oldProductID = '';
            if($import!='' && $POST['productUrl']!='') {
                 $sqlGet     =   "select productID from dp_product_options where optionSKU='".$POST['skuRef']."' AND productOptionStatus!='Delete' LIMIT 0,1";                    
                 $resDet     =   $this->ObjDatabase->readValue($sqlGet);                 
                 if(!empty($resDet)) {
                    $sqlDel = "Delete from `" . DB_PREFIX . "products` where productID='".$resDet['productID']."'";
                    $this->ObjDatabase->setQuery($sqlDel);
                    $this->ObjDatabase->setQuery("Delete from `" . DB_PREFIX . "product_details` where productID='".$resDet['productID']."'");
                    $sqlDelOpt = "Delete from `" . DB_PREFIX . "product_option_details` optdet join `" . DB_PREFIX . "product_options` opt ON (optdet.productOptionID=opt.productOptionID) where opt.productID='".$resDet['productID']."'";
                    $this->ObjDatabase->setQuery($sqlDelOpt);
                    $this->ObjDatabase->setQuery("Delete from `" . DB_PREFIX . "product_to_category` where productID='".$resDet['productID']."'");
                    $this->ObjDatabase->setQuery("Delete from `" . DB_PREFIX . "product_options` where productID='".$resDet['productID']."'");
                    $this->ObjDatabase->setQuery("Delete from `" . DB_PREFIX . "url_rewrite` where objectID='".$resDet['productID']."' and type='product'");
                    $this->ObjDatabase->setQuery("DELETE ship.*, del.* 
							FROM `" . DB_PREFIX . "shipping_to_product` ship
							LEFT JOIN
							`" . DB_PREFIX . "product_to_shipping_deliveryzone` del
							ON del.shippingtoproductID = ship.shippingtoproductID 
							WHERE ship.productID = '" . $resDet['productID']."'");
                 }
                
            }
            $sqlsaveProduct = "INSERT INTO `" . DB_PREFIX . "products`
		(
				`productTypeID`,
				`businessID`,
				`brandID`,
				`isProductDeal`,
				`dealStartTime`,
				`dealEndTime`,
                                `dealDiscountType`,
				`dealDiscount`,
				`dealMaxBuyLimit`,
                                `dealSetBy`,
				`isTaxable`,
				`taxClassID`,
				`productDefaultCurrency`,
				`measurementLength`,
				`measurementWeight`,
				`productQuantityNotifyAt`,
				`taxPayableToBusiness`,
				`multiOptionsAvailable`,
				`attributeSetID`,
				`productTimeZone`,
				`productStartTime`,
				`productEndTime`,
				`productMinBuyLimit`,
				`productMaxBuyLimit`,
				`productMaxGiftBuy`,
				`productMinQntyReqToTipp`,
				`productCommissionRate`,
				`productUseGlobalCommision`,				
				`productServiceFee`,				
				`productShowNosBought`,
				`productImage`,
				`productStatus`,
				`InventoryTrackLevel`,
				`outofStockStatus`,
				`productCreatedDate`,
				`shippingStatus`,				
				`showCountTimer`,
				`featuredStatus`,
				`productUrl`,
				`shippingSetting`,
				`productAddedBy`,
				`shippingOrigin`,
				`showQuantityAvailable`,
				`productReturnable`,
				`productReturnPeriod`,
				`layoutActiveFrom`,
				`layoutActiveTo`,
				`productDetailsLayout`,
				`enableSizeChart`,
                                `setAsProductDeal`,
                                `enableBuybox`,
                                `sellAsBatch`,
                                `batchType`,
                                `qtyPerBatch`,
                                `financeAvail`,
                                `leaseAvail`,
                                `bodyStyle`
                                
		)
		VALUES
		(
				'" . $productTypeID . "',
				'" . $businessID . "',
				'" . $brandID . "',
				'" . $isProductDeal . "',
				'" . $dealStartTime . "',
				'" . $dealEndTime . "',
                                '" . $dealDiscountType . "',
				'" . $dealDiscount . "',
				" . $dealMaxBuyLimit . ",
                                '" .  $dealSetBy . "',
				'" . $isTaxable . "',
				'" . $taxClassID . "',
				'" . $productDefaultCurrency . "',
				'" . $measurementLength . "',
				'" . $measurementWeight . "',
				'" . $productQuantityNotifyAt . "',						
				'" . $taxPayableToBusiness . "',
				'" . $enableMultipleOptions . "',
				'" . $attributeSetID . "',
				'" . $productTimeZone . "',
				'" . $productStartTime . "',
				'" . $productEndTime . "',
				'" . $productMinBuyLimit . "',
				" . $productMaxBuyLimit . ",
				" . $productMaxGiftBuy . ",
				'" . $productMinQntyReqToTipp . "',
				'" . $productCommissionRate . "',
				'" . $productUseGlobalCommision . "',				
				'" . $productServiceFee . "',
				'" . $productShowNosBought . "',
				'" . $productImage . "',
				'" . $productStatus . "',
				'" . $inventoryTrackLevel . "',
				'" . $outofStockStatus . "',
				NOW(),
				'" . $hidshippingStatus . "',				
				'" . $showCountTimer . "',
				'" . $featuredStatus . "',
				'" . $productUrl . "',
				'" . $shippingSetting . "',
				'" . $productAddedBy . "',
				'" . $shippingOrigin . "',
				'" . $showQuantityAvailable . "',
				'" . $productReturnable . "',
				'" . $productReturnPeriod . "',
				'" . $layoutActiveFrom . "',
				'" . $layoutActiveTo . "',
				'" . $productDetailsLayout . "',
				'" . $enableSizeChart . "',
                                '" . $setAsProductDeal . "',
                                '" . $enableBoyBoxSel ."',
                                '".$sellAsBatch."',
                                '".$batchType."',
                                '".$qtyPerBatch."',
                                '" .$financeAvail. "',
                                '" .$leaseAvail. "',
                                '" .$bodyStyle. "'    
		)";
            $this->ObjDatabase->setQuery($sqlsaveProduct);
            
            $lastInsertProductID = $this->ObjDatabase->getInsertId();
            $flddesc       = '';
            $flddescvalue  = '';
            if($autoline!='') {
                $flddesc = ',`productShortDescKey`';
                $flddescvalue = ",'".$this->escape($POST['shortdesckey'])."'"; 
            }
            $sqlDetails          = "INSERT INTO `" . DB_PREFIX . "product_details`
				(
				`languageID`,
				`productID`,
				`productTitle`,
				`productFinePrint`,
				`productHighlights`,
				`productDescription`,				
				`productMetaTitle`,
				`productMetaDescription`,
				`productMetaKeywords`,
				`searchTags`,
                                `productShortDescription`
                                ".$flddesc."
				)
		VALUES";
            if (!empty($productRequestID)) {
                if (count($reqFetchLang) > 0) {
                    $obsolete_idstr = implode("','", $reqFetchLang);
                    $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_details` (
			`languageID`,
			`productID`,
			`productTitle`,
			`productFinePrint`,
			`productHighlights`,
			`productDescription`,				
			`productMetaTitle`,
			`productMetaDescription`,
			`productMetaKeywords`,
			`searchTags`,
                        `productShortDescription`
			) 
			SELECT 
				`languageID`,
				'" . $lastInsertProductID . "',
				`productTitle`,
				`productFinePrint`,
				`productHighlights`,
				`productDescription`,				
				`productMetaTitle`,
				`productMetaDescription`,
				`productMetaKeywords`,
				`searchTags`,
                                `productShortDescription`
			FROM 
						`" . DB_PREFIX . "product_request_details`
			WHERE 
				`productRequestID`='" . $productRequestID . "' AND languageID IN  ('" . $obsolete_idstr . "')");
                }
                foreach ($languageIDs['AllList'] as $langIds) {
                    if (!(in_array($langIds, $reqFetchLang)) || empty($reqFetchLang)) {
                        $insertval[] = "(
				'" . $langIds . "',
				'" . $lastInsertProductID . "',
				'" . $productTitle . "',
				'" . $productFinePrint . "',
				'" . $productHighlights . "',
				'" . $productDescription . "',				
				'" . $productMetaTitle . "',
				'" . $productMetaDescription . "',
				'" . $productMetaKeywords . "',
				'" . $searchTags . "',
                                '" . $productShortDescription . "')";
                    }
                }
                $sql = $sqlDetails . implode(",", $insertval);
                $this->ObjDatabase->setQuery($sql);
            } else {
                foreach ($languageIDs['AllList'] as $langIds) {
                    $sqlval[] = "(
				'" . $langIds . "',
				'" . $lastInsertProductID . "',
				'" . $productTitle . "',
				'" . $productFinePrint . "',
				'" . $productHighlights . "',
				'" . $productDescription . "',				
				'" . $productMetaTitle . "',
				'" . $productMetaDescription . "',
				'" . $productMetaKeywords . "',
				'" . $searchTags . "','" . $productShortDescription . "'".$flddescvalue.")";
                }               
                $sql = $sqlDetails . implode(",", $sqlval);               
                $this->ObjDatabase->setQuery($sql);
            }
            $productOptionCount = isset($POST["productOptionCount"]) ? $POST["productOptionCount"] : '';
            $options            = $POST['productOptionsGroup'];
            if (isset($productRequestID) && $productRequestID > 0) {
                $languageIDs['Fetch'] = $reqFetchLang;
                $this->saveProductRequestOptions($languageIDs, $options, $lastInsertProductID, $enableMultipleOptions, $productRequestID);
                $reqShipInfo              = $this->getRequestShipInfo($productRequestID);
                $reqShipInfo['productID'] = $lastInsertProductID;
                $this->updateShippingSettings($reqShipInfo);
                $this->saveRequestToProductID($lastInsertProductID, $productRequestID);
            }
            if ($productRequestID == '') {
               
                $this->saveProductOptions($languageIDs, $options, $lastInsertProductID, $productTypeKey, $enableMultipleOptions,$setAsProductDeal,$enableBoyBoxSel,$inventoryTrackLevel,$productStatus,$businessID,$saveFrom,$autoline);
            }
            
            if (!empty($POST['productCategoryID']) && $import=='') {
                $this->saveProductToCategory($lastInsertProductID, $POST,$autoline);
            }
            return $lastInsertProductID;
        } else {
            
            /*if($attributeSetID>0 && $attributeSetID!=$POST['hidAttrSetID'] && $POST['hidAttrSetID']>0) {
                //delete existing product attribute values
                 $this->ObjDatabase->setQuery("DELETE attr.*, attrDet.* 
							FROM `" . DB_PREFIX . "product_attribute_values` attr
							LEFT JOIN
							`" . DB_PREFIX . "product_attribute_value_details` attrDet
							ON attr.attrValueID = attrDet.attrValueID 
							WHERE attr.productID = " . $productID);
            }*/
            
           
                                if($autoline!='') {
                                    $sqlUpdateProducts = "UPDATE
				`" . DB_PREFIX . "products`
                                    SET
				`productTypeID`='" . $productTypeID . "',
				`brandID`='" . $brandID . "',				
				`productDefaultCurrency`='" . $productDefaultCurrency . "',
				`productUrl`='" . $productUrl . "' ,bodyStyle='".$bodyStyle."'";
                                } else {
                                    if (isset($POST['imageFlag']) && $POST['imageFlag'] == 1)
                                                $this->deleteProductImage($productID);
                                    $sqlUpdateProducts = "UPDATE
				`" . DB_PREFIX . "products`
		SET
				`productTypeID`='" . $productTypeID . "',
                                `shippingSetting`    ='" . $shippingSetting . "',   
                                `attributeSetID`='" . $attributeSetID . "',    
				`businessID`='" . $businessID . "',
				`brandID`='" . $brandID . "',
				`isProductDeal`='" . $isProductDeal . "',
				`dealStartTime`='" . $dealStartTime . "',
				`dealEndTime`='" . $dealEndTime . "',
                                `dealDiscountType`='" . $dealDiscountType . "',
				`dealDiscount`='" . $dealDiscount . "',
				`dealMaxBuyLimit`=" . $dealMaxBuyLimit . ",
                                `dealSetBy`='" . $dealSetBy . "',
				`isTaxable`='" . $isTaxable . "', 
				`taxClassID`='" . $taxClassID . "',
				`taxPayableToBusiness`='" . $taxPayableToBusiness . "',
				`productDefaultCurrency`='" . $productDefaultCurrency . "',
				`measurementLength`='" . $measurementLength . "',
				`measurementWeight`='" . $measurementWeight . "',
				`productQuantityNotifyAt`='" . $productQuantityNotifyAt . "',
				`showQuantityAvailable`='" . $showQuantityAvailable . "',	
				`purchasePopularity`='" . $purchasePopularity . "',
				`popularity`='" . $popularity . "',
				`productTimeZone`='" . $productTimeZone . "',
				`productStartTime`='" . $productStartTime . "', 
				`productEndTime`='" . $productEndTime . "',
				`productMinBuyLimit`='" . $productMinBuyLimit . "', 
				`productMaxBuyLimit`=" . $productMaxBuyLimit . ",
				`productMaxGiftBuy` = " . $productMaxGiftBuy . ", 
				`productMinQntyReqToTipp`='" . $productMinQntyReqToTipp . "',
				`productCommissionRate`='" . $productCommissionRate . "',
				`productUseGlobalCommision`='" . $productUseGlobalCommision . "',
				`multiOptionsAvailable`='" . $enableMultipleOptions . "',
				`productServiceFee`='" . $productServiceFee . "',
				`productUrl`='" . $productUrl . "',
				`outofStockStatus`='" . $outofStockStatus . "', ";
                                    $sqlUpdateProducts .= " 
                                        `productImage`='" . $productImage . "',
				`productShowNosBought`='" . $productShowNosBought . "',
				`productImage`='" . $productImage . "',
				`productStatus`='" . $productStatus . "',
				`InventoryTrackLevel`='" . $inventoryTrackLevel . "',
				`shippingStatus`='" . $hidshippingStatus . "',
				`featuredStatus`='" . $featuredStatus . "',
				`showCountTimer`='" . $showCountTimer . "' " . $appendResetProductTippedDate . ",
				`productReturnable`='" . $productReturnable . "',
				`productReturnPeriod`='" . $productReturnPeriod . "',
				`layoutActiveFrom`	=	'" . $layoutActiveFrom . "',
				`layoutActiveTo`	=	'" . $layoutActiveTo . "',
				`productDetailsLayout` = '" . $productDetailsLayout . "',
				`enableSizeChart` = '" . $enableSizeChart  . "',
				`sizeChart` = '" . $productSizeChart . "',
                                `setAsProductDeal` = '".$setAsProductDeal."',
                                `enableBuybox` = '".$enableBoyBoxSel."',
                                `sellAsBatch`='".$sellAsBatch."',
                                `batchType`='".$batchType."',
                                `qtyPerBatch`='".$qtyPerBatch."',`financeAvail`='" .$financeAvail. "',
                                `leaseAvail`='" .$leaseAvail. "',bodyStyle='".$bodyStyle."'";
                                }
				
            $sqlUpdateProducts .= " WHERE `productID` = '" . $productID . "'";
            $this->ObjDatabase->setQuery($sqlUpdateProducts);
            $this->destroyProductToCategory($productID);
            if (!empty($POST['productCategoryID'])) {
                $this->saveProductToCategory($productID, $POST,$autoline);
            }

            if ($this->isProductWithLanguageIDExists($languageID, $productID)) {
				if($autoline!='') {
					$this->ObjDatabase->setQuery("
		UPDATE
				`" . DB_PREFIX . "product_details`
		SET
				`productTitle`='" . $productTitle . "',
				`productFinePrint`='" . $productFinePrint . "',
				`productHighlights`='" . $productHighlights . "',
				`productDescription`='" . $productDescription . "',				
				`productSizeChart`='" . $productSizeChart . "',
				`searchTags`='" . $searchTags . "',`productShortDescription`='" . $productShortDescription . "'
		WHERE
				`productID` = '" . $productID . "' AND `languageID`='" . $languageID . "'");
				} else {
                $this->ObjDatabase->setQuery("
		UPDATE
				`" . DB_PREFIX . "product_details`
		SET
				`productTitle`='" . $productTitle . "',
				`productFinePrint`='" . $productFinePrint . "',
				`productHighlights`='" . $productHighlights . "',
				`productDescription`='" . $productDescription . "',				
				`productMetaTitle`='" . $productMetaTitle . "',
				`productMetaDescription`='" . $productMetaDescription . "',
				`productMetaKeywords`='" . $productMetaKeywords . "',
                                `productSizeChart`='" . $productSizeChart . "',
				`searchTags`='" . $searchTags . "',`productShortDescription`='" . $productShortDescription . "'
		WHERE
				`productID` = '" . $productID . "' AND `languageID`='" . $languageID . "'");
				}

            } else {
                $tempLangArr[] = $languageIDs['Current'];
            }
            if(!empty($tempLangArr)) {
                //echo "<pre>";print_r($languageIDs['AllList']);exit;
                foreach ($tempLangArr as $langIds) {
                    if ($this->isProductWithLanguageIDExists($langIds, $productID)) {
                        $upddesc = ($autoline!='')?",productShortDescKey = '".$this->escape($POST['shortdesckey'])."'":'';
                        $this->ObjDatabase->setQuery("
                        UPDATE
                                        `" . DB_PREFIX . "product_details`
                        SET
                                        `productTitle`='" . $productTitle . "',
                                        `productFinePrint`='" . $productFinePrint . "',
                                        `productHighlights`='" . $productHighlights . "',
                                        `productDescription`='" . $productDescription . "',				
                                        `productMetaTitle`='" . $productMetaTitle . "',
                                        `productMetaDescription`='" . $productMetaDescription . "',
                                        `productMetaKeywords`='" . $productMetaKeywords . "',
                                        `productSizeChart`='" . $productSizeChart . "',
                                        `searchTags`='" . $searchTags . "',`productShortDescription`='" . $productShortDescription . "' ".$upddesc."

                        WHERE
                                        `productID` = '" . $productID . "' AND `languageID`='" . $langIds . "'"); 
                    } else {
                        $flddesc       = '';
                        $flddescvalue  = '';
                        if($autoline!='') {
                            $flddesc = ',`productShortDescKey`';
                            $flddescvalue = ",'".$this->escape($POST['shortdesckey'])."'"; 
                        }
                        $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_details` (
                                `languageID`,
                                `productID`,
                                `productTitle`,
                                `productFinePrint`,
                                `productHighlights`,
                                `productDescription`,			
                                `productMetaTitle`,
                                `productMetaDescription`,
                                 `productMetaKeywords`,
                                 `productSizeChart`,
                                 `searchTags`,
                                 `productShortDescription` ".$flddesc."
                        ) VALUES (
                                '" . $langIds . "',
                                '" . $productID . "',
                                '" . $productTitle . "',
                                '" . $productFinePrint . "',
                                '" . $productHighlights . "',
                                '" . $productDescription . "',			
                                '" . $productMetaTitle . "',
                                '" . $productMetaDescription . "',
                                '" . $productMetaKeywords . "',
                                '" . $productSizeChart . "',
                                '" . $searchTags . "',
                                '" . $productShortDescription . "' ".$flddescvalue."
                        )");
                    }
                }
            }
            $productOptionCount = isset($POST["productOptionCount"]) ? $POST["productOptionCount"] : '';
            $options            = isset($POST['productOptionsGroup']) ? $POST['productOptionsGroup'] : '';
            $this->saveProductOptions($languageIDs, $options, $productID, $productTypeKey, $enableMultipleOptions,$setAsProductDeal,$enableBoyBoxSel,$inventoryTrackLevel,$productStatus,$businessID,$saveFrom,$autoline);
            if ($enableMultipleOptions == 'Yes')
                $this->deleteExistCombo($productID);
            return $productID;
        }
    }
    //END OF FUNCTION
    //FUNCTION TO SAVE RELATED PRODUCTS
    public function saveProductProductIDs($productID, $selproductIDs) {
        if ($productID > 0) {
            /*saving super admin products*/
            $this->destroyProductProducts($productID);
            if (!empty($selproductIDs) && $selproductIDs[0] != '') {
                $sql = "INSERT INTO " . DB_PREFIX . "product_link_relation(
										productID,
										relatedProductID,
										priority
								) values";
                $i   = 0;
                foreach ($selproductIDs as $Ids) {
                    $i++;
                    $sqlval[] = "(
				'" . $productID . "',				
				'" . $Ids . "',
				'" . $i . "')";
                }
                $sql    = $sql . implode(",", $sqlval);
                $result = $this->ObjDatabase->setQuery($sql);
            }
        }
        return 1;
    }
    //END OF FUNCTION
    //FUNCTION TO DESTROY RELATED PRODUCTS
    public function destroyProductProducts($productID) {
        $sql    = "	DELETE
								FROM
						" . DB_PREFIX . "product_link_relation
						WHERE
						`productID` ='" . $productID . "' ";
        $result = $this->ObjDatabase->setQuery($sql);
        return $result;
    }
    //END OF FUNCTION
    //FUNCTION TO SAVE PRODUCT TO CATEGORY
    public function saveProductToCategory($productID, $POST,$autoline='') {
	   	 
		foreach($POST['productCategoryID'] as $catIDs){
                    
		    $cat = ($autoline=='')?substr($catIDs, strpos($catIDs, ",") + 1):$catIDs;		
			$productCatIDs = explode(",",$cat);
		}
        /*for ($z = 0; $z < count($POST['productCategoryID']); $z++) {
			if($POST['productCategoryID'][$z]>0){
				$this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_to_category`
					(`productID`, `productCategoryID`) VALUES ('" . $productID . "', '" . $POST['productCategoryID'][$z] . "')");
			}
        }*/
                
		foreach($productCatIDs as $catID){
		
		$this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_to_category`
					(`productID`, `productCategoryID`) VALUES ('" . $productID . "', '" . $catID . "')");
		}
	
    }
    //END OF FUNCTION
    //FUNCTION TO DESTROY PRODUCT TO CATEGORY
    public function destroyProductToCategory($productID) {
        $sqlProductTocategory = "DELETE FROM  " . DB_PREFIX . "product_to_category WHERE `productID` =" . $productID;
        $resProductTocategory = $this->ObjDatabase->setQuery($sqlProductTocategory);
        return $resProductTocategory;
    }
    //END OF FUNCTION
    
    //FUNCTION TO SAVE PRODUCT OPTIONS
    public function saveProductOptions($languageIDs, $options, $productID, $productTypeKey = '', $enableMultipleOptions = 'No',$setAsProductDeal='No',$enableBoyBoxSel="No",$inventoryTrackLevel="",$productStatus="",$businessID=0,$saveFrom='',$autoline='') {
        
        $languageID        = $languageIDs['Current'];
        $DefaultLanguageID = $languageIDs['Default'];
        $optionsToInsert   = array();
        $optionsToDelete   = array();
        $optionsToUpdate   = array();
        
        $prodOptCount      = 0;
        
        $optionDefaultVal  = 0; 
        if($autoline=='') {
            foreach ($options as $optionValue){
                $pdtOptDef     = isset($optionValue['defaultOpion']) ? $this->escape($optionValue['defaultOpion']) : '';
                if($pdtOptDef=="Yes"){
                    $optionDefaultVal = $optionDefaultVal+1;
                }
            }
        }
       
        foreach ($options as $rowHash => $row) // Traverse through all posted options
            {
            $option_id    = (int) $row['option_id'];
            $option_count = (int) $row['realOptionCount'];
            
            if ($row['is_delete'] == 1) // Option is deleted
                {
                if ($row['option_id'] > -1) // Option already present in db. Delete it
                    {
                    $this->ObjDatabase->setQuery("
				DELETE
						FROM
						`" . DB_PREFIX . "product_option_details`
				WHERE
						`productOptionID`='" . $row['option_id'] . "'");
                    $this->ObjDatabase->setQuery("
				DELETE
				FROM
						`" . DB_PREFIX . "product_options`
				WHERE
						`productOptionID`='" . $row['option_id'] . "'");
                }
            } else {
                if($productStatus=="Pending" || $saveFrom=="business"){
                    $businessOptionsGroup[0]['assignBusinessID']            =       $businessID;
                    $businessOptionsGroup[0]['hiddenBusinessID']            =       $businessID;
                    $businessOptionsGroup[0]['businessOptionDefault']       =       "Yes";
                    $businessOptionsGroup[0]['group_price']                 =       $row['group_price'];
                    $businessOptionsGroup[0]['businessOptionReqPrice']      =       $row['productOptionRegularPrice'];
                    $businessOptionsGroup[0]['businessOptionSalePrice']     =       $row['productOptionProductPrice'];
                    $businessOptionsGroup[0]['businessOptionDealPrice']     =       0;
                    $businessOptionsGroup[0]['businessQuantity']            =       $row['productOptionQuantity'];
                    $businessOptionsGroup[0]['businessOptionSKU']           =       $row['optionSKU'];
                    $businessOptionsGroup[0]['businessWareHouse']           =       "";
                    $businessOptionsGroup[0]['businessDispatchTime']        =       "";
                    $businessOptionsGroup[0]['busProductStatus']            =       "Active";
                    
                }else{
                    $businessOptionsGroupArr   = isset($row['businessOptionsGroup']) ? $row['businessOptionsGroup'] : array();
                    $businessOptionsGroup      = array();
                    if($enableBoyBoxSel=="No" || $enableBoyBoxSel==""){
                        $businessOptionsGroup[0]  =  $businessOptionsGroupArr[0];
                    }else{
                        $businessOptionsGroup     =  $businessOptionsGroupArr;
                    }
                }
                //echo "<pre>"; print_r($businessOptionsGroup); exit;
//                if($row['option_id']=='159'){
//                    echo "<pre>"; print_r($businessOptionsGroupArr);
//                    echo "<pre>"; print_r($businessOptionsGroup); exit;
//                }
                $productOptionName         = $this->escape($row['productOptionName']);
                $optionSKU                 = $this->escape($row['optionSKU']);
                $optionBarCode             = $this->escape($row['optionBarCode']);
                $productOptionRegularPrice = isset($row['productOptionRegularPrice']) ? $this->escape($row['productOptionRegularPrice']) : 0;
                $productOptionProductPrice = isset($row['productOptionProductPrice']) ? $this->escape($row['productOptionProductPrice']) : 0;
                $productOptionCashBack     = isset($row['productOptionCashBack']) ? $this->escape($row['productOptionCashBack']) : 0;
                $vsb                       = isset($row['vsb']) ? $this->escape($row['vsb']) : 0;
                $modelCode                 = isset($row['modelCode']) ? $this->escape($row['modelCode']) : '';
                $bmwCode                   = isset($row['bmwCode']) ? $this->escape($row['bmwCode']) : '';
                $modelYear                 = isset($row['modelYear']) ? $this->escape($row['modelYear']) : 0;
				
				//Finance rate calculator
				$variantArray = explode('-',$optionSKU);
				$monthlyInstallment = $this->financeRateCalculator($productOptionRegularPrice,$optionSKU);
				//$monthlyInstallment = $this->financeRateCalculator(250000,$variantArray[0]);
								
                if($inventoryTrackLevel=="No"){
                    $productOptionQuantity = "";
                    $productQuantityUnlimited = 1;
                }else{
                    $productOptionQuantity     = isset($row['productOptionQuantity']) ? $row['productOptionQuantity'] : "";
                    $productQuantityUnlimited = 0;
                }
                
                if ($productOptionQuantity == "")
                    $productOptionQuantityNotify = '';
                $productQuantityUnlimited = ($productOptionQuantity == "") ? "1" : "0";
                $productOptionStatus      = $this->escape($row['productOptionStatus']);
                $packageWeight            = $this->escape($row['packageWeight']);
                $packageLength            = $this->escape($row['packageLength']);
                $packageWidth             = $this->escape($row['packageWidth']);
                $packageHeight            = $this->escape($row['packageHeight']);
                $sortOrder                = $this->escape($row['productOptionImageSort']);
                $productOptionDefault     = isset($row['defaultOpion']) ? $this->escape($row['defaultOpion']) : '';
                
                if ($enableMultipleOptions != 'Yes') {
                    $productOptionName    = ($autoline=='')?$this->escape($_POST['productTitle']):$this->escape($row['productOptionName']);
                    $productOptionDefault = 'Yes';
                } else {
                    if($optionDefaultVal==0 && $prodOptCount==0){
                        $productOptionDefault = 'Yes';
                    }
                    $productOptionName = $this->escape($row['productOptionName']);
                }
                if ($productOptionProductPrice == '') {
                    $productOptionProductPrice = $productOptionRegularPrice;
                }
                $productOptionDefault = ($productOptionDefault == "Yes") ? "Yes" : "No";
                
                if ($row['option_id'] > -1) // Option already present in db. Update it
                    {
                    
                    $this->ObjDatabase->setQuery("UPDATE
				`" . DB_PREFIX . "product_options`
					  SET 	`productOptionRegularPrice`='" . $productOptionRegularPrice . "',
						`optionSKU`='" . $optionSKU . "',
						`optionBarCode`='" . $optionBarCode . "',
							`productOptionProductPrice`='" . $productOptionProductPrice . "',
                                                        `productOptionCashBack`='" . $productOptionCashBack . "',
                                                         `dealPrice`='" . $dealPrice . "',   
							`productOptionQuantity`='" . $productOptionQuantity . "',							
							`packageWeight`='" . $packageWeight . "',
							`packageLength`='" . $packageLength . "',
							`packageWidth`='" . $packageWidth . "',
							`packageHeight`='" . $packageHeight . "',
							`productQuantityUnlimited` = '" . $productQuantityUnlimited . "',
							`productOptionStatus`='" . $productOptionStatus . "' ,
							`productOptionDefault`='" . $productOptionDefault . "',
                                                         `vsb`='" . $vsb . "',
                                                        `modelCode`='" . $modelCode . "',
                                                        `bmwCode`='" . $bmwCode . "',
                                                        `modelYear`='" . $modelYear. "'
					  WHERE `productOptionID` = '" . $option_id . "'");
                    
                    $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_option_details`
					  SET 	`productOptionName`='" . $productOptionName . "'
					  WHERE `productOptionID`='" . $option_id . "' AND `languageID`='" . $languageID . "'");
                    if($enableBoyBoxSel=="Yes"){
                        $row['tier_price'] = array();
                    }
                    if($autoline=='') {
                        $this->groupTierPriceUpdate($row, $option_id);
                        $this->SaveProductOptionImages($option_count, $_POST, $productID, $option_id, $sortOrder);
                        if(count($businessOptionsGroup)>0){
                            $sqlDelete          =       "DELETE FROM ".DB_PREFIX."products_options_business 
                                                         WHERE productOptionID = '".$option_id."'";
                            $resDelete          =       $this->ObjDatabase->setQuery($sqlDelete);
                            //echo "<pre>"; print_r($businessOptionsGroup); exit;

                            $busOptDefIncr          =   0;
                            $busArrIncr             =   1;
                            foreach($businessOptionsGroup as $key=>$busOptGroup){
                                $busOptionDefault   =       isset($busOptGroup['businessOptionDefault']) && !empty($busOptGroup['businessOptionDefault']) ? $busOptGroup['businessOptionDefault'] : "No";
                                if($busOptionDefault=="Yes"){
                                    $busOptDefIncr  =       $busOptDefIncr+1;
                                }
                                if($busOptDefIncr==0 && $busArrIncr==count($businessOptionsGroup)){
                                    $busOptGroup['businessOptionDefault']       =   "Yes";
                                }
                                if($setAsProductDeal!="Yes"){
                                    $busOptGroup['businessOptionDealPrice']     =    0;
                                }
                                $this->addBusinessOptions($option_id,$busOptGroup,$productID,0,$inventoryTrackLevel);
                                $busArrIncr++;
                            }
                        }
                    } else {
                        $sqlSelect          =       "select productOptionBusinessID from ".DB_PREFIX."products_options_business where productOptionID='".$option_id."'";
                        $resSelect          =       $this->ObjDatabase->readValue($sqlSelect);
                        if(!empty($resSelect) && $resSelect['productOptionBusinessID']>0) {
                            $sqlUpdate          =       "UPDATE ".DB_PREFIX."products_options_business SET
                                                                      productOptionID = '".$option_id."',   
                                                                      businessID='".$businessID."',    
                                                                      productOptionRegularPrice = '".$productOptionRegularPrice."',
                                                                      productOptionProductPrice = '".$productOptionProductPrice."',
                                                                      dealPrice = '".$dealPrice."',
                                                                      productOptionQuantity = '".$productOptionQuantity."',
                                                                      productQuantityUnlimited = '".$productQuantityUnlimited."',                                                                  
                                                                      businessOptionDefault = '".$productOptionDefault."',
                                                                      busProductStatus = '".$productOptionStatus."',
                                                                      monthlyInstallment = '".$monthlyInstallment."'
                                                                 WHERE productOptionBusinessID = '".$resSelect['productOptionBusinessID']."'";

                            $resUpdate          =       $this->ObjDatabase->setQuery($sqlUpdate);
                        } else {
                            $sqlInsert          =       "INSERT INTO ".DB_PREFIX."products_options_business
                                                                  (productOptionID,   
                                                                   businessID,
                                                                   productOptionRegularPrice,
                                                                   productOptionProductPrice,
                                                                   dealPrice,
                                                                   productOptionQuantity,
                                                                   productQuantityUnlimited,                                                                   
                                                                   businessOptionDefault,
                                                                   busProductStatus,
																   monthlyInstallment) VALUES
                                                                   ('".$option_id."', 
                                                                    '".$businessID."',
                                                                    '".$productOptionRegularPrice."',
                                                                    '".$productOptionProductPrice."',
                                                                    '".$dealPrice."',
                                                                    '".$productOptionQuantity."',
                                                                    '".$productQuantityUnlimited."',                                                                    
                                                                    '".$productOptionDefault."',
                                                                    '".$productOptionStatus."',
                                                                    '".$monthlyInstallment."'
																	)";
                                $resUpdate          =       $this->ObjDatabase->setQuery($sqlInsert);
                        }
                    }
                } else // New option. Insert it
                    {
                    
                    $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_options`
			 (`productID`,
			 `optionSKU`,
			 `optionBarCode`,
			 `productOptionRegularPrice`,
			 `productOptionProductPrice`,
                        `productOptionCashBack`, 
			 `productOptionQuantity`,			 
			 `packageWeight`,
			 `packageLength`,
			 `packageWidth`,
			 `packageHeight`,
			  `productQuantityUnlimited`,
			  `productOptionStatus`,
			  `productOptionDefault`,
                          `dealPrice`,
                          `vsb`,
                          `modelCode`,
                          `bmwCode`,
                          `modelYear`
			 )
			 VALUES
			 ('" . $productID . "',
			 '" . $optionSKU . "',
			 '" . $optionBarCode . "',
			  '" . $productOptionRegularPrice . "',
			  '" . $productOptionProductPrice . "',	
                          '" . $productOptionCashBack . "',	
			  '" . $productOptionQuantity . "',
			  '" . $packageWeight . "',
			  '" . $packageLength . "',
			  '" . $packageWidth . "',
			  '" . $packageHeight . "',
			  '" . $productQuantityUnlimited . "',
			  '" . $productOptionStatus . "',
			  '" . $productOptionDefault . "','".$dealPrice."','".$vsb."','".$modelCode."','".$bmwCode."','".$modelYear."')");
                    $last_insert_productOptionID = $this->ObjDatabase->getInsertId();
                    foreach ($languageIDs['AllList'] as $langIds) {
                        $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_option_details`
				 (`productOptionID`,
				  `languageID`,
				  `productOptionName`
				 )
				 VALUES
				 ('" . $last_insert_productOptionID . "',
				  '" . $langIds . "',
				  '" . $productOptionName . "'
				 )");
                    }
                    if($enableBoyBoxSel=="Yes"){
                        $row['tier_price'] = array();
                    }
                    if($autoline=='') {
                        $this->groupTierPriceUpdate($row, $last_insert_productOptionID);
                        $this->SaveProductOptionImages($option_count, $_POST, $productID, $last_insert_productOptionID, $sortOrder);
                    
                        $busOptDefIncr          =   0;
                        $busArrIncr             =   1;
                        if(count($businessOptionsGroup)>0){
                            foreach($businessOptionsGroup as $key=>$busOptGroup){
                                $busOptionDefault   =       isset($busOptGroup['businessOptionDefault']) && !empty($busOptGroup['businessOptionDefault']) ? $busOptGroup['businessOptionDefault'] : "No";
                                if($busOptionDefault=="Yes"){
                                    $busOptDefIncr  =       $busOptDefIncr+1;
                                }
                                if($busOptDefIncr==0 && $busArrIncr==count($businessOptionsGroup)){
                                    $busOptGroup['businessOptionDefault']       =   "Yes";
                                }
                                if($setAsProductDeal!="Yes"){
                                    $busOptGroup['businessOptionDealPrice']     =    0;
                                }
                                $this->addBusinessOptions($last_insert_productOptionID,$busOptGroup,$productID,0,$inventoryTrackLevel);
                                $busArrIncr++;
                            }
                        }
                    } else {
                            $sqlInsert          =       "INSERT INTO ".DB_PREFIX."products_options_business
                                                                  (productOptionID,   
                                                                   businessID,
                                                                   productOptionRegularPrice,
                                                                   productOptionProductPrice,
                                                                   dealPrice,
                                                                   productOptionQuantity,
                                                                   productQuantityUnlimited,                                                                   
                                                                   businessOptionDefault,
                                                                   busProductStatus,
																   monthlyInstallment) VALUES
                                                                   ('".$last_insert_productOptionID."', 
                                                                    '".$businessID."',
                                                                    '".$productOptionRegularPrice."',
                                                                    '".$productOptionProductPrice."',
                                                                    '".$dealPrice."',
                                                                    '".$productOptionQuantity."',
                                                                    '".$productQuantityUnlimited."',                                                                    
                                                                    '".$productOptionDefault."',
                                                                    '".$productOptionStatus."',
																	'".$monthlyInstallment."'
																	)";
                                $resUpdate          =       $this->ObjDatabase->setQuery($sqlInsert);
                    }
        }
    }
            $prodOptCount = $prodOptCount+1;
            }
            }
    
    public function getBusinessOptions($languageIDs,$productOptionID,$userGroupID=-1,$inventoryTrackLevel="",$combinationID=0,$frontendView="",$selBusinessID=0,$showAllProducts=''){
        
        $invLevel             =       $this->getInventoryTrackLevel(0,$productOptionID);
        if($userGroupID>=0){
//            $sqlProdPrice   =       " IF(varGroPri.specialPrice IS NULL OR busOptions.productOptionProductPrice IS NULL, 
//                                          COALESCE(varGroPri.specialPrice, busOptions.productOptionProductPrice),
//                                          LEAST(varGroPri.specialPrice,busOptions.productOptionProductPrice))
//                                      AS productOptionProductPrice,";
            $sqlProdPrice   =       " LEAST(
						COALESCE(
							varOffPri.offerPrice,
							busOptions.productOptionProductPrice
						),
						COALESCE(
							varGroPri.specialPrice,
							busOptions.productOptionProductPrice
						) 
					)
					AS productOptionProductPrice,";
        }else{
//            $sqlProdPrice   =       " LEAST(
//						COALESCE(
//							varOffPri.offerPrice,
//							busOptions.productOptionProductPrice
//						),
//						COALESCE(
//							varGroPri.specialPrice,
//							busOptions.productOptionProductPrice
//						) 
//					)
//					AS productOptionProductPrice,";
            $sqlProdPrice   =       " busOptions.productOptionProductPrice,";
        }
        if($inventoryTrackLevel=="Options"){
            $sqlFields      =       "SUM(CAST(IFNULL(proComBus.businessCombQuantity,0) AS UNSIGNED)) as productOptionQuantity,
                                     0 as productQuantityUnlimited,
                                     proComBus.businessCombPrice,
                                     proComBus.businessCombDiff,";
            
            $sqlJoin        =       "FROM ".DB_PREFIX."product_combination_business proComBus ";
            $sqlJoin       .=       "LEFT JOIN 
					" . DB_PREFIX . "products_options_business AS busOptions 
						ON (
							busOptions.businessID=proComBus.businessID
						)";
            $sqlWhere       =       " proComBus.combinationID = '".$combinationID."'
                                      AND busOptions.productOptionID = '".$productOptionID."'
                                      AND proComBus.businessCombQuantity>0";
            $sqlGroup       =       " GROUP BY proComBus.combBusinessID";
        }else{
            $sqlFields      =       "busOptions.productOptionQuantity,
                                     0 as businessCombPrice,
                                     '' as businessCombDiff,";
            if($invLevel=="No" || $invLevel==""){
                $sqlFields .=       " 1 as productQuantityUnlimited,";
            }else{
                $sqlFields .=       "busOptions.productQuantityUnlimited,";
            }
            $sqlJoin        =       "FROM ".DB_PREFIX."products_options_business busOptions";
            $sqlWhere       =       " busOptions.productOptionID = '".$productOptionID."'";
            if($frontendView=="Yes"){
                if($invLevel=="Product"){
                   $sqlWhere  .=       " AND busOptions.productOptionQuantity>0";
                }
                if($showAllProducts!='Yes') {
					$sqlWhere  .=       " AND busOptions.busProductStatus = 'Active'";
				} else {
					$sqlWhere  .=       " AND busOptions.busProductStatus != 'Delete'";
				}
            }
            $sqlGroup       =       "";
        }
        $sqlSelect          =       "SELECT busOptions.productOptionBusinessID,
                                            busOptions.productOptionID,
                                            busOptions.businessID,
                                            busOptions.businessOptionSKU,
                                            busOptions.businessOptionSKU as optionSKU,
                                            busOptions.productOptionRegularPrice,
                                            $sqlProdPrice
                                            $sqlFields
                                            busOptions.dealPrice,
                                            busOptions.productQuantityNotifyAt,
                                            busOptions.soldQuantity,
                                            busOptions.busWareHouse,                                             
                                            busOptions.businessDispatchTime,
                                            busOptions.busProductStatus,
                                            busOptions.businessOptionDefault,
                                            bus.businessKey,
                                            busDet.businessName,
                                            prodDispDays.dispatchTime
                                     $sqlJoin
                                     LEFT JOIN 
					".DB_PREFIX."variant_offer_price AS varOffPri
						ON	(
							varOffPri.productOptionID = busOptions.productOptionID
							AND
							varOffPri.userGroupID='".$userGroupID."'
                                                        AND varOffPri.businessID = busOptions.businessID
						)
                                     LEFT JOIN
					".DB_PREFIX."variant_group_price AS varGroPri
						ON	(
							varGroPri.productOptionID = busOptions.productOptionID
							AND
							varGroPri.userGroupID='".$userGroupID."'
                                                        AND varGroPri.businessID = busOptions.businessID
						)
                                     INNER JOIN ".DB_PREFIX."business bus ON
                                     (bus.businessID = busOptions.businessID)
                                     INNER JOIN ".DB_PREFIX."business_details busDet ON
                                     (busDet.businessID = bus.businessID AND busDet.languageID = '".$languageIDs['Current']."')
                                     LEFT JOIN ".DB_PREFIX."product_dispatched_in_days prodDispDays ON
                                     (prodDispDays.dispatchID = busOptions.businessDispatchTime)
                                     WHERE $sqlWhere";
        if($selBusinessID>0){
            if($inventoryTrackLevel=="Options"){
                $sqlSelect     .=       " AND proComBus.businessID = '".$selBusinessID."'";
            }else{
                $sqlSelect     .=       " AND busOptions.businessID = '".$selBusinessID."'";
            }
        }
        $sqlSelect         .=       " $sqlGroup ORDER BY FIELD(busOptions.businessOptionDefault, 'Yes') DESC,busOptions.productOptionBusinessID ASC";
        //echo $sqlSelect."<br/>"."<br/>";
        $result             =       $this->ObjDatabase->readValues($sqlSelect);
        return $result;
    }
    
    public function addBusinessOptions($productOptionID,$busOptGroup,$productID=0,$productOptionBusinessID=0,$inventoryTrackLevel=""){
        $assignBusinessID   =       $busOptGroup['assignBusinessID'];
        $hiddenBusinessID   =       isset($busOptGroup['hiddenBusinessID']) ? $busOptGroup['hiddenBusinessID'] : 0;
        $busOptionDefault   =       isset($busOptGroup['businessOptionDefault']) && !empty($busOptGroup['businessOptionDefault']) ? $busOptGroup['businessOptionDefault'] : "No"; 
        $groupPriceArr      =       isset($busOptGroup['group_price']) && !empty($busOptGroup['group_price']) ? $busOptGroup['group_price'] : array();
        $busOptRegPrice     =       isset($busOptGroup['businessOptionReqPrice']) ? $busOptGroup['businessOptionReqPrice'] : 0;
        $busOptSalePrice    =       isset($busOptGroup['businessOptionSalePrice']) ? $busOptGroup['businessOptionSalePrice'] : 0;
        $busOptDealPrice    =       isset($busOptGroup['businessOptionDealPrice']) ? $busOptGroup['businessOptionDealPrice'] : 0;
        
        $busOptStatus       =       isset($busOptGroup['busProductStatus']) ? $busOptGroup['busProductStatus'] : 'Active';
        if($busOptStatus=="Approved"){
            $busOptStatus   =       "Active";
        }
        
        if($inventoryTrackLevel=="No"){
            $busQuantity           = "";
            $busQuanUnlimited      = 1;
        }else{
            $busQuantity           = isset($busOptGroup['businessQuantity']) ? $busOptGroup['businessQuantity'] : "";
            $busQuanUnlimited      = 0;
        }
                
        if($busOptSalePrice<=0){
            $busOptSalePrice =      $busOptRegPrice;
        }
        
        if($busOptionDefault=="Yes"){
            $sqlUpdateDef   =      "UPDATE ".DB_PREFIX."products_options_business SET businessOptionDefault = 'No'
                                                              WHERE productOptionID = '".$productOptionID."'";
            $resUpdateDef   =       $this->ObjDatabase->setQuery($sqlUpdateDef);
        }
        if($productOptionBusinessID>0){
            $sqlUpdate          =       "UPDATE ".DB_PREFIX."products_options_business SET
                                                                  productOptionID = '".$productOptionID."',
                                                                  businessID      = '".$assignBusinessID."',
                                                                  businessOptionSKU = '".$busOptGroup['businessOptionSKU']."',
                                                                  productOptionRegularPrice = '".$busOptRegPrice."',
                                                                  productOptionProductPrice = '".$busOptSalePrice."',
                                                                  dealPrice = '".$busOptDealPrice."',
                                                                  productOptionQuantity = '".$busQuantity."',
                                                                  productQuantityUnlimited = '".$busQuanUnlimited."',
                                                                  busWareHouse = '".$busOptGroup['businessWareHouse']."',
                                                                  businessDispatchTime = '".$busOptGroup['businessDispatchTime']."',
                                                                  businessOptionDefault = '".$busOptionDefault."',
                                                                  busProductStatus = '".$busOptStatus."'
                                                             WHERE productOptionBusinessID = '".$productOptionBusinessID."'";
            $resUpdate          =       $this->ObjDatabase->setQuery($sqlUpdate);
        }else{
            $sqlInsert          =       "INSERT INTO ".DB_PREFIX."products_options_business
                                                                  (productOptionID,
                                                                   businessID,
                                                                   businessOptionSKU,
                                                                   productOptionRegularPrice,
                                                                   productOptionProductPrice,
                                                                   dealPrice,
                                                                   productOptionQuantity,
                                                                   productQuantityUnlimited,
                                                                   busWareHouse,
                                                                   businessDispatchTime,
                                                                   businessOptionDefault,
                                                                   busProductStatus) VALUES
                                                                   ('".$productOptionID."',
                                                                    '".$assignBusinessID."',
                                                                    '".$busOptGroup['businessOptionSKU']."',
                                                                    '".$busOptRegPrice."',
                                                                    '".$busOptSalePrice."',
                                                                    '".$busOptDealPrice."',
                                                                    '".$busQuantity."',
                                                                    '".$busQuanUnlimited."',
                                                                    '".$busOptGroup['businessWareHouse']."',
                                                                    '".$busOptGroup['businessDispatchTime']."',
                                                                    '".$busOptionDefault."',
                                                                    '".$busOptStatus."')";
            $resUpdate          =       $this->ObjDatabase->setQuery($sqlInsert);
        }
        
        if($busOptionDefault=="Yes"){
            $sqlSelect             =     "SELECT COUNT(*) as cntOption FROM ".DB_PREFIX."product_options
                                          WHERE productOptionID = '".$productOptionID."'
                                          AND productOptionDefault = 'Yes'";
            $resOptionCnt          =      $this->ObjDatabase->getField($sqlSelect);
            
            if($productID>0 && $resOptionCnt>0){
                $sqlUpdateProduct  =    "UPDATE ".DB_PREFIX."products SET businessID = '".$assignBusinessID."'
                                         WHERE productID = '".$productID."'";
                $resUpdateProduct  =     $this->ObjDatabase->setQuery($sqlUpdateProduct);
            }
            
            $sqlUpdateOpt   =       "UPDATE ".DB_PREFIX."product_options 
                                                SET productOptionRegularPrice = '".$busOptRegPrice."',
                                                    productOptionProductPrice = '".$busOptSalePrice."',
                                                    productOptionQuantity = '".$busQuantity."',
                                                    productQuantityUnlimited = '".$busQuanUnlimited."'
                                                WHERE productOptionID = '".$productOptionID."'";   
            $resUpdateOpt    =       $this->ObjDatabase->setQuery($sqlUpdateOpt);
        }
        
        if($productID>0){
            $sqlCntBus         =     "SELECT COUNT(*) as cntBus FROM ".DB_PREFIX."products_options_business
                                             WHERE productOptionID = '".$productOptionID."'";
            $resBusCnt         =      $this->ObjDatabase->getField($sqlCntBus);
            if($resBusCnt>1){
                $this->ObjDatabase->setQuery("UPDATE ".DB_PREFIX."products SET enableBuybox = 'Yes'
                                              WHERE productID = '".$productID."'");
            }
        }
        if($assignBusinessID!=$hiddenBusinessID && $hiddenBusinessID>0){
            $selBusinessID  =       $hiddenBusinessID; 
        }else{
            $selBusinessID  =       $assignBusinessID; 
        }
        $sqlDelete          =       "DELETE FROM ".DB_PREFIX."variant_group_price 
                                     WHERE productOptionID = '".$productOptionID."'
                                     AND businessID = '".$selBusinessID."'";
        $resDelete          =       $this->ObjDatabase->setQuery($sqlDelete);
        
        if(count($groupPriceArr)>0){
            foreach($groupPriceArr as $groupPriceVal){
                $groupUserID            =       isset($groupPriceVal['userGroupID']) ? $groupPriceVal['userGroupID'] : "";
                $groupPrice             =       isset($groupPriceVal['specialPrice']) ? $groupPriceVal['specialPrice'] : 0;
                
                if($groupUserID!="" && $groupPrice>0){
                    $sqlCheck               =       "SELECT COUNT(*) as groupCnt,optionToGroupID FROM ".DB_PREFIX."variant_group_price
                                                     WHERE productOptionID = '".$productOptionID."'
                                                     AND businessID = '".$assignBusinessID."'
                                                     AND userGroupID = '".$groupUserID."'";
                    $resCheck               =       $this->ObjDatabase->readValue($sqlCheck);
                    
                    if($resCheck['groupCnt']<=0){
                        $sqlInsertGroupPrice    =       "INSERT INTO ".DB_PREFIX."variant_group_price
                                                                                  (productOptionID,
                                                                                   businessID,
                                                                                   userGroupID,
                                                                                   specialPrice) VALUES
                                                                                   ('".$productOptionID."',
                                                                                    '".$assignBusinessID."',
                                                                                    '".$groupUserID."',
                                                                                    '".$groupPrice."')";
                        $resInsertGroupPrice    =       $this->ObjDatabase->setQuery($sqlInsertGroupPrice);
                    }else{
                        $sqlUpdateGroupPrice    =       "UPDATE ".DB_PREFIX."variant_group_price SET
                                                                                    specialPrice = '".$groupPrice."'
                                                                            WHERE optionToGroupID = '".$resCheck['optionToGroupID']."'";
                        $resUpdateGroupPrice    =       $this->ObjDatabase->setQuery($sqlUpdateGroupPrice);
                    }
                }
            }
        }
        
    }
    
    public function groupTierPriceUpdate($row, $option_id) {
//        $sql = "
//			DELETE FROM 
//				`" . DB_PREFIX . "variant_group_price` 
//			WHERE
//				productOptionID = '" . $option_id . "'
//		";
//        $this->ObjDatabase->setQuery($sql);
//        if (!empty($row['group_price'])) {
//            $groupPrice = array();
//            foreach ($row['group_price'] as $group_price) {
//                if ($group_price['specialPrice'] > 0) {
//                    array_push($groupPrice, "('" . $option_id . "','" . $group_price['userGroupID'] . "','" . $group_price['specialPrice'] . "')");
//                }
//            }
//            $sql = "
//				INSERT INTO `" . DB_PREFIX . "variant_group_price`
//					(
//					`productOptionID`, 
//					`userGroupID`, 
//					`specialPrice`
//					)
//				VALUES
//					" . implode(",", $groupPrice) . "
//			";
//            $this->ObjDatabase->setQuery($sql);
//        }
        $sql = "
			DELETE FROM 
				`" . DB_PREFIX . "variant_tier_price` 
			WHERE
				productOptionID = '" . $option_id . "'
		";
        $this->ObjDatabase->setQuery($sql);
        if (!empty($row['tier_price'])) {
            $groupPrice = array();
            foreach ($row['tier_price'] as $tier_price) {
                if ($tier_price['quantity'] > 0 && $tier_price['tierPrice'] > 0) {
                    $allGroups = 0;
                    if ($tier_price['userGroupID'] == '') {
                        $allGroups = 1;
                    }
                    array_push($groupPrice, "(
						'" . $option_id . "',
						'" . $tier_price['userGroupID'] . "',
						'" . $allGroups . "',
						'" . $tier_price['quantity'] . "',
						'" . $tier_price['tierPrice'] . "'
						)");
                }
            }
            $sql = "
				INSERT INTO `" . DB_PREFIX . "variant_tier_price`
					(
					`productOptionID`, 
					`userGroupID`,
					`allGroups`,
					`quantity`, 
					`tierPrice`
					)
				VALUES
					" . implode(",", $groupPrice) . "
			";
            $this->ObjDatabase->setQuery($sql);
        }
    }
    //FUNCTION TO CHANGE PRODUCT REQUEST STATUS
    public function changeProductRequestStatus($status, $productID) {
        $this->ObjDatabase->setQuery("
			UPDATE
					`" . DB_PREFIX . "products`
			SET
					`productStatus` ='" . $status . "'
			WHERE
					productID = '" . $productID . "'");
    }
    //END OF FUNCTION
    //check products or productrequest exists by business id
    public function isProductsExistByBusiness($businessID) {
        $sql = "	SELECT
						productID
				FROM
					" . DB_PREFIX . "products
				WHERE
					businessID=" . (int) $businessID . " AND productStatus!='Deleted' ";
        $sql .= " UNION
					SELECT
						productRequestID AS productID
					FROM
						" . DB_PREFIX . "product_requests
					WHERE
						businessID=" . (int) $businessID . " AND productStatus!='Deleted' ";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        return $result;
    }
    //END OF FUNCTION
    //FUNCTION TO GET ACTIVE PRODUCT OPTION DETAILS
    public function getActiveProductOptionDetails($languageIDs, $productID) {
        $defaultLanguageID = $languageIDs['Default'];
        $currentLanguageID = $languageIDs['Current'];
        $userGroupID       = isset($userGroupID) ? $userGroupID : '';
        $sql               = "
			SELECT
				product.productID,
				product.productUrl,
				product.productDefaultCurrency,
				product.productImage,
				productDet.productTitle,
				LEAST(
						COALESCE(
							varOffPri.offerPrice,
							prodOptBus.productOptionProductPrice
						),
						COALESCE(
							varGroPri.specialPrice,
							prodOptBus.productOptionProductPrice
						) 
				) AS offerPrice
			FROM
					" . DB_PREFIX . "products AS product
				LEFT JOIN
					" . DB_PREFIX . "product_details AS productDet 
						ON 	(
							product.productID=productDet.productID
							AND 
							productDet.languageID='" . $currentLanguageID . "'
						)
				LEFT JOIN
					" . DB_PREFIX . "product_options AS productOpt
						ON 	(
							product.productID=productOpt.productID
							AND 
							productOpt.productOptionDefault = 'Yes'
						)
				LEFT JOIN
					".DB_PREFIX."products_options_business AS prodOptBus
						ON	(
							prodOptBus.productOptionID = productOpt.productOptionID
							AND
							prodOptBus.businessOptionDefault='Yes'
						)
				LEFT JOIN
					" . DB_PREFIX . "variant_offer_price AS varOffPri
						ON	(
							varOffPri.productOptionID = productOpt.productOptionID
							AND
							varOffPri.userGroupID='" . $userGroupID . "'
                                                        AND varOffPri.businessID = prodOptBus.businessID
						)
				LEFT JOIN
					" . DB_PREFIX . "variant_group_price AS varGroPri
						ON	(
							varGroPri.productOptionID = productOpt.productOptionID
							AND
							varGroPri.userGroupID='" . $userGroupID . "'
                                                        AND varGroPri.businessID = prodOptBus.businessID
						)
			WHERE
				product.productID = '" . (int) $productID . "'
				AND product.productStatus='Active'";
        $result            = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    //END OF FUNCTION
    //Update status update
    public function changeProductOptionBulkStatus($POST, $status) {
        for ($i = 0; $i < count($POST['productOptionBulkStatus']); $i++) {
            $optID  = $POST['productOptionBulkStatus'][$i];
            $sql    = "UPDATE
						" . DB_PREFIX . "product_options
				SET
						productOptionStatus = '" . $status . "'
				WHERE
						productOptionID = '" . $optID . "'";
            $result = $this->ObjDatabase->setQuery($sql);
        }
    }
    //END OF FUNCTION		
    //END OF FUNCTION		
    //FUNCTION TO GET RANDOM CODE
    public function getRandomCode($length, $type) {
        if ($type == 'Alphanumerics')
            $characters = '23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        else
            $characters = '0123456789';
        $string       = '';
        $stringLength = strlen($characters) - 1;
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, $stringLength)];
        }
        return $string;
    }
    //END OF FUNCTION
    //FUNCTION TO CHANGE PRODUCT STATUS
    public function changeProductStatus($productID,$businessID=0) {
        if ($_POST['changeStatus'] != '') {
//            if($_POST['changeStatus']=='Active'){
//                $buyBoxProd = $this->checkBuyboxProduct($productID);
//                if($buyBoxProd>0){
//                    $status = 'Buybox';
//                }
//            }
            $enableBuyBox = $this->getEnableBuybox($productID);
            if($enableBuyBox=="Yes" && $businessID>0){
                if ($_POST['changeStatus'] == 'Deleted') {
                    $changeStatus   =       "Delete";
                }else{
                    $changeStatus   =       $_POST['changeStatus'];
                }
                $sqlSelect          =       "SELECT GROUP_CONCAT(productOptionID) as productOptionIDs 
                                                        FROM " . DB_PREFIX . "product_options 
                                                        WHERE productID = '".$productID."'";
                $productOptionIDs   =       $this->ObjDatabase->getField($sqlSelect);

                $sql                =       "UPDATE " . DB_PREFIX . "products_options_business
                                            SET
                                            busProductStatus = '" . $changeStatus . "'
                                            WHERE productOptionID IN ($productOptionIDs)
                                            AND businessID = '".$businessID."'";
                $res = $this->ObjDatabase->setQuery($sql);
            }else{
                $sql                    =       "UPDATE " . DB_PREFIX . "products
                                                SET
                                                productStatus = '" . $_POST['changeStatus'] . "'
                                                WHERE productID='" . $productID . "'";
                $res                    =       $this->ObjDatabase->setQuery($sql);
                if ($_POST['changeStatus'] == 'Deleted') {
                    $sql                =       "UPDATE " . DB_PREFIX . "product_options
                                                SET
                                                        productOptionStatus = 'Delete'
                                                WHERE productID='" . $productID . "'";
                    $this->ObjDatabase->setQuery($sql);
                }
            }
            return $res;
        }
    }
    //END OF FUNCTION
    //FUNCTION TO GET PRODUCT SOLD COUNT
    public function getProductSoldCount($productID, $default = '') {
        $sql    = " SELECT 
									productSoldQuantity AS soldCount
								FROM 
									" . DB_PREFIX . "products
								WHERE 
									productID='" . $productID . "'";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    //END OF FUNCTION
    //FUNCTION TO GET CURRENT TIME
    public function getCurrentTime() {
        $sql    = "SELECT NOW() AS currentTime";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['currentTime'];
    }
    //END OF FUNCTION
    //FUNCTION TO GET CURRENT DATE
    public function getCurrentDate() {
        $date     = date('m/d/Y');
        $datetime = strtotime('-1 day', strtotime($date));
        $currDate = date('m/d/Y 00:00', $datetime);
        return $currDate;
    }
    //END OF FUNCTION
    public function listProductTocategoryDetails($languageIDs, $productID, $status = '') {
        $sql = "
				SELECT
						productToCat.*,
						productCatDet.productCategoryName,
						productCat.productCategoryParent,
						IF(productCat.productCategoryParent != '0',(SELECT productCategoryName FROM dp_product_category_details  WHERE productCat.productCategoryParent=productCategoryID AND languageID='" . $languageIDs['Current'] . "'),'') as parentCategory				FROM
						" . DB_PREFIX . "product_to_category AS productToCat
					LEFT JOIN
						" . DB_PREFIX . "product_categories AS productCat
							ON	(
								productCat.productCategoryID=	productToCat.productCategoryID";
        if (empty($status))
            $sql .= " AND productCat.productCategoryStatus='Active'";
        $sql .= ") 	
					LEFT JOIN
						" . DB_PREFIX . "product_category_details AS productCatDet 
							ON	(
								productToCat.productCategoryID=productCatDet.productCategoryID
							)
				WHERE
					productID='" . $productID . "'
					AND 
					productCatDet.languageID = '" . $languageIDs['Current'] . "' order by productToCat.productToCategoryID";
        return $this->ObjDatabase->readValuesSlave($sql);
    }
    public function getProductOptionsDetails($languageIDs, $productID) {
        $defaultLanguageID = $languageIDs['Default'];
        $currentLanguageID = $languageIDs['Current'];
        $sql               = "
					SELECT
						productOpt.productOptionID,
						productOptDet.productOptionName,
						productOpt.*,
						productOptDet.*
					FROM
						" . DB_PREFIX . "product_options productOpt,
						" . DB_PREFIX . "product_option_details productOptDet
					WHERE
						productOpt.productOptionID=productOptDet.productOptionID
						AND
						languageID=
							(
							SELECT CASE
								WHEN
								(
								SELECT EXISTS
									(
									SELECT
									*
									FROM
									" . DB_PREFIX . "product_options
									WHERE
									productOptionID=productOpt.productOptionID
									AND
									languageID='" . $currentLanguageID . "'
									)
								)
								THEN
								'" . $currentLanguageID . "'
								ELSE
								'" . $currentLanguageID . "'
								END
							)
						AND
						productID='" . $productID . "'
						AND
						productOptionStatus='Active' ";
        return $this->ObjDatabase->readValuesSlave($sql);
    }
    public function getSelectedOption($currProductID, $languageIDs) {
        $languageID        = $languageIDs['Current'];
        $defaultLanguageID = $languageIDs['Default'];
        $sql               = "SELECT
						productOpt.productOptionID,
						productOpt.productOptionRegularPrice,
						productOpt.productOptionProductPrice,
						productOpt.productOptionQuantity,
						productOpt.productQuantityUnlimited,
						productOptDet.productOptionName,
						(productOpt.productOptionRegularPrice-productOpt.productOptionProductPrice)
						AS productOptionSavePrice,CONCAT(
						ROUND((((productOpt.productOptionRegularPrice
						-productOpt.productOptionProductPrice)*100)
						/productOpt.productOptionRegularPrice),2),'%')
						AS productOptionDiscount,
						SUM(productOpt.soldQuantity) AS productOrderItemsCount
				FROM
						" . DB_PREFIX . "product_options AS productOpt
				LEFT JOIN
						" . DB_PREFIX . "product_option_details AS productOptDet
				ON (productOptDet.productOptionID=productOpt.productOptionID
				AND productOptDet.languageID = '" . $languageID . "')
				WHERE
						productOpt.productOptionStatus='Active'
						AND productOpt.productID='" . $currProductID . "'
				GROUP BY
						productOpt.productOptionID
				ORDER BY
						productOpt.productOptionDefault,productOpt.productOptionID ASC";
        $result            = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        return $result;
    }
    public function getSettingsValue($settingsKey, $settingsGroupId) {
        $sql    = "SELECT
						settingsValue as qrcodesetting
				FROM
						" . DB_PREFIX . "settings
				WHERE
						settingsKey='" . $settingsKey . "' AND settingsGroupID='" . $settingsGroupId . "'";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    //For Getting latest Product Orders
    public function latestProductOrders($languageIDs, $businessID = '') {
        $sql = "
				
				SELECT
						ordMas.masterOrderID,
						ordMas.orderNumber,
						ordMas.billingAddress AS billingAddress,
						ordMas.orderSubtotal AS total,
						ordMas.orderCreatedDate AS orderDate,
						ordMas.purchasedCurrency,
						SUM(ordMas.businessPayment) AS amount
				FROM
						" . DB_PREFIX . "order_masters ordMas ";
        $sql .= "
					WHERE
						ordMas.businessID='" . $businessID . "' ";
        $sql .= "
						AND (ordMas.paymentStatus='Received' OR ordMas.paymentStatus='Pending')
						AND (ordMas.orderStatus='Completed' OR ordMas.orderStatus='Process')
					GROUP BY
						ordMas.masterOrderID DESC
					LIMIT 0,5";
        return $this->ObjDatabase->readValuesSlave($sql);
    }
    // Get Dashboard VAlues
    public function getDashboardValues($params) {
        extract($params);
        $now             = date('Y-m-d');
        $dashboardValues = array();
        if ($productPrivilege) {
            $sql = "
					SELECT";
                $sql .= "	
					(
							SELECT  
								COUNT(DISTINCT product.productID) 
							FROM 
								" . DB_PREFIX . "products AS product 
							WHERE
								product.productStartTime <= NOW()  
								AND
								(
									product.productEndTime >= '" . $now . "'
									OR
									product.productEndTime = '0000-00-00' 
								)	
								AND ( product.productStatus	= 'Active') AND ( product.brandID= '2') 
					) AS upcoming";
				 $sql .= "	
					,(
							SELECT  
								COUNT(DISTINCT product.productID) 
							FROM 
								" . DB_PREFIX . "products AS product 
							WHERE
								( product.productStatus	= 'Review') AND ( product.brandID= '2')
					) AS review";
          // echo $sql;exit;
            $dashboardValues = $this->ObjDatabase->readValueSlave($sql);
        }
        return $dashboardValues;
    }
    public function getProductTitle($languageIDs, $productID,$type='') {
        $languageID        = $languageIDs['Current'];
        $defaultLanguageID = $languageIDs['Default'];
        $fields            = ($type!='')? ',product.productID,product.productImage,product.freeProductsCount,brandDet.brandName':'';
        $sql               = "		SELECT
				productTitle".$fields."
				FROM
				`" . DB_PREFIX . "products` product
				LEFT JOIN
				`" . DB_PREFIX . "product_details` productDet
                                    ON (product.productID = productDet.productID AND
				 languageID='" . $languageID . "') ";        
        if($type!='') {
            $sql            .= " LEFT JOIN
				`" . DB_PREFIX . "brands` brands
                                    ON (brands.brandID = product.brandID AND
				 brands.status='A')
                                     LEFT JOIN
				`" . DB_PREFIX . "brand_details` brandDet
                                    ON (brandDet.brandID = brands.brandID AND
				 brandDet.languageID='" . $languageID . "') ";
        
        }
        $sql               .= "                             WHERE
				product.productID = '" . (int) $productID . "'
                                    LIMIT 0,1";
        $result            = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    //FUNCTION TO GET BUSINESS ID
    public function getProductBusinessID($productID = "") {
        $sql    = "SELECT
						product.businessID
				FROM
						" . DB_PREFIX . "products as product
				WHERE
						product.productID='" . $this->escape($productID) . "' ";
        $result = $this->ObjDatabase->readValueSlave($sql, MYSQLI_ASSOC);
        return $result['businessID'];
    }
    //END OF FUNCTION
    public function SaveProductOptionImages($option_count, $POST, $productID, $productOptionID, $sortOrder) {
        $ObjImage          = new ImageModel();
        $productUriKey     = $POST['productUrl'];
        $entryproduct      = array();
        $flag              = "0";
        $mediaFlag         = '';
        $productImageCount = $POST["productOptionImageCount" . $option_count];
        if (!empty($sortOrder)) {
            $sortOrder = explode(",", $sortOrder);
        }
        for ($i = 1; $i <= $productImageCount; $i++) {
            if (is_array($sortOrder)) {
                $order = array_search($i, $sortOrder) + 1;
            } else {
                $order = $i;
            }
            $mediaID  = isset($POST['hidmediaID_' . $option_count . '_' . $i]) ? $POST['hidmediaID_' . $option_count . '_' . $i] : '';
            $isDelete = isset($POST['isdelete_' . $option_count . '_' . $i]) ? $POST['isdelete_' . $option_count . '_' . $i] : '';
            if ($mediaID != '') {
                if ($isDelete == 1) {
                    $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_media` WHERE `productMediaID`='" . $mediaID . "'  And productMediaType='I' AND productObjectType='DO'");
                } else {
                    if (($POST["productOptionImage_" . $option_count . '_' . $i . "_temp"] == "") && ($POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"] == "")) {
                        $mediaFlag = 1;
                        $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_media` SET `productMediaPriority`='" . $order . "' WHERE  productMediaID='" . $mediaID . "'");
                    } else {
                        $mediaFlag = 0;
                    }
                }
            } else {
                $mediaFlag = 0;
            }
            if ($mediaFlag == 0 && $isDelete != 1) {
                $productImageType = $POST['productOptionImage_' . $option_count . '_' . $i];
                $productImage     = "";
                if ($productImageType) {
                    /*@ main image exist */
                    if ($POST["productOptionImage_" . $option_count . '_' . $i . "_temp"] == '' && $POST['productOptionImage_' . $option_count . '_' . $i] != '')
                        $productImage = $this->getImageName($productImageType);
                    else /*@ main image upload */ 
                        $productImage = $productImageType;
                    /*@ thumb exist,main uploads*/
                    if (($_POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"] == '') && ($_POST["productOptionImageThumb_" . $option_count . '_' . $i] != '')) {
                        $paramMedia['thumbFlag'] = 1;
                        $paramMedia['resImage']  = $_POST["productOptionImageThumb_" . $option_count . '_' . $i];
                    }
                }
                if ($productImageType == "productOptionImage_" . $option_count . '_' . $i || $productImage == "") {
                    continue;
                }
                if ($productImage) {
                    $flag                          = "1";
                    $paramMedia['mainImage_temp']  = $POST["productOptionImage_" . $option_count . '_' . $i . "_temp"];
                    $paramMedia['thumbImage_temp'] = $POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"];
                    $paramMedia['mediaParam']      = $POST['dataResize'];
                    $paramMedia['mainImage']       = $productImage;
                    $paramMedia['destFolder']      = 'product';
                    $paramMedia['productImage']    = $POST["productOptionImage_" . $option_count . '_' . $i];
                    $paramMedia['productID']       = $productID;
                    $productImage                  = $this->generateMedia($paramMedia);
                }
                if (!$mediaID) {
                    $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_media`
						(`productObjectID`,`productID`,
						`productMedia` ,`productMediaType`,
						`productMediaPriority`,`productObjectType`)
						VALUES
						('" . $productOptionID . "','" . $productID . "',
						'" . $productImage . "','I','" . $order . "','DO')");
                } else {
                    $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_media` SET `productMedia`='" . $productImage . "',`productMediaPriority`='" . $order . "' WHERE  productMediaID='" . $mediaID . "'");
                }
            }
        }
        //echo $flag;
    }
    //GET PRODUCT IMAGES
    public function listProductOptionMedia($productOptionID) {
        $querySelectProductImages = "SELECT productMedia,productMediaID FROM `" . DB_PREFIX . "product_media` WHERE  productObjectID = '" . (int) $productOptionID . "' AND `productMediaType` = 'I' AND productObjectType='DO' ORDER BY productMediaPriority ASC";
        $resSelectProductImages   = $this->ObjDatabase->readValuesSlave($querySelectProductImages);
        return $resSelectProductImages;
    }
    //END OF FUNCTION
    //measurement class
    public function listMeasuremntClass($type) {
        $querySelectMeasuremntClass = "SELECT MC.classID,MC.class,MC.* FROM `" . DB_PREFIX . "measurement_class` As MC WHERE `classType` = '" . $type . "' And status='Active'";
        $resSelectMeasuremntClass   = $this->ObjDatabase->readValuesSlave($querySelectMeasuremntClass);
        return $resSelectMeasuremntClass;
    }
    //measurement class
    //Get Measurement Class By Id
    function getMeasurementById($MeasuremntClassId) {
        $sql    = "SELECT
				class
				FROM
				`" . DB_PREFIX . "measurement_class`
				WHERE
				`classID` = '" . $MeasuremntClassId . "'";
        $result = $this->ObjDatabase->readValueSlave($sql, MYSQLI_ASSOC);
        return $result['class'];
    }
    function getUserGroupById($IDs) {
        if ($IDs != '') {
            $sql    = "SELECT
						group_concat(userGroupName separator ', ') AS visibleTo
						FROM
						`" . DB_PREFIX . "user_group`
						WHERE
						`userGroupID` IN (" . $IDs . ")";
            $result = $this->ObjDatabase->readValueSlave($sql);
            return $result['visibleTo'];
        }
    }
    public function fetchProductCustomInfo($languageIDs, $productID) {
        $sql    = "SELECT
								productDescription
				FROM
						" . DB_PREFIX . "product_details
				WHERE
						productID='" . $productID . "'
				AND
						languageID='" . $languageIDs['Current'] . "'
				LIMIT 0,1";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    function getComboImage($combinationID) {
        $sql    = "SELECT
				productMedia
		FROM
				" . DB_PREFIX . "product_media
		WHERE
				productObjectID = '" . $combinationID . "' AND  productObjectType='C'";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    public function getDeliveryBusinessLocations($businessID, $languageIDs = '') {
        $sql    = "
				SELECT
						busLoc.businessLocID,			
						CONCAT_WS(',',
						busLocDet.locName,
						IF(busLocDet.locProvince!='',					
						busLocDet.locProvince,busLocDet.locCity),				
						busLoc.locZip
						)  AS location
				
				FROM 
						" . DB_PREFIX . "business_locations  busLoc
				LEFT JOIN 
						" . DB_PREFIX . "business_location_details busLocDet
				ON
				(
						busLocDet.businessLocID	= busLoc.businessLocID
						AND	busLocDet.languageID = '" . $languageIDs['Current'] . "'										
				)		
				WHERE  busLoc.locStatus='Active' AND busLoc.businessID='" . $businessID . "' ";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        return $result;
    }
    public function getBusinessByProductID($productID) {
        $sql    = "
				SELECT
		businessID				 
		FROM 
				" . DB_PREFIX . "products
		
		WHERE  productID='" . $productID . "' ";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['businessID'];
    }
    //End of function
    //ADD PRODUCT SHIPPING
    public function addProductShipping() {
        $productID        = $this->escape($_POST['productID']);
        $productRequestID = (!empty($_POST['productRequestID'])) ? $this->escape($_POST['productRequestID']) : '';
        $deliveryZoneID   = array();
        $deliveryZoneID   = $_POST['deliveryZoneID'];
        $shippingID       = $_POST['shippingID'];
        $table_prefix     = '';
        if ($productRequestID) {
            $table_prefix = "request_";
            $productID    = $productRequestID;
        }
        $sql = "select shippingServiceID from " . DB_PREFIX . "shipping_" . $table_prefix . "to_product where shippingServiceID='" . $this->escape($_POST['shippingServiceID']) . "'";
        $sql .= " and baseCharge='" . $this->escape($_POST['baseCharge']) . "' and maxQtyPerShipping='" . $this->escape($_POST['maxQtyPerShipping']) . "'";
        $sql .= " and chargePerExtraQty='" . $this->escape($_POST['chargePerExtraQty']) . "' and taxClassID='" . $this->escape($_POST['taxClassID']) . "'";
        $sql .= " and handlingCharge='" . $this->escape($_POST['handlingCharge']) . "'";
        $sql .= " and productID='" . $productID . "' and status!='D' ";
        if ($shippingID) {
            $sql .= " and shippingtoproductID!='" . $shippingID . "'";
        }
        $resultCount = $this->ObjDatabase->numberOfRecords($sql);
        if ($resultCount > 0) {
            return "5";
        }
        if ($shippingID) {
            $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "shipping_" . $table_prefix . "to_product
								SET 						
								shippingServiceID='" . $this->escape($_POST['shippingServiceID']) . "',						
								baseCharge='" . $this->escape($_POST['baseCharge']) . "',						
								maxQtyPerShipping='" . $this->escape($_POST['maxQtyPerShipping']) . "',									 	
								chargePerExtraQty='" . $this->escape($_POST['chargePerExtraQty']) . "',
								taxClassID='" . $this->escape($_POST['taxClassID']) . "',
								handlingCharge='" . $this->escape($_POST['handlingCharge']) . "',
								ModifiedDate = '" . date("Y-m-d H:i:s") . "'								
								WHERE
								shippingtoproductID = '" . $shippingID . "'");
            $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "product_" . $table_prefix . "to_shipping_deliveryzone WHERE shippingtoproductID='" . $shippingID . "'");
            $action = "2";
        } else {
            $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "shipping_" . $table_prefix . "to_product`(`productID`, `shippingServiceID`,
								`baseCharge`,`maxQtyPerShipping`, `chargePerExtraQty`,
								`taxClassID`,`handlingCharge`,
								`status`,`AssignedDate`,`ModifiedDate`) VALUES 
								( 
									'" . $productID . "',												
									'" . $this->escape($_POST['shippingServiceID']) . "',												 
									  '" . $this->escape($_POST['baseCharge']) . "',												   
									     '" . $this->escape($_POST['maxQtyPerShipping']) . "',
									      '" . $this->escape($_POST['chargePerExtraQty']) . "',
									      '" . $this->escape($_POST['taxClassID']) . "',
									       '" . $this->escape($_POST['handlingCharge']) . "',
									      'A',
									      '" . date("Y-m-d H:i:s") . "',
									      '" . date("Y-m-d H:i:s") . "'
								)");
            $shippingID = $this->ObjDatabase->getInsertId();
            $action     = "1";
        }
        if ($deliveryZoneID) {
            $insertDeliveryzoneValueSql = '';
            $insertDeliveryzonesql      = "INSERT INTO " . DB_PREFIX . "product_" . $table_prefix . "to_shipping_deliveryzone 
									 (deliveryZoneID, 
									  shippingtoproductID
									 ) 
									 VALUES";
            for ($x = 0; $x < count($deliveryZoneID); $x++) {
                $insertDeliveryzoneValueSql .= "('" . $deliveryZoneID[$x] . "', 
								
								'" . $shippingID . "')";
                if ($x < (count($deliveryZoneID) - 1)) {
                    $insertDeliveryzoneValueSql .= ",";
                }
            }
            $sql = $insertDeliveryzonesql . $insertDeliveryzoneValueSql;
            $this->ObjDatabase->setQuery($sql);
        }
        return $action;
    }
    public function getProductShippings($productID, $languageIDs, $productRequestID = '') {
        $table_prefix = '';
        $zoneArry     = array();
        if ($productRequestID > 0) {
            $table_prefix = 'request_';
            $productID    = $productRequestID;
        }
        $sql    = "SELECT 
						shipToPro.*,
				(SELECT settingsGroupXmlLabel
						FROM " . DB_PREFIX . "shipping_methods 
				WHERE settingsGroupID=shipToPro.shippingServiceID) AS SMservice
				
				FROM 
						`" . DB_PREFIX . "shipping_" . $table_prefix . "to_product` as shipToPro
				WHERE 
						shipToPro.productID =" . (int) $productID . "
						AND shipToPro.status != 'D' 
				ORDER BY 
						`ModifiedDate` Desc";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        $i      = 0;
        foreach ($result as $productship) {
            $zoneArry = $this->getdeliveryZone($languageIDs, $productship['shippingtoproductID'], $productRequestID);
            if (count($zoneArry) > 0)
                $result[$i]['zone'] = implode(', ', $zoneArry);
            $i++;
        }
        if (count($result) > 0) {
            return $result;
        } else {
            return array();
        }
    }
    public function getdeliveryZone($languageIDs, $shipID, $productRequestID = '') {
        $zoneArry          = array();
        $table_prefix      = '';
        $currentLanguageID = $languageIDs['Current'];
        if ($productRequestID)
            $table_prefix = 'request_';
        $sql    = "
				SELECT
						deliveryZoneName 
				FROM
						`" . DB_PREFIX . "product_" . $table_prefix . "to_shipping_deliveryzone` proToZone
				LEFT JOIN
						`" . DB_PREFIX . "deliveryzones` delZon
				ON
						(proToZone.deliveryZoneID = delZon.deliveryZoneID)
                                LEFT JOIN 
                                                `" . DB_PREFIX . "deliveryzone_details` delZonDet
                                ON
                                                delZon.deliveryZoneID=delZonDet.deliveryZoneID
                                                AND delZonDet.languageID='" . $currentLanguageID . "'
				
				WHERE
						`shippingtoproductID`='" . $shipID . "'";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        foreach ($result as $zone) {
            $zoneArry[] = $zone['deliveryZoneName'];
        }
        return $zoneArry;
    }
    public function getProductShippingByID($shipID, $productRequestID = '') {
        $table_prefix = '';
        if ($productRequestID > 0) {
            $table_prefix = 'request_';
            $productID    = $productRequestID;
        }
        $sql = "select *  FROM
						`" . DB_PREFIX . "shipping_" . $table_prefix . "to_product` as shipToPro WHERE shipToPro.shippingtoproductID='" . $shipID . "'";
        return $result = $this->ObjDatabase->readValueSlave($sql);
    }
    public function updateProShipStatus($POST, $productRequestID = '') {
        $shipID = $POST['shipID'];
        $status = $POST['status'];
        if ($productRequestID)
            $sql = "UPDATE  " . DB_PREFIX . "shipping_request_to_product SET `status` = '" . $status . "'
		WHERE `shippingtoproductID` ='" . $shipID . "';";
        else
            $sql = "UPDATE  " . DB_PREFIX . "shipping_to_product SET `status` = '" . $status . "'
		WHERE `shippingtoproductID` ='" . $shipID . "';";
        $updateAttrStatus = $this->ObjDatabase->setQuery($sql);
        return true;
    }
    public function getZonesByShippingID($shippingID, $productRequestID = '') {
        $table_prefix = '';
        if ($productRequestID)
            $table_prefix = 'request_';
        $sql    = "select  	deliveryZoneID  FROM
						`" . DB_PREFIX . "product_" . $table_prefix . "to_shipping_deliveryzone`  WHERE shippingtoproductID='" . $shippingID . "'";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        foreach ($result as $zone) {
            $zoneArry[] = $zone['deliveryZoneID'];
        }
        return $zoneArry;
    }
    public function getBasicByproductID($productID, $productRequestID = '') {
        if ($productRequestID)
            $sql = "select  	*  FROM
						`" . DB_PREFIX . "product_requests`  WHERE productRequestID='" . $productRequestID . "'";
        else
            $sql = "select  	*  FROM
						`" . DB_PREFIX . "products`  WHERE productID='" . $productID . "'";
        return $result = $this->ObjDatabase->readValueSlave($sql);
    }
    public function updateShippingSettings($POST) {
        $POST['productDispatchTime'] = isset($POST['productDispatchTime']) ? $POST['productDispatchTime'] : '';
        if (!empty($POST['productRequestID']))
            $sql = "UPDATE  " . DB_PREFIX . "product_requests SET `shippingSetting` = '" . $POST['isShipByMer'] . "',`shippingOrigin` = '" . $POST['businessLocID'] . "',
						`productDispatchTime`='" . $POST['productDispatchTime'] . "'
						WHERE `productRequestID` ='" . $POST['productRequestID'] . "';";
        else
            $sql = "UPDATE  " . DB_PREFIX . "products SET `shippingSetting` = '" . $POST['isShipByMer'] . "',`shippingOrigin` = '" . $POST['businessLocID'] . "',
				`productDispatchTime`='" . $POST['productDispatchTime'] . "'
						WHERE `productID` ='" . $POST['productID'] . "';";
        $result = $this->ObjDatabase->setQuery($sql);
        return true;
    }
    public function saveCustomOptionToProduct($productRequestID, $productID, $languageIDs, $OptionArry) {
        $ObjProductReq                            = new ProductRequestModel();
        $ObjImage                                 = new ImageModel();
        $varReqArry                               = array();
        //copy customoption
        $customAttributeArray['productRequestID'] = $productRequestID;
        $customAttributeArray['languageIDs']      = $languageIDs;
        $rescustomOptionDetails                   = $ObjProductReq->listRequestCustomProductOption($languageIDs, $customAttributeArray);
        for ($z = 0; $z < count($rescustomOptionDetails); $z++) {
            //custom option import
            $sqlImportoption          = "INSERT INTO " . DB_PREFIX . "product_custom_option
		(
				inputType,
				validateRule,
				include_in_combination,
				priceDiff,
				priceDiffType,
				status
		)
		SELECT
				inputType,
				validateRule,
				include_in_combination,
				priceDiff,
				priceDiffType,
				status
		FROM " . DB_PREFIX . "product_request_custom_option WHERE customOptionID = '" . $rescustomOptionDetails[$z]['customOptionID'] . "'";
            $insertCustomAttr         = $this->ObjDatabase->setQuery($sqlImportoption);
            $lastInsertCustomOptionId = $this->ObjDatabase->getInsertId();
            //Option Details Table Import
            $sqlImportoptionDet       = "INSERT INTO " . DB_PREFIX . "product_custom_option_details
		(
				customOptionID,
				languageID,
				customOptionName,
				validationMessage,
				helpText
		)
		SELECT
				" . $lastInsertCustomOptionId . ",
				languageID,
				customOptionName,
				validationMessage,
				helpText
		FROM " . DB_PREFIX . "product_request_custom_option_details WHERE customOptionID = '" . $rescustomOptionDetails[$z]['customOptionID'] . "'";
            $insertCustomAttrDet      = $this->ObjDatabase->setQuery($sqlImportoptionDet);
            $reqLangIDs               = $ObjProductReq->get_request_Custom_langIDs($rescustomOptionDetails[$z]['customOptionID']);
            foreach ($languageIDs['AllList'] as $langIds) {
                if (!(in_array($langIds, (array) $reqLangIDs)) || empty($reqLangIDs)) {
                    $sql = "INSERT INTO " . DB_PREFIX . "product_custom_option_details
		(
				customOptionID,
				languageID,
				customOptionName,
				validationMessage,
				helpText
		)
		SELECT
				" . $lastInsertCustomOptionId . ",
				" . $langIds . ",
				customOptionName,
				validationMessage,
				helpText
		FROM " . DB_PREFIX . "product_request_custom_option_details WHERE customOptionID = '" . $rescustomOptionDetails[$z]['customOptionID'] . "' AND languageID='" . $languageIDs['Default'] . "'";
                    $this->ObjDatabase->setQuery($sql);
                }
            }
            $inputTypesql   = "SELECT
				inputType
		
		FROM
				" . DB_PREFIX . "product_request_custom_option
		WHERE
				customOptionID = '" . $rescustomOptionDetails[$z]['customOptionID'] . "'";
            $inputType_arry = $this->ObjDatabase->readValueSlave($inputTypesql);
            $inputType      = $inputType_arry['inputType'];
            if ($inputType != 'textbox' || $inputType != 'textarea' || $inputType != 'date' || $inputType != 'datetime' || $inputType != 'time') {
                $sqlSelectOptions = "SELECT * FROM  " . DB_PREFIX . "product_request_custom_option_variant WHERE customOptionID='" . $rescustomOptionDetails[$z]['customOptionID'] . "'";
                $resAttrOptions   = $this->ObjDatabase->readValuesSlave($sqlSelectOptions);
                if (!empty($resAttrOptions)) {
                    foreach ($resAttrOptions as $options) {
                        $currentValueID              = $options['customOptionVariantID'];
                        //Option Variant Table Import
                        $sqlImportAttributeOptions   = "INSERT INTO " . DB_PREFIX . "product_custom_option_variant
		  (
				customOptionID,				
				priceDiff,
				priceDiffType,
				weightDiff,
				weightDiffType,
				sortOrder,
				isDefault,
				status
		  )
		  SELECT
				" . $lastInsertCustomOptionId . ",				
				priceDiff,
				priceDiffType,
				weightDiff,
				weightDiffType,
				sortOrder,
				isDefault,
				status
		  FROM " . DB_PREFIX . "product_request_custom_option_variant WHERE customOptionVariantID = '" . $currentValueID . "'";
                        $insertCustomAttrOptions     = $this->ObjDatabase->setQuery($sqlImportAttributeOptions);
                        $customOptionVariantID       = $this->ObjDatabase->getInsertId();
                        $varReqArry[$currentValueID] = $customOptionVariantID;
                        $variantthumbImagesql        = "SELECT
		variantThumbImage
		FROM
		" . DB_PREFIX . "product_request_custom_option_variant
		WHERE
		customOptionVariantID = '" . $currentValueID . "'";
                        $variantthumbImage_arry      = $this->ObjDatabase->readValueSlave($variantthumbImagesql);
                        if ($variantthumbImage_arry['variantThumbImage']) {
                            $thumbImage    = $variantthumbImage_arry['variantThumbImage'];
                            $target_path   = $this->getDestFilePath(__CORE_PUBLIC_UPLOADS_PATH . "catalog-request/custom-option-variant/" . $thumbImage);
                            $upload_images = $this->getSettingValue('site_settings', 'upload_images_to');
                            if ($upload_images != 'filesystem') {
                                $resize_path     = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . "catalog-request/custom-option-variant/" . $thumbImage);
                                //$target_path =__DIR_PUBLIC . '/'.__UPLOADS_FOLDER.'temp/'.$thumbImage;
                                $resize_path_new = __ROOT_PATH . '/' . __DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $resize_path;
                                $target_path     = $this->getDestFilePath(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $thumbImage);
                                $ObjImage->resizeImage($resize_path_new, $target_path, 20, 20);
                            } else {
                                $ObjImage->resizeImage(__CORE_PUBLIC_UPLOADS_PATH . "catalog-request/custom-option-variant/" . $thumbImage, $target_path, 20, 20);
                            }
                            $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . "catalog/custom-option-variant/" . $thumbImage);
                            @unlink($target_path);
                            $sql = "UPDATE " . DB_PREFIX . "product_custom_option_variant SET variantThumbImage='" . $thumbImage . "' WHERE customOptionVariantID='" . $customOptionVariantID . "'";
                            $this->ObjDatabase->setQuery($sql);
                        }
                        //Select Option Details
                        $sqlSelectOptionDetailIDs = "SELECT GROUP_CONCAT(customOptionVariantDetailsID) AS valueDetailsIDs FROM  " . DB_PREFIX . "product_request_custom_option_variant_details WHERE customOptionVariantID='" . $currentValueID . "'";
                        $resAttrOptionDetailIDs   = $this->ObjDatabase->readValueSlave($sqlSelectOptionDetailIDs);
                        if (!empty($resAttrOptionDetailIDs)) {
                            $attrOptionDetailIdsVar = $resAttrOptionDetailIDs['valueDetailsIDs'];
                            $attrOptionDetailIds    = explode(",", $attrOptionDetailIdsVar);
                            if (!empty($attrOptionDetailIds) && $attrOptionDetailIds[0] > 0) {
                                //variant Options Details Table Import
                                $sqlImportAttributeOptDet = "INSERT INTO " . DB_PREFIX . "product_custom_option_variant_details
								  (
										customOptionVariantID,
										languageID,
										value
								  )
								  SELECT
										" . $customOptionVariantID . ",
										languageID,
										value
								  FROM " . DB_PREFIX . "product_request_custom_option_variant_details WHERE customOptionVariantID IN (" . $currentValueID . ")";
                                $insertCustomAttrOptDet   = $this->ObjDatabase->setQuery($sqlImportAttributeOptDet);
                                foreach ($languageIDs['AllList'] as $langIds) {
                                    if (!(in_array($langIds, (array) $reqLangIDs)) || empty($reqLangIDs)) {
                                        $sql = "INSERT INTO " . DB_PREFIX . "product_custom_option_variant_details
				(
				customOptionVariantID,
				languageID,
				value
				)
				SELECT
						" . $customOptionVariantID . ",
						" . $langIds . ",
						value
				FROM " . DB_PREFIX . "product_request_custom_option_variant_details WHERE customOptionVariantID = '" . $currentValueID . "' AND languageID='" . $languageIDs['Default'] . "'";
                                        $this->ObjDatabase->setQuery($sql);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //link table import
            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option_link
		(
		customOptionID,
		productID,
		sortOrder
		)
		SELECT
		" . $lastInsertCustomOptionId . ",
		'" . $productID . "',
		`sortOrder`
		
		FROM
		`" . DB_PREFIX . "product_request_custom_option_link`
		WHERE
		`customOptionLinkID`='" . $rescustomOptionDetails[$z]['customOptionLinkID'] . "'");
            //link table import
        }
        $_POST['productID']              = $productID;
        $productArry['productID']        = $productID;
        $productArry['productRequestID'] = $productRequestID;
        $this->saveComboToproduct($productArry, $varReqArry);
        //copy customoption request
    }
    //saveComboToproduct				
    public function saveComboToproduct($productArry, $VariantArry) {
        $productID        = $productArry['productID'];
        $productRequestID = $productArry['productRequestID'];
        $ObjImage         = new ImageModel();
        $ObjProductReq    = new ProductRequestModel();
        //Combo
        $sql              = "
				SELECT  
					combinationID,
					combination,
					combinationSKU 
				FROM  
					" . DB_PREFIX . "product_request_combination 
				WHERE 
					productID='" . $productRequestID . "'";
        $resCombos        = $this->ObjDatabase->readValuesSlave($sql);
        for ($c = 0; $c < count($resCombos); $c++) {
            $newcombo    = array();
            $combination = explode('_', $resCombos[$c]['combination']);
            unset($combination[0]);
            foreach ($combination as $combo) {
                $newcombo[] = $VariantArry[$combo];
            }
            $newcombination  = $productID . "_" . implode('_', $newcombo);
            $combinationHash = $this->makeHAsh($newcombination);
            $sql             = "
					INSERT INTO `" . DB_PREFIX . "product_combination`
						(
						`productID`,
						`combination`,
						`combinationHash`,
						`combinationSKU`,
						`combinationBarCode`,
						`combinationQty`,
						`combinationPrice`,
						`combinationPriceDiffType`,
						`status`,
						`combinationWeight`,
						`combinationWeightDiffType`,
						`combinationHeight`,
						`combinationWidth`,
						`combinationLength`
						)
					SELECT
						'" . $productID . "',
						'" . $newcombination . "',
						'" . $combinationHash . "',
						`combinationSKU`,
						`combinationBarCode`,
						`combinationQty`,
						`combinationPrice`,
						`combinationPriceDiffType`,
						`status`,
						`combinationWeight`,
						`combinationWeightDiffType`,
						`combinationHeight`,
						`combinationWidth`,
						`combinationLength`
					FROM
						`" . DB_PREFIX . "product_request_combination`
					WHERE
						`combinationID`='" . $resCombos[$c]['combinationID'] . "'";
            $this->ObjDatabase->setQuery($sql);
            $lastInsertcomboID = $this->ObjDatabase->getInsertId();
            $comboImage_arry   = $ObjProductReq->getRequestComboImage($resCombos[$c]['combinationID']);
            if ($comboImage_arry['productMedia']) {
                $comboImage = $comboImage_arry['productMedia'];
                if ($ObjImage->file_exist(__UPLOADS_FOLDER . "catalog-request/product-combination/large/" . $comboImage_arry['productMedia']))
                    $paramMedia['mainImage_temp'] = __DIR_PUBLIC . "/" . __UPLOADS_FOLDER . "catalog-request/product-combination/large/" . $comboImage_arry['productMedia'];
                $upload_images = $this->getSettingValue('site_settings', 'upload_images_to');
                if ($upload_images != 'filesystem') {
                    $target_path_new              = $ObjImage->copy_to_temp(__DIR_PUBLIC . "/" . __UPLOADS_FOLDER . "catalog-request/product-combination/large/" . $comboImage_arry['productMedia']);
                    $paramMedia['mainImage_temp'] = __DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $target_path_new;
                }
                if ($ObjImage->file_exist(__UPLOADS_FOLDER . "catalog-request/product-combination/preview-main/" . $comboImage_arry['productMedia']))
                    $paramMedia['thumbImage_temp'] = __DIR_PUBLIC . "/" . __UPLOADS_FOLDER . "catalog-request/product-combination/preview-main/" . $comboImage_arry['productMedia'];
                $paramMedia['mediaParam'] = $_POST['dataResize'];
                $paramMedia['mainImage']  = $this->getImageName($comboImage);
                $paramMedia['destFolder'] = 'product-combination';
                $paramMedia['productID']  = $productID;
                $resImage                 = $this->generateMedia($paramMedia);
                $sql                      = "
						INSERT INTO `" . DB_PREFIX . "product_media`
							(
							`productID`,
							`productObjectID`,
							`productMedia`,
							`productObjectType`,
							`productMediaType`,
							`productMediaPriority`,
							`productMediaStatus`
							)
						SELECT
							'" . $_POST['productID'] . "',
							'" . $lastInsertcomboID . "',
							'" . $resImage . "',
							`productObjectType`,
							`productMediaType`,
							`productMediaPriority`,
							`productMediaStatus`
						FROM
							`" . DB_PREFIX . "product_request_media`
						WHERE
							`productObjectID`='" . $resCombos[$c]['combinationID'] . "'";
                $this->ObjDatabase->setQuery($sql);
            }
        }
    }
    public function getAttrSetID($productID, $productRequestID = '') {
        if ($productRequestID) {
            $sql = "
				SELECT							
				attributeSetID		    
				FROM " . DB_PREFIX . "product_requests WHERE productRequestID='" . $productRequestID . "'";
        } else {
            $sql = "
				SELECT							
				attributeSetID		    
				FROM " . DB_PREFIX . "products WHERE productID='" . $productID . "'";
        }
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['attributeSetID'];
    }
    //Assign Shipping Details to product
    public function assignShippingToProduct($productRequestID, $productID) {
        $sql    = "SELECT 
				shippingtoproductID			
		
		FROM 
				`" . DB_PREFIX . "shipping_request_to_product` as shipToPro
		WHERE 
				shipToPro.productID =" . (int) $productRequestID . "						
		ORDER BY 
				`ModifiedDate` Desc";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        foreach ($result as $productship) {
            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "shipping_to_product		
				(
						`productID`,
						`shippingServiceID`,
						`baseCharge`,`maxQtyPerShipping`,`chargePerExtraQty`,
						`taxClassID`,`handlingCharge`,
						`status`,`AssignedDate`,`ModifiedDate`
				)		
				SELECT
						'" . $productID . "',
						`shippingServiceID`,
						`baseCharge`,`maxQtyPerShipping`,`chargePerExtraQty`,
						`taxClassID`,`handlingCharge`,
						`status`,`AssignedDate`,`ModifiedDate`
				FROM
						`" . DB_PREFIX . "shipping_request_to_product` 
				WHERE 
						shippingtoproductID =" . $productship['shippingtoproductID']);
            $lastInsertshippingID = $this->ObjDatabase->getInsertId();
            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_to_shipping_deliveryzone		
				(
						`deliveryZoneID`,
						`shippingtoproductID`
				)		
				SELECT
						`deliveryZoneID`,
						'" . $lastInsertshippingID . "'				
				FROM
						`" . DB_PREFIX . "product_request_to_shipping_deliveryzone` 
				WHERE 
				shippingtoproductID =" . $productship['shippingtoproductID']);
        }
    }
    //FUNCTION TO SAVE REQUESTED ATTRIBUTES
    public function assignRequestAttributesToProduct($productRequestID, $productID, $languageIDs) {
        $ObjProductReq     = new ProductRequestModel();
        $ObjBusiness       = new BusinessModel();
        $businessID        = $this->getProductRequestBusinessID($productRequestID);
        $profileLanguageID = $ObjBusiness->getBusinessLanguageID($businessID);
        $sql               = "
		SELECT 
				attrValueID,`attrOptionID`,attr.attrInputType			
		
		FROM 
				`" . DB_PREFIX . "product_request_attribute_values` attrReqVal
		LEFT JOIN
				`" . DB_PREFIX . "attributes` attr
				ON (attr.attributeID=attrReqVal.attributeID)
		WHERE 
		productID =" . (int) $productRequestID;
        $result            = $this->ObjDatabase->readValuesSlave($sql);
        foreach ($result as $productship) {
            $insertval = array();
            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_attribute_values(
			`productID`,
			`attributeID`,
			`attrOptionID`
			)		
			SELECT
			'" . $productID . "',
			`attributeID`,
			`attrOptionID`
			FROM
			`" . DB_PREFIX . "product_request_attribute_values` 
			WHERE 
			attrValueID =" . $productship['attrValueID']);
            $lastInsertvalueID = $this->ObjDatabase->getInsertId();
            if ($productship['attrOptionID'] == 0) {
                $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_attribute_value_details		
				(
				attrValueID,
				languageID,
				attrDetValue
				)		
				SELECT
				
				'" . $lastInsertvalueID . "',
				languageID,
				attrDetValue
				FROM
				`" . DB_PREFIX . "product_request_attribute_value_details` 
				WHERE 
				attrValueID =" . $productship['attrValueID']);
                //get_request_attr_langIDs
                $reqFetchLang         = $ObjProductReq->get_request_attr_langIDs($productship['attrValueID']);
                $attrDetValue_default = $this->ObjDatabase->getField("SELECT
								attrDetValue
								FROM
								`" . DB_PREFIX . "product_request_attribute_value_details` 
								WHERE  
								attrValueID =" . $productship['attrValueID'] . " AND 
		(IF(EXISTS (SELECT 1  FROM `" . DB_PREFIX . "product_request_attribute_value_details` WHERE attrValueID =" . $productship['attrValueID'] . " AND languageID='" . $languageIDs['Default'] . "'),
			   languageID = " . $languageIDs['Default'] . ",IF(EXISTS (SELECT 1  FROM `" . DB_PREFIX . "product_details` WHERE attrValueID =" . $productship['attrValueID'] . " AND languageID='" . $profileLanguageID . "'),
		   languageID = " . $profileLanguageID . ",languageID ='1' DD.languageID ='1') ))");
                if (empty($attrDetValue_default))
                    $attrDetValue_default = $this->ObjDatabase->getField("SELECT
							attrDetValue
							FROM
							`" . DB_PREFIX . "product_request_attribute_value_details` 
							WHERE  
							attrValueID =" . $productship['attrValueID'] . " limit 1");
                //Sync to all newly added langs after request
                foreach ($languageIDs['AllList'] as $langIds) {
                    if (!(in_array($langIds, $reqFetchLang)) || empty($reqFetchLang)) {
                        $insertval[] = "(
				'" . $lastInsertvalueID . "',
				  '" . $langIds . "',
				  '" . $attrDetValue_default . "')";
                    }
                }
                if (count($insertval) > 0) {
                    $sqlOptDetails = "INSERT INTO " . DB_PREFIX . "product_attribute_value_details		
				(
				attrValueID,
				languageID,
				attrDetValue
				)
				VALUES";
                    $sql           = $sqlOptDetails . implode(",", $insertval);
                    $this->ObjDatabase->setQuery($sql);
                }
            }
            if ($productship['attrInputType'] == 'file') {
                $sqFile     = "SELECT				
		attrDetValue
		FROM
		`" . DB_PREFIX . "product_request_attribute_value_details` 
		WHERE 
		attrValueID =" . $productship['attrValueID'];
                $resultFile = $this->ObjDatabase->readValuesSlave($sqFile);
                foreach ($resultFile as $attrFile) {
                    $file = __CORE_PUBLIC_UPLOADS_PATH . "catalog-request/attributes/" . $attrFile['attrDetValue'];
                    if (file_exists($file))
                        copy($file, __CORE_PUBLIC_UPLOADS_PATH . "catalog/attributes/" . $attrFile['attrDetValue']);
                }
            }
        }
    }
    //FUNCTION TO DELETE PRODUCT MAIN MEDIA
    public function deleteProductImage($productID) {
        $ObjImage = new ImageModel();
        $sql      = "SELECT 									  
						productImage									
																			  
						FROM
						    " . DB_PREFIX . "products
						WHERE
						    productID = '" . $productID . "'";
        $result   = $this->ObjDatabase->readValueSlave($sql);
        if ($result['productImage']) {
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/product/thumb/' . trim($result['productImage']));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/product/large/' . trim($result['productImage']));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/product/preview/' . trim($result['productImage']));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/product/small/' . trim($result['productImage']));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/product/preview-main/' . trim($result['productImage']));
        }
    }
    //FUNCTION TO GENERATE MEDIA	
    function generateMedia($MediaArry) {
        $ObjImage           = new ImageModel();
        $productImage       = (isset($MediaArry['productImage'])) ? $MediaArry['productImage'] : '';
        $Image              = $MediaArry['mainImage'];
        $info               = pathinfo($Image);
        $dirs               = basename($Image, '.' . $info['extension']);
        $mainDir            = strtolower($dirs['0']);
        $subDir             = (!empty($dirs['1'])) ? strtolower($dirs['1']) : "";
        $destination        = $MediaArry['destFolder'];
        $imageType          = isset($MediaArry['imageType']) ? $MediaArry['imageType'] : '';
        $productID          = isset($MediaArry['productID']) ? $MediaArry['productID'] : '';
        $mainImage_temp     = $MediaArry['mainImage_temp'];
        $thumbImage_temp    = $MediaArry['thumbImage_temp'];
        $thumbFlag          = isset($MediaArry['thumbFlag']) ? $MediaArry['thumbFlag'] : 0;
        $resImage           = isset($MediaArry['resImage']) ? $MediaArry['resImage'] : '';
        //Image Size Params
        $previewHeight      = $MediaArry['mediaParam']['previewHeight'];
        $previewWidth       = $MediaArry['mediaParam']['previewWidth'];
        $thumbHeight        = $MediaArry['mediaParam']['thumbHeight'];
        $thumbWidth         = $MediaArry['mediaParam']['thumbWidth'];
        $smallthumbWidth    = $MediaArry['mediaParam']['smallthumbWidth'];
        $smallthumbHeight   = $MediaArry['mediaParam']['smallthumbHeight'];
        $productThumbWidth  = $thumbWidth;
        $productThumbHeight = $thumbHeight;
        $Image              = preg_replace('/\s+/', '-', $Image);
        $dest_image         = (!empty($subDir) && $subDir != "_") ? $mainDir . "/" . $subDir . "/" . $Image : $mainDir . "/" . $Image;
        $upload_images      = $this->getSettingValue('site_settings', 'upload_images_to');
        if ($productID != '') {
            $getCategorySpecificDimension = $this->getCategorySpecificDimension($productID);
            if ($getCategorySpecificDimension['productThumbWidth'] > 0 && $getCategorySpecificDimension['productThumbHeight'] > 0) {
                $productThumbWidth  = $getCategorySpecificDimension['productThumbWidth'];
                $productThumbHeight = $getCategorySpecificDimension['productThumbHeight'];
            }
        }
        
        //Product Level Directory Creation
        if ($upload_images == 'filesystem') {
            $dirLevel1              = __CORE_PUBLIC_UPLOADS_PATH . "catalog/" . $destination . "/large/" . $mainDir;
            $dirLevel2              = __CORE_PUBLIC_UPLOADS_PATH . "catalog/" . $destination . "/large/" . $mainDir . "/" . $subDir;
            $dirLevel2_thumb        = __CORE_PUBLIC_UPLOADS_PATH . "catalog/" . $destination . "/thumb/" . $mainDir . "/" . $subDir;
            $dirLevel2_preview      = __CORE_PUBLIC_UPLOADS_PATH . "catalog/" . $destination . "/preview/" . $mainDir . "/" . $subDir;
            $dirLevel2_small        = __CORE_PUBLIC_UPLOADS_PATH . "catalog/" . $destination . "/small/" . $mainDir . "/" . $subDir;
            $dirLevel2_preview_main = __CORE_PUBLIC_UPLOADS_PATH . "catalog/" . $destination . "/preview-main/" . $mainDir . "/" . $subDir;
            $dirLevel2_custom       = __CORE_PUBLIC_UPLOADS_PATH . "catalog/" . $destination . "/custom/" . $mainDir . "/" . $subDir;
            if (file_exists($dirLevel2) && is_dir($dirLevel2)) {
            } elseif (file_exists($dirLevel1) && is_dir($dirLevel1)) {
                mkdir($dirLevel2, 0777);
                mkdir($dirLevel2_thumb, 0777);
                mkdir($dirLevel2_preview, 0777);
                mkdir($dirLevel2_small, 0777);
                mkdir($dirLevel2_preview_main, 0777);
                mkdir($dirLevel2_custom, 0777);
            } else {
                mkdir($dirLevel2, 0777, TRUE);
                mkdir($dirLevel2_thumb, 0777, TRUE);
                mkdir($dirLevel2_preview, 0777, TRUE);
                mkdir($dirLevel2_small, 0777, TRUE);
                mkdir($dirLevel2_preview_main, 0777, TRUE);
                mkdir($dirLevel2_custom, 0777, TRUE);
            }
        }
        if ($thumbImage_temp != '') {
            if ($imageType == 'request') {
                //copy original preview image
                $tempImage = $ObjImage->copy_to_temp($thumbImage_temp);
                $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview-main/' . $dest_image);
                @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                $tempImage = $ObjImage->copy_to_temp($thumbImage_temp);
                $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $thumbWidth, $thumbHeight);
                $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $dest_image);
                @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                $tempImage = $ObjImage->copy_to_temp($thumbImage_temp);
                $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $smallthumbWidth, $smallthumbHeight);
                $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $dest_image);
                @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                $tempImage = $ObjImage->copy_to_temp($thumbImage_temp);
                $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $previewWidth, $previewHeight);
                $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $dest_image);
                @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                $tempImage = $ObjImage->copy_to_temp($thumbImage_temp);
                $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $productThumbWidth, $productThumbHeight);
                $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $dest_image);
                @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                if (strpos($thumbImage_temp, "exim") === false && strpos($thumbImage_temp, "catalog-request") === false)
                    @unlink($thumbImage_temp);
                @unlink($target_path);
            } else {
                $target_path = $this->getDestFilePath($thumbImage_temp);
                //copy original preview image				
                $ObjImage->copy_file($thumbImage_temp, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview-main/' . $dest_image);
                $ObjImage->resizeImage(__ROOT_PATH . '/' . $thumbImage_temp, $target_path, $thumbWidth, $thumbHeight);
                $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $dest_image);
                $ObjImage->resizeImage(__ROOT_PATH . '/' . $thumbImage_temp, $target_path, $smallthumbWidth, $smallthumbHeight);
                $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $dest_image);
                $ObjImage->resizeImage(__ROOT_PATH . '/' . $thumbImage_temp, $target_path, $previewWidth, $previewHeight);
                $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $dest_image);
                $ObjImage->resizeImage(__ROOT_PATH . '/' . $thumbImage_temp, $target_path, $productThumbWidth, $productThumbHeight);
                $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $dest_image);
                if (strpos($thumbImage_temp, "exim") === false && strpos($thumbImage_temp, "catalog-request") === false)
                    @unlink($thumbImage_temp);
                @unlink($target_path);
            }
        } elseif ($mainImage_temp != '') {
            /* @main changes:preview same */
            if ($mainImage_temp != '' && $thumbFlag == 1) {
                if ($upload_images == 'filesystem') {
                    $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview-main/' . $resImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview-main/' . $dest_image);
                    $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $resImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $dest_image);
                    $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $resImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $dest_image);
                    $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $resImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $dest_image);
                    $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $resImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $dest_image);
                    $this->unlinkImages($resImage, $destination);
                } else {
                    $tempImg = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview-main/' . $resImage);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview-main/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg);
                    $tempImg = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $resImage);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg);
                    $tempImg = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $resImage);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg);
                    $tempImg = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $resImage);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg);
                    $tempImg = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $resImage);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg);
                }
            }
            /* @main changes */
            else {
                if ($imageType == 'request') {
                    $tempImage = $ObjImage->copy_to_temp($mainImage_temp);
                    $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $smallthumbWidth, $smallthumbHeight);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                    $tempImage = $ObjImage->copy_to_temp($mainImage_temp);
                    $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $thumbWidth, $thumbHeight);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                    $tempImage = $ObjImage->copy_to_temp($mainImage_temp);
                    $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $previewWidth, $previewHeight);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                    $tempImage = $ObjImage->copy_to_temp($mainImage_temp);
                    $ObjImage->resizeImage(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '', $productThumbWidth, $productThumbHeight);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
                } else {
                    $target_path = $this->getDestFilePath($mainImage_temp);
                    $ObjImage->resizeImage(__ROOT_PATH . '/' . $mainImage_temp, $target_path, $smallthumbWidth, $smallthumbHeight);
                    $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/small/' . $dest_image);
                    $ObjImage->resizeImage(__ROOT_PATH . '/' . $mainImage_temp, $target_path, $thumbWidth, $thumbHeight);
                    $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/thumb/' . $dest_image);
                    $ObjImage->resizeImage(__ROOT_PATH . '/' . $mainImage_temp, $target_path, $previewWidth, $previewHeight);
                    $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/preview/' . $dest_image);
                    $ObjImage->resizeImage(__ROOT_PATH . '/' . $mainImage_temp, $target_path, $productThumbWidth, $productThumbHeight);
                    $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/custom/' . $dest_image);
                    @unlink($target_path);
                }
            }
        }
       
        if ($mainImage_temp != '') {
            if ($imageType == 'request') {
                $tempImage        = $ObjImage->copy_to_temp($mainImage_temp);
                $source_path      = __DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage;
                $destination_path = '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/large/' . $dest_image;
                $ObjImage->copy_file($source_path, $destination_path);
                if (strpos($mainImage_temp, "exim") === false && strpos($mainImage_temp, "catalog-request") === false)
                    @unlink($mainImage_temp);
                @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImage);
            } else {
                $source_path      = $mainImage_temp;
                $destination_path = '/' . __UPLOADS_FOLDER . 'catalog/' . $destination . '/large/' . $dest_image;
                $ObjImage->copy_file($source_path, $destination_path);
                if (strpos($mainImage_temp, "exim") === false && strpos($mainImage_temp, "catalog-request") === false)
                    @unlink($mainImage_temp);
            }
        }
        return $dest_image;
    }
    public function getDestFilePath($path) {
        $path_parts = pathinfo($path);
        $file_name  = basename($path, '.' . $path_parts['extension']);
        return $path_parts['dirname'] . "/" . $file_name . "_" . rand() . "." . $path_parts['extension'];
    }
    public function getCategorySpecificDimension($productID) {
        $currentDate = date('Y-m-d');
        $sql         = "
				SELECT
					productThumbWidth,
					productThumbHeight
				FROM
					" . DB_PREFIX . "product_categories
				WHERE
					productCategoryID = (
						SELECT 
							productCategoryID
						FROM
							dp_product_to_category
						WHERE
							productID ='" . $productID . "'
						LIMIT 
							1
					)
				LIMIT 
					1
			";
        return $this->ObjDatabase->readValueSlave($sql);
    }
    //FUNCTION TO GET SOLD QUANTITY		
    public function getSoldQuantity($comboHash) {
        $sql    = " SELECT 
		SUM(orderItemQuantity) AS soldCount 
		FROM 
		" . DB_PREFIX . "order_items ordIte
		LEFT JOIN 
		" . DB_PREFIX . "order_masters ordMas
		ON ordMas.masterOrderID=ordIte.masterOrderID 
		WHERE
		ordIte.combinationHash='" . $comboHash . "' AND (ordMas.orderStatus='Process' OR ordMas.orderStatus='Completed')";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['soldCount'];
    }
    //FUNCTION TO GET MAIN IMAGE			
    public function getProductDefaultImage($productID, $productOptionID, $defaultReq) {
        $sql = "SELECT 
				productImage
				FROM 
				" . DB_PREFIX . "products	AS product
				LEFT JOIN	
				" . DB_PREFIX . "product_options	AS deaOpt
				ON 
				(
				deaOpt.productOptionID = " . $productOptionID . "
				)
				WHERE 
				product.productID='" . $productID . "' ";
        if ($defaultReq != 'No') {
            $sql .= " AND deaOpt.productOptionDefault='Yes' ";
        }
        $sql .= " LIMIT 0,1";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    //FUNCTION TO SAVE REQUESTED OPTIONS
    public function saveProductRequestOptions($languageIDs, $options, $productID, $enableMultipleOptions = 'No', $productRequestID = '') {
        $languageID        = $languageIDs['Current'];
        $DefaultLanguageID = $languageIDs['Default'];
        $reqFetchLang      = $languageIDs['Fetch'];
        $optionsToInsert   = array();
        $optionsToDelete   = array();
        $optionsToUpdate   = array();
        foreach ($options as $rowHash => $row) // Traverse through all posted options
            {
            $insertval    = array();
            $option_id    = (int) $row['option_id'];
            $option_count = (int) $row['realOptionCount'];
            if ($row['is_delete'] != 1) {
                $productOptionName         = $this->escape($row['productOptionName']);
                $optionSKU                 = $this->escape($row['optionSKU']);
                $optionBarCode             = $this->escape($row['optionBarCode']);
                $productOptionRegularPrice = $this->escape($row['productOptionRegularPrice']);
                $productOptionProductPrice = $this->escape($row['productOptionProductPrice']);
                $productOptionQuantity     = $row['productOptionQuantity'];
                if ($row['productOptionQuantity'] == "")
                    $productOptionQuantityNotify = '';
                $productQuantityUnlimited = ($row['productOptionQuantity'] == "") ? "1" : "0";
                $productOptionStatus      = $this->escape($row['productOptionStatus']);
                $packageWeight            = $this->escape($row['packageWeight']);
                $packageLength            = $this->escape($row['packageLength']);
                $packageWidth             = $this->escape($row['packageWidth']);
                $packageHeight            = $this->escape($row['packageHeight']);
                $sortOrder                = $this->escape($row['productOptionImageSort']);
                $productOptionDefault     = (!empty($row['defaultOpion'])) ? $this->escape($row['defaultOpion']) : 'No';
                if ($enableMultipleOptions != 'Yes') {
                    $productOptionName    = $this->escape($_POST['productTitle']);
                    $productOptionDefault = 'Yes';
                } else {
                    $productOptionName = $this->escape($row['productOptionName']);
                }
                if ($productOptionProductPrice == '') {
                    $productOptionProductPrice = $productOptionRegularPrice;
                }
                $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_options`
			 (`productID`,
			 `optionSKU`,
			 `productOptionRegularPrice`,
			 `productOptionProductPrice`,
			  `optionBarCode`,			
			 `productOptionQuantity`,			 
			 `packageWeight`,
			 `packageLength`,
			 `packageWidth`,
			 `packageHeight`,
			  `productQuantityUnlimited`,
			  `productOptionStatus`,
			  `productOptionDefault`
			 )
			 VALUES
			 ('" . $productID . "',
			 '" . $optionSKU . "',		        
			  '" . $productOptionRegularPrice . "',
			  '" . $productOptionProductPrice . "',
			   '" . $optionBarCode . "',			 
			  '" . $productOptionQuantity . "',
			  '" . $packageWeight . "',
			  '" . $packageLength . "',
			  '" . $packageWidth . "',
			  '" . $packageHeight . "',
			  '" . $productQuantityUnlimited . "',
			  '" . $productOptionStatus . "',
			  '" . $productOptionDefault . "')");
                $last_insert_productOptionID = $this->ObjDatabase->getInsertId();
                if (count($reqFetchLang) > 0) {
                    $obsolete_idstr = implode("','", $reqFetchLang);
                    $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_option_details` (
									 `productOptionID`, 
									 `languageID`, 
									 `productOptionName` 
									 )
				SELECT				
				'" . $last_insert_productOptionID . "',
				`languageID`,
				`productOptionName`
									 
			FROM 
						`" . DB_PREFIX . "product_request_option_details`
			WHERE 
				`productRequestOptionID`='" . $option_id . "' AND languageID IN  ('" . $obsolete_idstr . "')");
                }
                $sqlOptDetails = "INSERT INTO `" . DB_PREFIX . "product_option_details`
				 (`productOptionID`,
				  `languageID`,
				  `productOptionName`
				 )
				 VALUES";
                foreach ($languageIDs['AllList'] as $langIds) {
                    if (!(in_array($langIds, $reqFetchLang)) || empty($reqFetchLang)) {
                        $insertval[] = "(
				'" . $last_insert_productOptionID . "',
				  '" . $langIds . "',
				  '" . $productOptionName . "')";
                    }
                }
                $sql = $sqlOptDetails . implode(",", $insertval);
                $this->ObjDatabase->setQuery($sql);
                $this->groupTierPriceUpdate($row, $last_insert_productOptionID);
                $this->SaveProductRequestOptionMedia($option_count, $_POST, $productID, $last_insert_productOptionID, $sortOrder);
                if ($row['option_id'] > -1) // Option already present in db. Update it
                    {
                    $OptionReqArry[$row['option_id']] = $last_insert_productOptionID;
                }
            }
        }
        $this->saveCustomOptionToProduct($productRequestID, $productID, $languageIDs, $OptionReqArry);
    }
    //FUNCTION TO SAVE REQUESTED OPTIONS MEDIA		
    public function SaveProductRequestOptionMedia($option_count, $POST, $productID, $productOptionID, $sortOrder) {
        $main_path         = __DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog-request/product/large/';
        //$thumbImgUpload=__UPLOADS_FOLDER.'catalog-request/product/preview-main/';
        $thumb_path        = __DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog-request/product/preview-main/';
        //$ObjImage       = new ImageModel();				
        $productImageCount = $POST["productOptionImageCount" . $option_count];
        if (!empty($sortOrder)) {
            $sortOrder = explode(",", $sortOrder);
        }
        for ($i = 1; $i <= $productImageCount; $i++) {
            if (is_array($sortOrder)) {
                $order = array_search($i, $sortOrder) + 1;
            } else {
                $order = $i;
            }
            $isDelete = (isset($POST['isdelete_' . $option_count . '_' . $i])) ? $POST['isdelete_' . $option_count . '_' . $i] : '';
            if ($isDelete != 1) {
                $productImageType      = $POST['productOptionImage_' . $option_count . '_' . $i];
                $productThumbImageType = $POST["productOptionImageThumb_" . $option_count . '_' . $i];
                $productImage          = "";
                if ($productImageType) {
                    $productImage = $this->getImageName($productImageType);
                }
                if ($productImageType == "productOptionImage_" . $option_count . '_' . $i || $productImage == "") {
                    continue;
                }
                if ($productImage) {
                    if ($POST["productOptionImage_" . $option_count . '_' . $i . "_temp"] == '')
                        $paramMedia['mainImage_temp'] = $main_path . $productImageType;
                    else
                        $paramMedia['mainImage_temp'] = $POST["productOptionImage_" . $option_count . '_' . $i . "_temp"];
                    if ($productThumbImageType != '' && $POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"] == '')
                        $paramMedia['thumbImage_temp'] = $thumb_path . $productImageType;
                    else
                        $paramMedia['thumbImage_temp'] = $POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"];
                    $paramMedia['mediaParam']   = $POST['dataResize'];
                    $paramMedia['mainImage']    = $productImage;
                    $paramMedia['destFolder']   = 'product';
                    $paramMedia['productImage'] = $POST["productOptionImage_" . $option_count . '_' . $i];
                    $paramMedia['productID']    = $productID;
                    $paramMedia['imageType']    = 'request';
                    $productImage               = $this->generateMedia($paramMedia);
                }
                $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_media`
						(`productObjectID`,`productID`,
						`productMedia` ,`productMediaType`,
						`productMediaPriority`,`productObjectType`)
						VALUES
						('" . $productOptionID . "','" . $productID . "',
						'" . $productImage . "','I','" . $order . "','DO')");
            }
        }
    }
    function generate_random_unique($length) {
        $random = '';
        for ($i = 0; $i < $length; $i++) {
            $random .= rand(0, 1) ? rand(0, 9) : chr(rand(ord('a'), ord('z')));
        }
        return $random;
    }
    public function getProductPopularityCount($productID = "") {
        $sql                          = "	SELECT 
								sum(viewed) as viewed,
								sum(uniqueViewed) as uniqueViewed
							FROM 
								" . DB_PREFIX . "product_popularity
							WHERE
								productID='" . $productID . "'";
        $resSelectproductIdImpression = $this->ObjDatabase->readValueSlave($sql);
        return $resSelectproductIdImpression;
    }
    //FUNCTION TO CHECK PRODUCT URL EXISTS
    function isProductUrlAlreadyExists($productUrl, $productID = NULL) {
        $productUrl = trim($productUrl);
        if ($productID)
            $append = "AND `productID` != '" . $productID . "'";
        $sql    = "
				SELECT
						1
				FROM
						`" . DB_PREFIX . "products`
				WHERE
						`productUrl` = '$productUrl' AND `productStatus` != 'Deleted' $append";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        if ($result)
            return true;
        else
            return false;
    }
    //FUNCTION TO CHECK PRODUCT URL EXISTS
    function isProductSkuAlreadyExists($SKU, $optionID = NULL, $productRequestID = '', $businessID = '',$type='',$compare='') {
        $table  = '';
        $append = '';
        if ($productRequestID > 0) {
            if ($businessID == '' && $optionID) {
                $businessID = $this->ObjDatabase->getField("SELECT businessID FROM " . DB_PREFIX . "product_request_options DO
								INNER JOIN " . DB_PREFIX . "product_requests D ON(D.productID=DO.productID) WHERE D.optionID=" . $optionID);
            }
            $table    = "request_";
            $prefix   = "_request";
            $idPrefix = "Request";
            if ($optionID)
                $append = "AND `productRequestOptionID` != '" . $optionID . "'";
        } else {
            if ($businessID == '' && $optionID) {
                $businessID = $this->ObjDatabase->getField("SELECT businessID FROM " . DB_PREFIX . "product_options DO
								INNER JOIN " . DB_PREFIX . "products D ON(D.productID=DO.productID) WHERE D.optionID=" . $optionID);
            }
            $prefix   = '';
            $idPrefix = '';
            if ($optionID)
                $append = "AND `productOptionID` != '" . $optionID . "'";
        }
        if (!empty($businessID))
            $append .= " AND products.businessID='" . $businessID . "'";
        $SKU    = trim($SKU);
        if($type=='') {
             $sql    = "
		SELECT
				1
		FROM
				`" . DB_PREFIX . "product_" . $table . "options` deaOpt
		LEFT JOIN
				`" . DB_PREFIX . "product" . $prefix . "s` products
			ON(deaOpt.product" . $idPrefix . "ID=products.product" . $idPrefix . "ID) WHERE
		
				`optionSKU` = '$SKU' AND `productOptionStatus` != 'Delete' $append";
        
            $result = $this->ObjDatabase->numberOfRecords($sql);
             if ($result)
                return true;
            else
                return false;
        } else {
            $sql    = "
		SELECT deaOpt.productID,deaOpt.productOptionID,deaOpt.productOptionStatus,deaOpt.productOptionDefault,products.productUrl,deaOpt.bmwCode,products.productStatus
		FROM
				`" . DB_PREFIX . "product_" . $table . "options` deaOpt
		LEFT JOIN
				`" . DB_PREFIX . "product" . $prefix . "s` products
			ON(deaOpt.product" . $idPrefix . "ID=products.product" . $idPrefix . "ID) WHERE ";
            if($compare=='') {
                $sql .= " `optionSKU` = '$SKU' AND `productOptionStatus` != 'Delete' $append";
            } else {
                $sql .= " `optionSKU` LIKE '%$SKU%' AND `productOptionStatus` != 'Delete' $append";
            }				
            
            $result = $this->ObjDatabase->readValue($sql);
            return $result;
        }
        
       
    }
    //FUNCTION TO CHECK PRODUCT URL EXISTS
    function isCombinationSkuAlreadyExists($SKU, $combinationID = NULL) {
        $SKU = trim($SKU);
        if ($combinationID)
            $append = "AND `combinationID` != '" . $combinationID . "'";
        $sql    = "
		SELECT
				1
		FROM
				`" . DB_PREFIX . "product_combination`
		WHERE
				`combinationSKU` = '$SKU' AND `status` != 'D' $append";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        if ($result)
            return true;
        else
            return false;
    }
    public function updateProductOptionDetails($optionID, $params = array()) {
        $sql = " UPDATE " . DB_PREFIX . "product_options
						SET
							productOptionRegularPrice='" . $params['productOptionRegularPrice'] . "',
							optionSKU='" . $params['optionSKU'] . "',";
        if ($params['productOptionProductPrice'] >= 0) {
            $sql .= "	productOptionProductPrice='" . $params['productOptionProductPrice'] . "',";
        }
        $sql .= " productOptionQuantity='" . $params['productOptionQuantity'] . "'
						WHERE 
							productOptionID = '" . $optionID . "'";
        $this->ObjDatabase->setQuery($sql);
    }
    public function updateProductsOptionsDetails($optionID, $params = array()) {
        $sql = " UPDATE " . DB_PREFIX . "product_options SET productOptionRegularPrice='" . $params['productOptionRegularPrice'] . "'";
        if ($params['optionSKU'] !='') {
            $sql .= "	,optionSKU='" . $params['optionSKU'] . "'";
        }
        if ($params['productOptionProductPrice'] >= 0) {
            $sql .= "	,productOptionProductPrice='" . $params['productOptionProductPrice'] . "'";
        }
        if ($params['productOptionQuantity'] !='') {
            $sql .= "	,productOptionQuantity='" . $params['productOptionQuantity'] . "'";
        }
        $sql .= " WHERE productOptionID = '" . $optionID . "'";
        $this->ObjDatabase->setQuery($sql);
        
        
        if(isset($params['businessID']) && $params['businessID']>0){
            $sql = " UPDATE " . DB_PREFIX . "products_options_business SET productOptionRegularPrice='" . $params['productOptionRegularPrice'] . "'";
            if ($params['optionSKU'] !='') {
                $sql .= "	,businessOptionSKU='" . $params['optionSKU'] . "'";
            }
            if ($params['productOptionProductPrice'] >= 0) {
                $sql .= "	,productOptionProductPrice='" . $params['productOptionProductPrice'] . "'";
            }
            if ($params['productOptionQuantity'] !='') {
                $sql .= "	,productOptionQuantity='" . $params['productOptionQuantity'] . "'";
            }
            $sql .= " WHERE productOptionID = '" . $optionID . "' AND businessID = '".$params['businessID']."'";
            $this->ObjDatabase->setQuery($sql);
        }
    }
    public function updateProductCombinationDetails($combinationID, $params = array()) {
        $sql = " UPDATE " . DB_PREFIX . "product_combination
						SET
							combinationQty='" . $params['combinationQty'] . "',
							combinationSKU='" . $params['combinationSKU'] . "',
							combinationPrice='" . $params['combinationPrice'] . "',
							combinationPriceDiffType='" . $params['combinationPriceDiffType'] . "'
						WHERE 
							combinationID = '" . $combinationID . "'";
        $this->ObjDatabase->setQuery($sql);
    }
    public function updateProductsCombinationsDetails($combinationID, $params = array()) {
        $sql = " UPDATE " . DB_PREFIX . "product_combination SET combinationPrice='" . $params['combinationPrice'] . "',combinationPriceDiffType='" . $params['combinationPriceDiffType'] . "'";
	if ($params['combinationSKU'] !='') {
            $sql .= "	,combinationSKU='" . $params['combinationSKU'] . "'";
        }
        if ($params['combinationQty'] !='') {
            $sql .= "	,combinationQty='" . $params['combinationQty'] . "'";
        }
        $sql .= " WHERE combinationID = '" . $combinationID . "'";
        $this->ObjDatabase->setQuery($sql); 
        
        if(isset($params['businessID']) && $params['businessID']>0){
            $sql = " UPDATE " . DB_PREFIX . "product_combination_business SET businessCombPrice='" . $params['combinationPrice'] . "',businessCombDiff='" . $params['combinationPriceDiffType'] . "'";
            if ($params['combinationSKU'] !='') {
                $sql .= "	,businessCombSKU='" . $params['combinationSKU'] . "'";
            }
            if ($params['combinationQty'] !='') {
                $sql .= "	,businessCombQuantity='" . $params['combinationQty'] . "'";
            }
            $sql .= " WHERE combinationID = '" . $combinationID . "' AND businessID = '".$params['businessID']."'";
            $this->ObjDatabase->setQuery($sql); 
        }
    }
    //FUNCTION TO GET MERCHANT name
    function getMerchantNameByProductID($productID, $languageID) {
        $sql    = "
			SELECT
					businessName
			FROM
					`" . DB_PREFIX . "business_details` busDet
			LEFT JOIN
					`" . DB_PREFIX . "products` products
			ON(busDet.businessID=products.businessID)
			WHERE 	products.`productID` = '" . $productID . "' AND busDet.`languageID`= " . $languageID;
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['businessName'];
    }
    function getProductNameByProductID($productID, $languageID) {
        $sql    = "
			SELECT
					productTitle
			FROM
					`" . DB_PREFIX . "product_details` productDet				
			WHERE 	`productID` = '" . $productID . "' AND `languageID`= " . $languageID;
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['productTitle'];
    }
    function getProductsBysetID($setID = '', $businessID = '', $limitFrom = '', $limitTo = '', $brandID = '', $searchProductCategories = '') {
        $sql = "
			SELECT
					productID
			FROM
					`" . DB_PREFIX . "products` products				
			WHERE  products.productStatus!='Deleted' AND products.productStatus!='Pending' AND products.productStatus!='Rejected' AND products.productStatus!='Buybox'";
        if ($setID)
            $sql .= " AND `attributeSetID` = '" . $setID . "'";
        if ($businessID)
            $sql .= " AND products.businessID='" . $businessID . "'";
        if ($brandID)
            $sql .= " AND products.brandID='" . $brandID . "'";
       
        if ((is_array($searchProductCategories) && count(array_filter($searchProductCategories)) > 0)) {
            $sql .= " 
						AND products.productID IN
						(
							SELECT
								productID
							FROM
								" . DB_PREFIX . "product_to_category
							WHERE
								productCategoryID IN ('" . implode("','", $searchProductCategories) . "')
						)";
        }
         if ((!empty($limitFrom)) && (!empty($limitTo)))
            $sql .= " LIMIT  " . $limitFrom . "," . $limitTo . " ";
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    function getComboBysetID($setID = '', $businessID = '', $limitFrom = '', $limitTo = '') {
        $sql = "
			SELECT
					1
			FROM
					`" . DB_PREFIX . "product_combination` proCombo					
					LEFT JOIN `" . DB_PREFIX . "products` as products ON
					(products.productID = proCombo.productID) WHERE proCombo.status='A' AND productStatus='Active'";
        if ($setID)
            $sql .= " AND `attributeSetID` = '" . $setID . "'";
        if ($businessID)
            $sql .= " AND products.businessID='" . $businessID . "'";
        if ((!empty($limitFrom)) && (!empty($limitTo)))
            $sql .= " LIMIT  " . $limitFrom . "," . $limitTo . " ";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        return $result;
    }
    function getmediaBysetID($setID = '', $businessID = '', $limitFrom = '', $limitTo = '') {
        $sql = "
			SELECT
					1
			FROM
					`" . DB_PREFIX . "product_media` deamedia					
					LEFT JOIN `" . DB_PREFIX . "products` as products ON
					(products.productID = deamedia.productID) WHERE  productStatus='Active'";
        if ($businessID)
            $sql .= " AND products.businessID='" . $businessID . "'";
        if ($setID)
            $sql .= " AND `attributeSetID` = '" . $setID . "'";
        if ((!empty($limitFrom)) && (!empty($limitTo)))
            $sql .= " LIMIT  " . $limitFrom . "," . $limitTo . " ";
       
        $result = $this->ObjDatabase->numberOfRecords($sql);
        return $result;
    }
    public function saveRequestToProductID($productID, $productRequestID) {
        $this->ObjDatabase->setQuery("
		UPDATE 
			`" . DB_PREFIX . "product_requests` 
		SET 
			`requestToProductID` ='" . $productID . "' 
		WHERE 
			productRequestID = '" . $productRequestID . "'");
    }
    function get_default_option_details($productID) {
        $sql = "SELECT optionSKU as sku FROM " . DB_PREFIX . "product_options WHERE productOptionDefault='Yes' AND productID ='" . $productID . "'";
        $sku = $this->ObjDatabase->readValueSlave($sql);
        return $sku['sku'];
    }
    function get_default_optionprice($productID) {
        $sql   = "SELECT productOptionRegularPrice as Price,productOptionProductPrice as listPrice FROM " . DB_PREFIX . "product_options WHERE productOptionDefault='Yes' AND productID ='" . $productID . "'";
        $price = $this->ObjDatabase->readValueSlave($sql);
        return $price['listPrice'];
    }
    //FUNCTION TO GET BUSINESS ID
    public function getProductRequestBusinessID($productID = "") {
        $sql    = "SELECT
						product.businessID
				FROM
						" . DB_PREFIX . "product_requests as product
				WHERE
						product.productRequestID='" . $this->escape($productID) . "' ";
        $result = $this->ObjDatabase->readValueSlave($sql, MYSQLI_ASSOC);
        return $result['businessID'];
    }
    public function getRequestShipInfo($productID) {
        $sqlGetProducts = "SELECT shippingOrigin as businessLocID,shippingSetting as isShipByMer  FROM " . DB_PREFIX . "product_requests WHERE `productRequestID`=" . $productID;
        return $this->ObjDatabase->readValueSlave($sqlGetProducts);
    }
    public function assignDefaultSmService($productID) {
        $sqlMainMethods = "SELECT * FROM
			" . DB_PREFIX . "shipping_methods WHERE settingsGroupParent!=0 AND `isDefault`='Yes' AND settingsGroupStatus='Active' AND `isAvailable`='Yes' AND
			settingsGroupKey NOT IN ('flat_custom','free_custom')  ORDER BY settingsGroupPriority ASC";
        $resMainMethods = $this->ObjDatabase->readValuesSlave($sqlMainMethods);
        $insertSql      = "INSERT INTO `" . DB_PREFIX . "shipping_to_product`(`productID`, `shippingServiceID`,
			`baseCharge`,`maxQtyPerShipping`,`taxClassID`,								
			`status`,`AssignedDate`,`ModifiedDate`) VALUES";
        foreach ($resMainMethods as $mainMethod) {
            $serviceData = array();
            $sqlService  = "SELECT * FROM
				" . DB_PREFIX . "shipping_methods_settings WHERE settingsGroupID='" . $mainMethod['settingsGroupID'] . "'";
            $resServices = $this->ObjDatabase->readValuesSlave($sqlService);
            foreach ($resServices as $service) {
                $serviceData[$service['settingsGroupID']][$service['settingKey']] = $service['settingValue'];
                $serviceData[$service['settingsGroupID']]['settingsGroupKey']     = $service['settingsGroupKey'];
            }
            foreach ($serviceData as $id => $data) {
                if (strpos($data['settingsGroupKey'], 'free_') !== false) {
                    $data['qty_upto']   = $data['free_qty_upto'];
                    $data['taxClassID'] = 0;
                } elseif (strpos($data['settingsGroupKey'], 'flat_') !== false) {
                    $data['qty_upto']   = 0;
                    $data['taxClassID'] = $data['flat_tax_class'];
                }
                $valueSql = "('" . $productID . "',												
					'" . $this->escape($id) . "',												 
					'" . (isset($data['flat_fixed_charge']) ? $this->escape($data['flat_fixed_charge']) : '') . "',												   
					'" . $this->escape($data['qty_upto']) . "',
					'" . $this->escape($data['taxClassID']) . "',	
					'A',
					'" . date("Y-m-d H:i:s") . "',
					'" . date("Y-m-d H:i:s") . "')";
                $this->ObjDatabase->setQuery($insertSql . $valueSql);
                $shippingID = $this->ObjDatabase->getInsertId();
                if ($data['delivery_zones'] != '') {
                    $dzones = explode('~*', $data['delivery_zones']);
                    foreach ($dzones as $zone) {
                        $insertDeliveryzonesql = "INSERT INTO " . DB_PREFIX . "product_to_shipping_deliveryzone 
							(deliveryZoneID, 
							 shippingtoproductID
							) 
							VALUES('" . $zone . "',
							'" . $shippingID . "')";
                        $this->ObjDatabase->setQuery($insertDeliveryzonesql);
                    }
                }
            }
        }
    }
    public function deleteExistCombo($productID) {
        $this->ObjDatabase->setQuery("Update " . DB_PREFIX . "product_combination SET `status`='D' WHERE productID='" . $productID . "'");
        $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_media` WHERE productID='" . $productID . "' AND  productObjectType='C'");
    }
    public function getDispatchTime() {
        $sql = "SELECT
				dispatchID,dispatchTime
				FROM
					" . DB_PREFIX . "product_dispatched_in_days";
        return $result = $this->ObjDatabase->readValuesSlave($sql);
    }
    public function getDispatchTimeByID($ID) {
        $sql = "SELECT
				dispatchTime
				FROM
					" . DB_PREFIX . "product_dispatched_in_days WHERE dispatchID='" . $ID . "'";
        return $result = $this->ObjDatabase->getField($sql);
    }
    public function saveSellProductProductIDs($productID, $selproductIDs, $type = '') {
        $prefix = strtolower($type);
        if ($productID > 0) {
            $this->destroySellProducts($productID, $type);
            if (!empty($selproductIDs) && $selproductIDs[0] != '') {
                $selectedProductIDs = $selproductIDs;
                $sql                = "INSERT INTO " . DB_PREFIX . "product_link_" . $prefix . "_sell(
										productID," . $prefix . "SellProductID,
										priority
								) values";
                $i                  = 0;
                foreach ($selproductIDs as $Ids) {
                    $i++;
                    $sqlval[] = "(
				'" . $productID . "',				
				'" . $Ids . "',
				'" . $i . "')";
                }
                $sql    = $sql . implode(",", $sqlval);
                $result = $this->ObjDatabase->setQuery($sql);
            }
        }
        return 1;
    }
    public function saveFreeProductProductIDs($productID, $selproductIDs, $type = '',$freeProductsCount='') {
        $prefix = strtolower($type);
        if ($productID > 0) {
            $this->destroySellProducts($productID, $type);
            if (!empty($selproductIDs) && $selproductIDs[0] != '') {
                $selectedProductIDs = $selproductIDs;
                $sql                = "INSERT INTO " . DB_PREFIX . "product_link_" . $prefix . "(
										productID," . $prefix . "ProductID,
										priority
								) values";
                $i                  = 0;
                foreach ($selproductIDs as $Ids) {
                    $i++;
                    $sqlval[] = "(
				'" . $productID . "',				
				'" . $Ids . "',
				'" . $i . "')";
                }
                $sql    = $sql . implode(",", $sqlval);
                
                $result = $this->ObjDatabase->setQuery($sql);
            $this->ObjDatabase->setQuery("update " . DB_PREFIX . "products set freeProductsCount='".$freeProductsCount."' where productID='".$productID."'");
        }
        }
        return 1;
    }
    //FUNCTION TO DESTROY RELATED PRODUCTS
    public function destroySellProducts($productID, $type = '') {
        $prefix = strtolower($type);
        if($prefix=='free') {
        $sql    = "	DELETE
								FROM
						" . DB_PREFIX . "product_link_" . $prefix . "
						WHERE
						`productID` ='" . $productID . "' ";
        $this->ObjDatabase->setQuery("update " . DB_PREFIX . "products set freeProductsCount='0' where productID='".$productID."'");
        } else {
            $sql    = "	DELETE
								FROM
						" . DB_PREFIX . "product_link_" . $prefix . "_sell
						WHERE
						`productID` ='" . $productID . "' ";
        }
       
        $result = $this->ObjDatabase->setQuery($sql);
        return $result;
    }
    //END OF FUNCTION
    public function getCartPromotions($productID = 0, $brandID = 0, $businessID = 0, $params = array()) {
        $ObjCart = new CartModel();
        extract($params);
        $applied_promotions                 = array();
        $items[0]['categories']             = explode(',', $ObjCart->getProductCategories($productID));
        $items[0]['attributes']             = $ObjCart->getProductAttributeValues($productID);
        $items[0]['attributeTexts']         = $ObjCart->getProductAttributeValuesText($productID, $language_id);
        $items[0]['productID']              = $productID;
        $items[0]['brandID']                = $brandID;
        $items[0]['businessID']             = $businessID;
        $product_details_array['items']     = $items;
        $today                              = date("Y-m-d");
        $applied_promotions                 = array();
        $promoApp                           = !empty($promoApp) ? $promoApp:'';
        if($promoApp!='') {
            $promoApp = ",'".$this->escape($promoApp)."'";
        }
        $sql                                = "
				SELECT
					*
				FROM
					" . DB_PREFIX . "cart_rules cartRul
				LEFT JOIN
					" . DB_PREFIX . "cart_rule_user_group cartRulUseGro
				ON (cartRulUseGro.ruleID=cartRul.ruleID)
				LEFT JOIN 
					" . DB_PREFIX . "cart_rule_details cartRulDet
				ON (cartRulDet.ruleID=cartRul.ruleID AND cartRulDet.languageID=" . (int) $current_language_id . ")
				WHERE
					IF(DATE_FORMAT(cartRul.fromDate, '%Y-%m-%d'),DATE_FORMAT(cartRul.fromDate, '%Y-%m-%d')<='" . $today . "',1)
					AND IF(DATE_FORMAT(cartRul.toDate, '%Y-%m-%d'),DATE_FORMAT(cartRul.toDate, '%Y-%m-%d')>='" . $today . "',1)
					AND cartRul.status='A'
					AND cartRul.couponType=1 
					AND cartRulUseGro.userGroupID=" . (int) $user_group_id . " ";
        $sql .= " AND cartRul.promoWebAppEnabled in ('Both'".$promoApp.")";        
	$sql .= "   GROUP BY cartRul.ruleID ORDER BY cartRul.priority";
        $promotions_result                  = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        $cart['extra']['userCheckoutEmail'] = isset($cart['extra']['userCheckoutEmail']) ? $cart['extra']['userCheckoutEmail'] : '';
        $user_email                         = ($user_id > 0) ? $user_email : $cart['extra']['userCheckoutEmail'];
        if (count($promotions_result) > 0) {
            foreach ($promotions_result as $k => $v) {
                if ($v['maxUsageCount'] > 0) {
                    $usage_count = $ObjCart->getRuleUsageCount($v['ruleID']);
                    if ($usage_count >= $v['maxUsageCount']) {
                        continue;
                    }
                }
                if ($v['maxUsagePerPerson'] > 0 && $user_email != '') {
                    $usage_count = $ObjCart->getRuleUsageCount($v['ruleID'], $user_email);
                    if ($usage_count >= $v['maxUsagePerPerson']) {
                        continue;
                    }
                }
                $promotions[$k]                    = $v;
                $promotions[$k]['conditions']      = !empty($v['conditions']) ? unserialize($v['conditions']) : array();
                $promotions[$k]['bonusConditions'] = !empty($v['bonusConditions']) ? unserialize($v['bonusConditions']) : array();
                if ($v['stopRules'] == "Y") {
                    break;
                }
            }
        }
        if (isset($promotions) && count($promotions) > 0) {
            foreach ($promotions as $promotion) {
                if ($this->fn_promotion_check($promotion['ruleID'], $promotion['conditions'], $product_details_array, $params, 'conditions', $ObjCart)) {
                    //print_r($promotion);
                    if ($this->fn_promotion_check($promotion['ruleID'], $promotion['bonusConditions'], $product_details_array, $params, 'bonuses', $ObjCart)) {
                        $applied_promotions[$promotion['ruleID']] = $promotion;
                    }
                }
            }
        }
        return $applied_promotions;
    }
    private function fn_promotion_check($promotion_id, $condition, $data, $params, $type = 'conditions', $ObjCart) {
        // This is unconditional promotiontion
        if (empty($condition)) {
            return true;
        }
        $sub_type = ($type == 'conditions') ? 'condition' : 'bonus';
        // if this is the conditions group, check each condition in cycle
        if (!empty($condition[$type])) {
            foreach ($condition[$type] as $cond) {
                if (!empty($cond[$type])) {
                    $c_res = $this->fn_promotion_check($promotion_id, $cond, $data, $params, $type, $ObjCart);
                } else {
                    $c_res = $this->fn_promotion_validate($promotion_id, $cond, $data, $params, $type, $sub_type, $ObjCart);
                }
                if (!isset($result)) {
                    $result = $c_res;
                }
                // Check result, if any condition is correct
                if ($condition['set'] == 'any' && $c_res == $condition['set_value']) {
                    return true;
                    // If we need to compare all conditions, summ the result
                } elseif ($condition['set'] == 'all') {
                    $result = $result & $c_res;
                }
            }
            return ($condition['set_value'] == true) ? $result : !$result;
            // If this is the ordinary condition, check it directly
        } else {
            return $this->fn_promotion_validate($promotion_id, $condition, $data, $params, $type, $sub_type, $ObjCart);
        }
    }
    function fn_promotion_validate($promotion_id, $promotion, $data, $params, $type, $sub_type, $ObjCart) {
        //$schema = fn_promotion_get_schema('conditions');
        $group_type = ($type == 'conditions') ? 'condition_group' : 'bonus_group';
        extract($params);
        $stop_validating = false;
        //print_r($promotion);print_r($data);print_r($params);
        if (empty($promotion[$sub_type])) { // if promotion is unconditional, apply it
            return true;
        }
        $promotion['value'] = !isset($promotion['value']) ? '' : $promotion['value'];
        if ($promotion[$sub_type] != '') {
            $value = '';
            // Ordinary field
            if ($promotion[$group_type] != '') {
                $operand_one;
                if ($promotion[$group_type] == 'cartAttribute') {
                    return true;
                } else if ($promotion[$group_type] == 'cartItemAttribute') {
                    switch ($promotion[$sub_type]) {
                        //Item Price in cart
                        case 'price':
                            return true;
                            break;
                        //Item Quantity in cart
                        case 'quantity':
                            return true;
                            break;
                        //Row total in cart	
                        case 'row_total':
                            return true;
                            break;
                        //Products	
                        case 'products':
                            if (count($data['items']) > 0) {
                                foreach ($data['items'] as $v) {
                                    $product_id = $v['productID'];
                                    if (isset($promotion['options']) && count($promotion['options'][$product_id]['combinations']) > 0) {
                                        $combination_string = implode(",", $promotion['options'][$product_id]['combinations']);
                                        if ($promotion['operator'] == 'nin') {
                                            if ($ObjCart->fn_promotion_validate_attribute($v['combinationHash'], $combination_string, 'in')) {
                                                return false;
                                            } else {
                                                return true;
                                            }
                                        } else {
                                            if ($ObjCart->fn_promotion_validate_attribute($v['combinationHash'], $combination_string, $promotion['operator'])) {
                                                return true;
                                            }
                                        }
                                    } else {
                                        if ($promotion['operator'] == 'nin') {
                                            if ($ObjCart->fn_promotion_validate_attribute($v['productID'], $promotion['value'], 'in')) {
                                                return false;
                                            } else {
                                                return true;
                                            }
                                        } else {
                                            if ($ObjCart->fn_promotion_validate_attribute($v['productID'], $promotion['value'], $promotion['operator'])) {
                                                return true;
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                    }
                } else if ($promotion[$group_type] == 'productAttribute') {
                    switch ($promotion[$sub_type]) {
                        // item Categories
                        case 'categories':
                            if (count($data['items']) > 0) {
                                foreach ($data['items'] as $v) {
                                    if ($promotion['operator'] == 'nin') {
                                        if ($ObjCart->fn_promotion_validate_attribute($v['categories'], $promotion['value'], 'in')) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    } else {
                                        if ($ObjCart->fn_promotion_validate_attribute($v['categories'], $promotion['value'], $promotion['operator'])) {
                                            return true;
                                        }
                                    }
                                }
                            }
                            break;
                        // item attributes	
                        case 'attributes':
                            if (count($data['items']) > 0) {
                                foreach ($data['items'] as $v) {
                                    if ($promotion['value'] != '') {
                                        $attributeTexts = (isset($v['attributeTexts'][$promotion['condition_element']]) ? $v['attributeTexts'][$promotion['condition_element']] : '');
                                        if ($promotion['operator'] == 'nin') {
                                            if ($ObjCart->fn_promotion_validate_attribute($attributeTexts, $promotion['value'], 'in')) {
                                                return false;
                                            } else {
                                                return true;
                                            }
                                        } else {
                                            if ($ObjCart->fn_promotion_validate_attribute($attributeTexts, $promotion['value'], $promotion['operator'])) {
                                                return true;
                                            }
                                        }
                                    } else {
                                        $attributes = (isset($v['attributes'][$promotion['condition_element']]) ? $v['attributes'][$promotion['condition_element']] : '');
                                        if ($promotion['operator'] == 'nin') {
                                            if ($ObjCart->fn_promotion_validate_attribute($attributes, $promotion['value_select'], 'in')) {
                                                return false;
                                            } else {
                                                return true;
                                            }
                                        } else {
                                            if ($ObjCart->fn_promotion_validate_attribute($attributes, $promotion['value_select'], $promotion['operator'])) {
                                                return true;
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        // item brands
                        case 'brands':
                            if (count($data['items']) > 0) {
                                foreach ($data['items'] as $v) {
                                    if ($promotion['operator'] == 'nin') {
                                        if ($ObjCart->fn_promotion_validate_attribute($v['brandID'], $promotion['value'], 'in')) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    } else {
                                        if ($ObjCart->fn_promotion_validate_attribute($v['brandID'], $promotion['value'], $promotion['operator'])) {
                                            return true;
                                        }
                                    }
                                }
                            }
                            break;
                        // item brands
                        case 'business':
                            if (count($data['items']) > 0) {
                                foreach ($data['items'] as $v) {
                                    if ($promotion['operator'] == 'nin') {
                                        if ($ObjCart->fn_promotion_validate_attribute($v['businessID'], $promotion['value'], 'in')) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    } else {
                                        if ($ObjCart->fn_promotion_validate_attribute($v['businessID'], $promotion['value'], $promotion['operator'])) {
                                            return true;
                                        }
                                    }
                                }
                            }
                            break;
                    }
                }
            }
        }
        return false;
    }
    public function getAvailableShippingMethods($params) {
        extract($params);
        $sql    = " SELECT 
						shiMet.settingsGroupID,
						shiMet.isRealTimeCalculation,
						shiMet.settingsGroupXmlLabel,
						shiMet.settingsGroupKey,
						shiMet.settingsGroupParent,
						shiToPro.baseCharge,
						shiToPro.maxQtyPerShipping,
						shiToPro.chargePerExtraQty,
						shiToPro.taxClassID,
						shiToPro.shippingtoproductID,
						shiToPro.handlingCharge,
						GROUP_CONCAT(DISTINCT deliveryZoneName) AS deliveryZoneNames
					FROM
						" . DB_PREFIX . "shipping_to_product as shiToPro
					LEFT JOIN 
						" . DB_PREFIX . "shipping_methods shiMet
						ON(shiMet.settingsGroupParent!=0 
						AND shiMet.settingsGroupID=shiToPro.shippingServiceID)
					LEFT JOIN 
						" . DB_PREFIX . "product_to_shipping_deliveryzone shiMetDelZon
						ON(shiMetDelZon.shippingtoproductID=shiToPro.shippingtoproductID)
					LEFT JOIN 
						" . DB_PREFIX . "deliveryzone_details delZonDet
						ON(delZonDet.deliveryZoneID=shiMetDelZon.deliveryZoneID AND delZonDet.languageID=" . (int) $current_language_id . ")	
					WHERE 
						shiToPro.productID=" . (int) $product_id . " AND shiToPro.status='A' 
					GROUP BY shiToPro.shippingtoproductID 
					ORDER BY shiMet.settingsGroupPriority ASC";
        $result = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        return $result;
    }
    public function checkCODAvailable($productDefaultCurrency) {
        $sql    = " 	SELECT
							paySetGroupID
						FROM
							" . DB_PREFIX . "payment_settings_group
						WHERE	
							paySetGroupKey='CashOnDeliveryRedemption'
							AND paySetGroupStatus='Active'";
        $result = $this->ObjDatabase->readValueSlave($sql);
        if ($result['paySetGroupID'] > 0) {
            return 'Yes';
        } else {
            return 'No';
        }
    }
    public function getShippingBusinessLocations($businessID, $languageIDs = '') {
        $sql = "
				SELECT
						busLoc.businessLocID,
						busLocDet.locName,
						busLocDet.locAddress1,
						busLocDet.locAddress2,
						busLocDet.locCity,
						busLocDet.locProvince,
						busLoc.locStateID,
						busLoc.locCountryID,
						busLoc.locZip,
						busLoc.locPhone
				
				FROM 
					dp_products  product 
				LEFT JOIN 
					" . DB_PREFIX . "business_locations  busLoc
					
				ON
				(
					product.businessID =  busLoc.businessID 
					AND busLoc.businessLocID = product.shippingOrigin
				)
				LEFT JOIN 
						" . DB_PREFIX . "business_location_details busLocDet
				ON
				(
						busLocDet.businessLocID	= busLoc.businessLocID
						AND	busLocDet.languageID = '" . $languageIDs['Current'] . "'										
				)		
				WHERE  busLoc.locStatus='Active' AND busLoc.businessID='" . $businessID . "' ";
        return $this->ObjDatabase->readValuesSlave($sql);
    }
    public function getBusinessIDByProductOptionID($productOptionID = 0) {
        $sql    = " SELECT
					businessID				 
				FROM 
					" . DB_PREFIX . "product_options productOpt
				LEFT JOIN	
					" . DB_PREFIX . "products as product
					ON (product.productID=productOpt.productID)
				WHERE  productOpt.productOptionID=" . $productOptionID . " LIMIT 0,1";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['businessID'];
    }
    public function getProductShippingOrigin($productID) {
        $sqlGetProducts = "SELECT shippingOrigin FROM " . DB_PREFIX . "products WHERE `productID`=" . $productID;
        return $this->ObjDatabase->getField($sqlGetProducts);
    }
    public function unlinkImages($Image, $destiantion) {
        if (!empty($Image)) {
            $ObjImage = new ImageModel();
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/thumb/' . trim($Image));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/large/' . trim($Image));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/preview/' . trim($Image));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/small/' . trim($Image));
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . 'catalog/' . $destiantion . '/preview-main/' . trim($Image));
        }
    }
    public function getImageName($img_file) {
        $info      = pathinfo($img_file);
        $file_name = basename($img_file, '.' . $info['extension']);
        return $file = $file_name . "." . $info['extension'];
    }
    function array_column(array $input, $column_key, $index_key = null) {
        $result = array();
        foreach ($input as $k => $v)
            $result[$index_key ? $v[$index_key] : $k] = $v[$column_key];
        return $result;
    }
    public function selectSizeChartByCategory($categoryID, $languageIDs) {
        $sql    = "  SELECT productCategorySizeChart FROM
						" . DB_PREFIX . "product_category_details
                                   WHERE
                                        productCategoryID  =       '" . $categoryID . "'
                                   AND
					languageID	=	'" . $languageIDs['Current'] . "' 
                    
                                ";
        $result = $this->ObjDatabase->readValue($sql);
        return $result;
    }
    public function getDeliveryCityDetails($cityText, $languageIDs = '') {
        $sql    = "
				SELECT
						city.cityID,
                                                citDet.cityName
				
				FROM 
						" . DB_PREFIX . "city_details  citDet
				LEFT JOIN 
						" . DB_PREFIX . "cities city
				ON
				(
						citDet.cityID	= city.cityID
						AND	citDet.languageID = '" . $languageIDs['Current'] . "'				
				)		
				WHERE  citDet.cityName LIKE '%" . $cityText . "%' AND city.cityStatus='Active'  ";
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    //Remove
    function cleanUrl() {
        $sql     = "
			
			SELECT 
				productUrl,productID
			FROM 
					`" . DB_PREFIX . "products` 						
			WHERE 
				cleanStatus='No' limit 5000";
        $prodata = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
        foreach ($prodata as $v) {
            if (!empty($v['productUrl'])) {
                $productUrl = $this->fn_clean_productUrl($v['productUrl']);
                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "products SET cleanStatus='Yes',productUrl='" . $productUrl . "' WHERE productID='" . $v['productID'] . "'");
            }
        }
    }
    //Url preproduction sections
    function cleanUrlRewrite() {
        echo $sql = "
			
			SELECT 
				type,rewriteID,requestPath 
			FROM 
					`" . DB_PREFIX . "url_rewrite` 						
			WHERE 
				cleanStatus='No' and type='product' limit 100";
        $prodata = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
        foreach ($prodata as $v) {
            if ((!empty($v['requestPath']))) {
                $requestPath = $this->fn_clean_productUrl($v['requestPath']);
                echo "UPDATE " . DB_PREFIX . "url_rewrite SET cleanStatus='Yes',requestPath='" . $requestPath . "' WHERE rewriteID='" . $v['rewriteID'] . "'";
                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "url_rewrite SET cleanStatus='Yes',requestPath='" . $requestPath . "' WHERE rewriteID='" . $v['rewriteID'] . "'");
            }
        }
    }
    function fn_clean_productUrl($productUrl) {
        if (!empty($productUrl)) {
            $productUrl = html_entity_decode($productUrl);
            return $productUrl = $this->fn_generate_productUrl($productUrl);
        } else
            return "";
    }
    private function fn_generate_productUrl($productName) {
        $string = str_replace(" ", "-", trim($productName)); // Replaces all spaces with hyphens.
        $string = preg_replace('/[^A-Za-z0-9\-]/', '-', $string); // Removes special chars.
        $string = preg_replace('/-+/', '-', $string); // Removes continuous hypens with a single hypen.
        return strtolower($string);
    }
    public function checkUrl() {
        $sql     = "
			
			SELECT 
				requestPath,productUrl,rewriteID
			FROM 
					`" . DB_PREFIX . "url_rewrite` url
					LEFT JOIN
					`" . DB_PREFIX . "products` product
					ON(product.productID=url.objectID)
			WHERE 
				`requestPath` LIKE  '%/-%'";
        $prodata = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
        foreach ($prodata as $v) {
            if ((!empty($v['requestPath']))) {
                $replace     = "/" . rtrim($v['productUrl'], "-") . "-";
                $requestPath = str_replace("/-", $replace, $v['requestPath']);
                //echo "UPDATE ".DB_PREFIX."url_rewrite SET requestPath='".$requestPath."' WHERE rewriteID='".$v['rewriteID']."'";
                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "url_rewrite SET requestPath='" . $requestPath . "' WHERE rewriteID='" . $v['rewriteID'] . "'");
            }
        }
    }
    //Bulk Product Delete
    public function bulkDeleteProducts() {
        if (!empty($_POST['proSku'])) {
            $sku = explode(",", $_POST['proSku']);
            if (!empty($sku)) {
                $sql     = "SELECT 
						productID
					FROM 
							`" . DB_PREFIX . "product_options` 
					WHERE 
						optionSKU  IN(" . implode(",", $sku) . ")";
                $prodata = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
                foreach ($prodata as $p) {
                    $productID = $p['productID'];
                    //Product, Details	,REWRITE				
                    $this->ObjDatabase->setQuery("DELETE product.*, detail.*,rewrite.* 
							FROM `" . DB_PREFIX . "products` product 
							LEFT JOIN
								`" . DB_PREFIX . "product_details` detail 
								ON product.productID = detail.productID
							LEFT JOIN
								`" . DB_PREFIX . "url_rewrite` rewrite
								ON product.productID = rewrite.objectID
							WHERE product.productID = " . $productID);
                    $this->deleteProductImage($productID);
                    //ProductOption, OptionDetails					
                    $this->ObjDatabase->setQuery("DELETE opt.*, optDet.* 
							FROM `" . DB_PREFIX . "product_options` opt
							LEFT JOIN
							`" . DB_PREFIX . "product_option_details` optDet
							ON opt.productOptionID = optDet.productOptionID 
							WHERE opt.productID = " . $productID);
                    //product Media
                    $this->ObjDatabase->setQuery("DELETE 
							FROM `" . DB_PREFIX . "product_media`
							WHERE productID = " . $productID);
                    //categories
                    $this->ObjDatabase->setQuery("DELETE 
							FROM `" . DB_PREFIX . "product_to_category`
							WHERE productID = " . $productID);
                    //Custom option n combinations					
                    $this->ObjDatabase->setQuery("DELETE 
							FROM `" . DB_PREFIX . "product_custom_option_link`
							WHERE productID = " . $productID);
                    $this->ObjDatabase->setQuery("DELETE 
							FROM `" . DB_PREFIX . "product_combination`
							WHERE productID = " . $productID);
                    //Upsell,cross sell,combination
                    $this->ObjDatabase->setQuery("DELETE 
							FROM `" . DB_PREFIX . "product_link_cross_sell`
							WHERE productID = " . $productID);
                    $this->ObjDatabase->setQuery("DELETE 
							FROM `" . DB_PREFIX . "product_link_up_sell`
							WHERE productID = " . $productID);
                    $this->ObjDatabase->setQuery("DELETE 
							FROM `" . DB_PREFIX . "product_link_relation`
							WHERE productID = " . $productID);
                    //Shipping					
                    $this->ObjDatabase->setQuery("DELETE ship.*, del.* 
							FROM `" . DB_PREFIX . "shipping_to_product` ship
							LEFT JOIN
							`" . DB_PREFIX . "product_to_shipping_deliveryzone` del
							ON del.shippingtoproductID = ship.shippingtoproductID 
							WHERE ship.productID = " . $productID);
                    //Attributes
                    $this->ObjDatabase->setQuery("DELETE attr.*, attrDet.* 
							FROM `" . DB_PREFIX . "product_attribute_values` attr
							LEFT JOIN
							`" . DB_PREFIX . "product_attribute_value_details` attrDet
							ON attr.attrValueID = attrDet.attrValueID 
							WHERE attr.productID = " . $productID);
                }
            }
        }
        return true;
    }
    public function updateVariantTitle() {
        $sql     = "SELECT 
						productID,productOptionID
					FROM 
							`" . DB_PREFIX . "product_options` 
					WHERE 
						productOptionID  NOT IN(SELECT 
						productOptionID
					FROM 
							`" . DB_PREFIX . "product_option_details`)";
        $prodata = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
        foreach ($prodata as $p) {
            $pname = $this->ObjDatabase->getField("SELECT productTitle 
													FROM  `" . DB_PREFIX . "product_details` 
													WHERE languageID=1 AND `productID` =" . $p['productID']);
            $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_option_details`
				 (`productOptionID`,
				  `languageID`,
				  `productOptionName`
				 )
				 VALUES
				 ('" . $p['productOptionID'] . "',
				  '1',
				  '" . $this->escape($pname) . "'
				 )");
        }
    }
	public function getProductBusinessDetails($params) {
        extract($params);
			$sql = " SELECT					
						product.productID,
						product.businessID,
						bus.businessDefaultLanguageID,
						bus.businessEmail,
						bus.businessCFirstName,
						bus.businessCLastName                      
						";
       
        
        $sql .= " FROM 
										" . DB_PREFIX . "products   AS product 
																		
									INNER JOIN 
											" . DB_PREFIX . "business AS bus 
										ON (
											product.businessID = bus.businessID 
											)";

       
        $sql .= " WHERE product.productID = " . (int) $selectedProductID . "
			AND product.productStatus!='Deleted' ";
        $resSelectProducts = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        return $resSelectProducts;
    }
    public function insertBuyBox($productID){
            $sqlInsert     =  "INSERT INTO `".DB_PREFIX."buybox` (`baseProductID`) VALUES('".$productID."')";
            $result        =  $this->ObjDatabase->setQuery($sqlInsert);
            $buyboxID      =  $this->ObjDatabase->getInsertId();
            
            if($buyboxID>0){
                $sqlInsertDet  =  "INSERT INTO `".DB_PREFIX."buybox_details` (`buyboxID`,`productID`) VALUES('".$buyboxID."','".$productID."')";
                $resultDet     =  $this->ObjDatabase->setQuery($sqlInsertDet);
                $buyboxDetID      =  $this->ObjDatabase->getInsertId();
                return $buyboxDetID;
            }else{
                return 0;
            }
     }
     private function getBuyBoxCount($productID){
            $sqlSelect       =   "SELECT COUNT(*) as totCount FROM `".DB_PREFIX."buybox_details` WHERE productID = '".$productID."'"; 
            $result          =   $this->ObjDatabase->readValue($sqlSelect);
            return $result['totCount'];
     }
     public function getProductTitleBuybox($languageIDs,$categories="",$businessID=''){
            $baseProductIDs = '';
            if($businessID>0) {
                $sql    = "    SELECT CAST( GROUP_CONCAT( distinct(box.baseProductID) SEPARATOR  ',' ) AS CHAR ) AS baseproductIDs FROM  `".DB_PREFIX."buybox_details` buydet JOIN ".DB_PREFIX."buybox box ON ( buydet.buyboxID = box.buyboxID ) 
                                JOIN dp_products p ON ( p.productID = buydet.productID )  WHERE p.businessID ='".$businessID."' ";
                $result		= $this->ObjDatabase->readValue($sql);
                $baseProductIDs = (!empty($result['baseproductIDs']))?$result['baseproductIDs']:'';
               
            }
            $languageID             = $languageIDs['Current'];
            $defaultLanguageID      = $languageIDs['Default'];
            $sql    = "    SELECT 
                                    productDet.productID,
                                    productDet.productTitle 
                                FROM 
                                        `".DB_PREFIX."buybox` box 
                                INNER JOIN 
                                         `".DB_PREFIX."products` product 
                                            ON (box.baseProductID = product.productID) 
                                INNER JOIN 
                                        `".DB_PREFIX."product_details` productDet 
                                            ON (productDet.productID = product.productID AND languageID='".$languageID."') 
                                LEFT JOIN 
                                        `".DB_PREFIX."product_to_category` productCat 
                                            ON (productCat.productID = product.productID) 
                                WHERE product.productStatus<>'Deleted'";
                if(!empty($categories) && $categories!=''){
                    $sql    .= " AND productCat.productCategoryID IN (".$categories.")";
                }
                if($businessID>0) {
                    $sql    .= " AND product.businessID!='".$businessID."' ";
                    if($baseProductIDs!='')
                    $sql    .= " AND product.productID NOT IN ($baseProductIDs) ";
                }
                $sql    .= " GROUP BY productDet.productID";
                $result		= $this->ObjDatabase->readValues($sql);
                return $result;
     }
      //SAVING BUYBOX PRODUCT DETAILS(ADD/EDIT)
        public function saveProductLinkBuybox($languageIDs,$POST,$pid,$prodReq=''){
            $buyboxproductID       =   $POST['buyboxproductID'];
            $sqlSelect          =   "SELECT buyboxID FROM `".DB_PREFIX."buybox` WHERE baseProductID = '".$buyboxproductID."'"; 
            $result             =   $this->ObjDatabase->readValue($sqlSelect);
            //
            $this->ObjDatabase->setQuery("DELETE FROM `".DB_PREFIX."buybox_details` WHERE productID = '".$pid."'");
            $sqlInsert  =  "INSERT INTO `".DB_PREFIX."buybox_details` (`buyboxID`,`productID`) VALUES('".$result['buyboxID']."','".$pid."')";
            $res        =  $this->ObjDatabase->setQuery($sqlInsert);
            //
            $businessID             = $POST['businessID'];
            
            $productStatus             = isset($POST['productStatus'])?$POST['productStatus']:'';
            if($productStatus=='Inactive'){
                $productStatus = 'Inactive';
            }else if($productStatus=='Pending'){
                $productStatus = 'Pending';
            }else{
                $productStatus = 'Buybox';
            }
            if($prodReq!='') {
                $productStatus = 'Pending';
            }
            $productMinBuyLimit        = $POST['productMinBuyLimit'];           
            $productMaxBuyLimit        = (!empty($POST['productMaxBuyLimit']))? $POST['productMaxBuyLimit'] : 'NULL';
            $productCommissionRate     = (isset($POST['productCommissionRate']))?$POST['productCommissionRate']:'';
            $productServiceFee         = (isset($POST['productServiceFee']))?$POST['productServiceFee']:'';
            $productQuantityNotifyAt   = (!empty($POST['productQuantityNotifyAt']))? $POST['productQuantityNotifyAt'] : 1 ;
            $showQuantityAvailable  =   $this->escape($POST['showQuantityAvailable']);
            $isProductDeal='No';
           
            $sqlUpdateProducts         = " UPDATE 
                                                    `".DB_PREFIX."products` 
                                         SET 
                                                    `businessID`='".$businessID."',
                                                    `productMinBuyLimit`='".$productMinBuyLimit."',
                                                    `productMaxBuyLimit`=".$productMaxBuyLimit.",
                                                    `productCommissionRate`='".$productCommissionRate."',
                                                    `productServiceFee`='".$productServiceFee."',
                                                    `productQuantityNotifyAt`='".$productQuantityNotifyAt."',
                                                    `showQuantityAvailable`='".$showQuantityAvailable."',
                                                    `productSoldQuantity`=0,
                                                    `buyboxStatus`='Yes',
                                                     `isProductDeal`='".$isProductDeal."',
                                                    `productStatus`='".$productStatus."'";
            $sqlUpdateProducts	.=	" WHERE `productID` = '".$pid."'";	
            $this->ObjDatabase->setQuery($sqlUpdateProducts);
            //
            $data = $this->ObjDatabase->readValues("SELECT productTitle,languageID FROM `".DB_PREFIX."product_details` WHERE productID =".$buyboxproductID,MYSQLI_ASSOC);
            foreach ($data as $v) {
                //if ($v['languageID'] == 'CART_LANGUAGE') {
                        $orig_name = $this->escape($v['productTitle']);
                        $this->ObjDatabase->setQuery("
                        UPDATE 
                                        `".DB_PREFIX."product_details` 
                        SET 
                                        `productTitle`='".$orig_name."' 
                        WHERE 
                                        `productID` = '".$pid."' AND `languageID`='".$v['languageID']."'");
                //}
            }
            //
            $options      	= isset($POST['productOptionsGroup'])?$POST['productOptionsGroup']:'';
            $data1 = $this->ObjDatabase->readValues("SELECT productOptionID FROM `".DB_PREFIX."product_options` WHERE productID=".$pid,MYSQLI_ASSOC);
            
            if($options[1]['productOptionProductPrice']==''){
                $options[1]['productOptionProductPrice']=$options[1]['productOptionRegularPrice'];
            }
            $i = 1;
            foreach ($data1 as $v) {

                if($options[$i]['productOptionQuantity']=="")
                $productQuantityUnlimited 	= "1";
                else
                $productQuantityUnlimited 	= "0";
                // Product option update 
                $productOptionID = $v['productOptionID'];
               
                $this->ObjDatabase->setQuery("
                        UPDATE 
                                        `".DB_PREFIX."product_options` 
                        SET 
                                    `productOptionRegularPrice`='".$options[$i]['productOptionRegularPrice']."',
                                    `optionSKU`='".$options[$i]['optionSKU']."',
                                    `optionBarCode`='".$options[$i]['optionBarCode']."',
                                    `productOptionProductPrice`='".$options[$i]['productOptionProductPrice']."',
                                    `productOptionQuantity`='".$options[$i]['productOptionQuantity']."',
                                    `productQuantityUnlimited` = '".$productQuantityUnlimited."' ,
                                    `productOptionCashBack` = '".$options[$i]['productOptionCashBack']."'
                        WHERE 
                                    `productOptionID` = '".$productOptionID."' ");
                // Product option details update 
                $this->ObjDatabase->setQuery("UPDATE `".DB_PREFIX."product_option_details`
                                  SET 	`productOptionName`='".$orig_name."'
                                  WHERE `productOptionID`='".$productOptionID."'");
                $this->groupTierPriceUpdate($options[$i],$productOptionID);
                $i++;
            }
        }
         public function destroyOptionValues($productID)
		{
                    $sqlSelect	= "	SELECT productOptionID 
                                                    FROM
                                    " . DB_PREFIX . "product_options	
                            WHERE
                                    `productID` ='" . $productID."' ";
                    $result	= $this->ObjDatabase->readValues($sqlSelect);
                    if(count($result)>0){
                        foreach($result as $res){
                          $sqlDel1   =  "DELETE
								FROM
						" . DB_PREFIX . "product_option_details	
					WHERE
						`productOptionID` ='" . $res['productOptionID']."'";
                          $result1	= $this->ObjDatabase->setQuery($sqlDel1);
                          
                          $sqlDel2   =  "DELETE
								FROM
						" . DB_PREFIX . "variant_group_price	
					WHERE
						`productOptionID` ='" . $res['productOptionID']."'";
                          $result2	= $this->ObjDatabase->setQuery($sqlDel2);
                          
                          $sqlDel3   =  "DELETE
								FROM
						" . DB_PREFIX . "variant_tier_price	
					WHERE
						`productOptionID` ='" . $res['productOptionID']."'";
                          $result3	= $this->ObjDatabase->setQuery($sqlDel3);
                        }
                        $sqlDel1   =  "DELETE
								FROM
						" . DB_PREFIX . "product_options	
					WHERE
						`productID` ='" .$productID."'";
                        $result    = $this->ObjDatabase->setQuery($sqlDel1);
                    }
                    return $result1;
		
		}
                public function destroyTablesWithProductID($productID,$table)
		{
				$sql	= "	DELETE
								FROM
						" . DB_PREFIX . "$table	
					WHERE
						`productID` ='" . $productID."' ";
				$result	= $this->ObjDatabase->setQuery($sql);
				return $result;
		
		}
                public function destroyAttributeValues($productID,$languageID)
		{
                    $sqlSelect	= "	SELECT attrValueID 
                                                    FROM
                                    " . DB_PREFIX . "product_attribute_values	
                            WHERE
                                    `productID` ='" . $productID."' ";
                    $result	= $this->ObjDatabase->readValues($sqlSelect);
                    if(count($result)>0){
                        foreach($result as $res){
                          $sqlDel   =  "DELETE
								FROM
						" . DB_PREFIX . "product_attribute_value_details	
					WHERE
						`attrValueID` ='" . $res['attrValueID']."'";
                          $result	= $this->ObjDatabase->setQuery($sqlDel);
                        }
                        $sqlDel1   =  "DELETE
								FROM
						" . DB_PREFIX . "product_attribute_values	
					WHERE
						`productID` ='" .$productID."'";
                        $result    = $this->ObjDatabase->setQuery($sqlDel1);
                    }
                    return $result1;
		
		}
                public function destroyUrlWithProductID($productID)
		{
				$sql	= "	DELETE
								FROM
						" . DB_PREFIX . "url_rewrite	
					WHERE
						`objectID` ='" . $productID."' AND type = 'product'";
				$result	= $this->ObjDatabase->setQuery($sql);
				return $result;
		
		}
                public function deleteBuyBox($productID){
                    $this->ObjDatabase->setQuery("DELETE FROM `".DB_PREFIX."buybox_details` WHERE productID = '".$productID."'");
                    $this->ObjDatabase->setQuery("UPDATE `".DB_PREFIX."products` SET buyboxStatus = 'No' WHERE productID = '".$productID."'");
                }
                 public function checkBuyboxProduct($productID){
                    $sqlSelect    =    "SELECT COUNT(buyboxDet.buyboxDetailsID) as cntProd FROM ".DB_PREFIX."buybox_details buyboxDet 
                                        LEFT JOIN ".DB_PREFIX."buybox buybox ON (buybox.buyboxID = buyboxDet.buyboxID)
                                        WHERE buyboxDet.$productID = '".$productID."' AND buybox.baseProductID != '".$productID."'";
                    //echo $sqlSelect; exit;
                    $result       =    $this->ObjDatabase->readValue($sqlSelect);
                    return $result['cntProd'];
                }
                
                public function getBuyboxProductCount($productID){
                    $sqlSelect    =    "SELECT COUNT(buyboxDet.buyboxDetailsID) as cntProd FROM ".DB_PREFIX."buybox_details buyboxDet 
                                        LEFT JOIN ".DB_PREFIX."buybox buybox ON 
                                        (buybox.buyboxID = buyboxDet.buyboxID AND buybox.baseProductID = '".$productID."')
                                        WHERE buyboxDet.buyboxID = buybox.buyboxID";
                    $result       =    $this->ObjDatabase->readValue($sqlSelect);
                    return $result['cntProd'];
                }
                public function getBuyboxBusinessIds($productID,$currProductID=''){
                    if($currProductID=='') { $currProductID = 0; }
                    /*$sqlSelect   =  "SELECT product.businessID FROM `".DB_PREFIX."products` product 
                                     INNER JOIN ".DB_PREFIX."buybox_details buyboxDet ON (buyboxDet.productID = product.productID)
                                     INNER JOIN ".DB_PREFIX."buybox buybox ON (buybox.buyboxID = buyboxDet.buyboxID)
                                     WHERE buybox.baseProductID = '".$productID."'
                                     AND product.productStatus<>'Deleted' GROUP BY product.businessID";*/
                    $sqlSelect   =  " SELECT product.businessID FROM ".DB_PREFIX."buybox buybox INNER JOIN ".DB_PREFIX."buybox_details 
                                      buyboxDet ON (buybox.`buyboxID`=buyboxDet.`buyboxID`) INNER JOIN ".DB_PREFIX."products product 
                                      ON (buyboxDet.productID=product.productID && buyboxDet.productID!=".$currProductID.")  WHERE buybox.buyboxID=(SELECT `buyboxID` 
                                      FROM ".DB_PREFIX."buybox WHERE `baseProductID`='".$productID."') AND product.productStatus<>'Deleted' GROUP BY product.businessID";
                    
                    $result      =   $this->ObjDatabase->readValues($sqlSelect,MYSQLI_ASSOC);	
                    $resBusIds   =   (@array_map(array($this, 'filterBusinessIDs'),$result));                    
                    return $resBusIds;
                }
                public function filterBusinessIDs($result)     {
                  return $result['businessID']; 
                }

		public function updateProductDeal(){
            $sql = "
				UPDATE
				`" . DB_PREFIX . "products`
		SET
				`isProductDeal`='No'
		WHERE
				DATE_FORMAT(dealEndTime, '%Y-%m-%d') < DATE_FORMAT(NOW(), '%Y-%m-%d')
				AND 
				`isProductDeal` = 'Yes'";
		$result = $this->ObjDatabase->setQuery($sql);
                
                $sql = "
				UPDATE
				`" . DB_PREFIX . "products`
		SET
				`isProductDeal`='Yes'
                WHERE
				DATE_FORMAT(dealStartTime ,'%Y-%m-%d') <= DATE_FORMAT(NOW(), '%Y-%m-%d')
				AND 
                                DATE_FORMAT(dealEndTime ,'%Y-%m-%d') >= DATE_FORMAT(NOW(), '%Y-%m-%d')
                                AND
				`setAsProductDeal` = 'Yes'";
		$result = $this->ObjDatabase->setQuery($sql);
        }
	public function exeQuery($sql,$type='') {
            if($type=='') {
                $res = $this->ObjDatabase->readValue($sql);
            } else {
                $res = $this->ObjDatabase->readValues($sql);
            }
            return $res;
        }
        public function setSqlQuery($sql,$type='') {
            $res = $this->ObjDatabase->setQuery($sql);  
			if($type!='') {
				return  $this->ObjDatabase->getInsertId();
			} else { return $res; }
            
        }	
        public function getSubstitueProductAvail($attrSetID,$productID){
            $currDate	=       date('Y-m-d');
            $sqlSelect      =       "SELECT COUNT(*) as prodCount FROM " . DB_PREFIX . "products
                                     WHERE attributeSetID = '".$attrSetID."'
                                     AND attributeSetID <> '1'
                                     AND productID != '".$productID."'
                                     AND productStatus = 'Active'
                                     AND (
                                            productStartTime <= " . $currDate . " 
                                            AND
                                            (
                                                    productEndTime = '0000-00-00'
                                                    OR
                                                    productEndTime >=	" . $currDate . "
                                            )
                                    )";
            $result = $this->ObjDatabase->getField($sqlSelect);
            return $result;
        }   
        
        public function getbusinessGroupPrice($productOptionID,$businessID){
            $sqlSelect          =       "SELECT * FROM ".DB_PREFIX."variant_group_price
                                         WHERE productOptionID = '".$productOptionID."'
                                         AND businessID = '".$businessID."'
                                         ORDER BY optionToGroupID ASC";
            $result = $this->ObjDatabase->readValues($sqlSelect);
            return $result;
        }
        
        public function getbusinessReqGroupPrice($productOptionID,$businessID){
            $sqlSelect          =       "SELECT * FROM ".DB_PREFIX."variant_request_group_price
                                         WHERE productOptionID = '".$productOptionID."'
                                         AND businessID = '".$businessID."'
                                         ORDER BY optionToGroupID ASC";
            $result = $this->ObjDatabase->readValues($sqlSelect);
            return $result;
        }
		
        public function getProductBusinessOptions($prodOptionBusID){
            $sqlSelect           =      "SELECT * FROM ".DB_PREFIX."products_options_business 
                                         WHERE productOptionBusinessID = '".$prodOptionBusID."'";
            $result              =      $this->ObjDatabase->readValue($sqlSelect);
            return $result;
}
        
        public function deleteMerchant($productOptionBusinessID,$productOptionID){
            $sqlSelect           =      "SELECT COUNT(*) as cntDef FROM ".DB_PREFIX."products_options_business WHERE
                                         businessOptionDefault = 'Yes' AND productOptionBusinessID = '".$productOptionBusinessID."'";
            $result              =      $this->ObjDatabase->getField($sqlSelect);
            
            $sqlSelBusinessID    =      "SELECT businessID FROM ".DB_PREFIX."products_options_business 
                                         WHERE productOptionBusinessID = '".$productOptionBusinessID."'";
            $selBusinessID       =      $this->ObjDatabase->getField($sqlSelBusinessID);
            
            $sqlDelete           =      "DELETE FROM ".DB_PREFIX."products_options_business 
                                         WHERE productOptionBusinessID = '".$productOptionBusinessID."'";
            $resDelete           =      $this->ObjDatabase->setQuery($sqlDelete);
            
            $sqlDeleteGroupPrice =      "DELETE FROM ".DB_PREFIX."variant_group_price 
                                         WHERE productOptionID = '".$productOptionID."'
                                         AND businessID = '".$selBusinessID."'";
            $resDeleteGroupPrice =       $this->ObjDatabase->setQuery($sqlDeleteGroupPrice);
            
            if($result>0){
                $sqlUpdate       =      "UPDATE ".DB_PREFIX."products_options_business SET
                                                        businessOptionDefault = 'Yes'
                                                     WHERE productOptionID = '".$productOptionID."'
                                                     ORDER BY productOptionBusinessID ASC LIMIT 1";
                $resUpdate       =      $this->ObjDatabase->setQuery($sqlUpdate);
                
                $sqlSelBus       =      "SELECT prodOptBus.businessID,
                                                prodOpt.productID,
                                                prodOptBus.productOptionID,
                                                prodOptBus.productOptionRegularPrice,
                                                prodOptBus.productOptionProductPrice,
                                                prodOptBus.productOptionQuantity
                                         FROM ".DB_PREFIX."products_options_business prodOptBus
                                         INNER JOIN ".DB_PREFIX."product_options prodOpt ON 
                                         (prodOpt.productOptionID = prodOptBus.productOptionID) 
                                         WHERE prodOptBus.businessOptionDefault = 'Yes' 
                                         AND prodOptBus.productOptionID = '".$productOptionID."'
                                         ORDER BY productOptionBusinessID ASC LIMIT 1";
                $resSelBus       =      $this->ObjDatabase->readValue($sqlSelBus);
                
                if($resSelBus['productID']>0){
                    $sqlUpdProd      =      "UPDATE ".DB_PREFIX."products SET businessID = '".$resSelBus['businessID']."'
                                             WHERE productID = '".$resSelBus['productID']."'";
                    $resUpdProd      =      $this->ObjDatabase->setQuery($sqlUpdProd);
                }
                
                if($resSelBus['productOptionID']>0){
                    $busQuanUnlimited   =       ($resSelBus['productOptionQuantity'] == "") ? "1" : "0";
                    $sqlUpdateOpt       =       "UPDATE ".DB_PREFIX."product_options 
                                                SET productOptionRegularPrice = '".$resSelBus['productOptionRegularPrice']."',
                                                    productOptionProductPrice = '".$resSelBus['productOptionProductPrice']."',
                                                    productOptionQuantity = '".$resSelBus['productOptionQuantity']."',
                                                    productQuantityUnlimited = '".$busQuanUnlimited."',
                                                    productOptionStatus = 'Active'
                                                WHERE productOptionID = '".$resSelBus['productOptionID']."'";   
                    $resUpdateOpt       =       $this->ObjDatabase->setQuery($sqlUpdateOpt);
                }
            }
        }
        
        public function getProductBusOptions($languageIDs,$productID,$userGroupID=-1,$combinationHash="",$frontendView="",$showAllProducts=''){
			 if($showAllProducts=='Yes') {
				$updprodstatus = " IN ('Active','Inactive') ";
			} else {
				$updprodstatus = " = 'Active' ";				
			}
            $sqlSelect          =    "SELECT prodOpt.productOptionID,
                                             prodOptDet.productOptionName
                                             FROM ".DB_PREFIX."product_options prodOpt 
                                             INNER JOIN ".DB_PREFIX."product_option_details prodOptDet ON
                                             (prodOptDet.productOptionID = prodOpt.productOptionID AND
                                              prodOptDet.languageID = '".$languageIDs['Current']."') 
                                      WHERE prodOpt.productID = '".$productID."'
                                       AND prodOpt.productOptionStatus ".$updprodstatus."";
            $result             =    $this->ObjDatabase->readValues($sqlSelect);
            $businessOptions    =    array();
            $inventotyTrackLevel        =       $this->getInventoryTrackLevel($productID);
            $incr               =    0;
            foreach($result as $res){
                if($inventotyTrackLevel=="Options"){
                    if($combinationHash!=""){
                        $combinationID          =       $this->getCombinationByHash($combinationHash,$showAllProducts);
                    }else{
                        $combinationID          =       $this->getCombinationID($productID);
                    }
                }else{
                    $combinationID          =       0;
                }
                $businessOptions[$res['productOptionID']]['productOptionID']     =  $res['productOptionID'];
                $businessOptions[$res['productOptionID']]['productOptionName']   =  $res['productOptionName'];
                $businessOptions[$res['productOptionID']]['busOptions']          =  $this->getBusinessOptions($languageIDs,$res['productOptionID'],$userGroupID,$inventotyTrackLevel,$combinationID,$frontendView,'',$showAllProducts);
                $incr++;
            }
            return $businessOptions;
            
        }
        
        public function getCombinationByHash($combinationHash,$showAllProducts=''){
			if($showAllProducts=='Yes') {
				$updprodcombstatus = " IN ('A','I') ";
			} else {
				$updprodcombstatus = " = 'A' ";				
			}
            $sqlSelect          =       "SELECT combinationID FROM ".DB_PREFIX."product_combination
                                         WHERE combinationHash = '".$combinationHash."'
                                         AND status ".$updprodcombstatus." ";
            $result             =       $this->ObjDatabase->getField($sqlSelect);
            return $result;
        }
        
        public function getBusinessOptionCount($productOptionID,$productID=0,$comb="No",$combinationHash="",$showAllProducts=''){
			if($showAllProducts=='Yes') {
					$updprodstatus = " IN ('Active','Inactive') ";
					$updprodcombstatus = " IN ('A','I') ";
				} else {
					$updprodstatus = " = 'Active' ";		
					$updprodcombstatus = " = 'A' ";
				}
            if($comb=="No"){
                $sqlSelect          =       "SELECT COUNT(*) as cntOption FROM ".DB_PREFIX."products_options_business
                                             WHERE productOptionID = '".$productOptionID."'
                                             AND businessOptionDefault!='Yes'
                                             AND busProductStatus ".$updprodstatus."
                                             AND (productQuantityUnlimited='1' OR productOptionQuantity>0)";
                $result             =       $this->ObjDatabase->getField($sqlSelect);
                return $result;
            }else if($productID>0 && $comb=="Yes"){
                $selectBusID        =       "SELECT businessID FROM ".DB_PREFIX."products_options_business
                                             WHERE productOptionID = '".$productOptionID."'
                                             AND businessOptionDefault='Yes'";
                $defBusID           =       $this->ObjDatabase->getField($selectBusID);
                
                $sqlAppend          =       "";
                if($combinationHash!=""){
                    $sqlAppend      =       " AND prodComb.combinationHash='".$combinationHash."'";
                }
                
                $sqlSelect          =       "SELECT COUNT(prodCombBus.combBusinessID) as cntOption
                                             FROM ".DB_PREFIX."product_combination_business prodCombBus
                                             INNER JOIN ".DB_PREFIX."product_combination prodComb ON 
                                                 (prodComb.combinationID = prodCombBus.combinationID)
                                             WHERE prodComb.productID = '".$productID."'
                                             $sqlAppend
                                            AND prodComb.status ".$updprodcombstatus."
                                             AND prodCombBus.businessCombQuantity>0
                                             AND prodCombBus.businessID != '".$defBusID."'";
                $result             =       $this->ObjDatabase->getField($sqlSelect);
//                if($result==1){
//                    $result = 0;
//                }
                return $result;
            }
        }
        
        public function getDefaultOptionID($productID){
            $sqlSelect          =       "SELECT productOptionID FROM ".DB_PREFIX."product_options WHERE
                                         productID = '".$productID."' AND productOptionDefault = 'Yes'";
            $result             =        $this->ObjDatabase->getField($sqlSelect);
            return $result;
        }
        
        public function getProductInvLevel($productID){
            $sqlSelect          =       "SELECT InventoryTrackLevel FROM ".DB_PREFIX."products WHERE productID = '".$productID."'";
            $result             =        $this->ObjDatabase->getField($sqlSelect);
            return $result;
        }
        
        public function changeDefaultBusiness($productID,$productOptionID,$businessID){
            if($productOptionID>0 && $businessID>0){
                $sqlSelect          =       "SELECT 
                                             productOptionBusinessID,
                                             productOptionRegularPrice,
                                             productOptionProductPrice,
                                             productOptionQuantity,
                                             productQuantityUnlimited
                                             FROM ".DB_PREFIX."products_options_business
                                             WHERE productOptionID = '".$productOptionID."'
                                             AND businessID = '".$businessID."'";
                $result             =       $this->ObjDatabase->readValue($sqlSelect);  
                if($result['productOptionBusinessID']>0){
                    $sqlUpdate1     =       "UPDATE ".DB_PREFIX."products_options_business 
                                             SET businessOptionDefault = 'No' 
                                             WHERE productOptionID = '".$productOptionID."'";
                    $this->ObjDatabase->setQuery($sqlUpdate1);  
                    
                    $sqlUpdate2     =       "UPDATE ".DB_PREFIX."products_options_business 
                                             SET businessOptionDefault = 'Yes' 
                                             WHERE productOptionID = '".$productOptionID."'
                                             AND businessID = '".$businessID."'";
                    $this->ObjDatabase->setQuery($sqlUpdate2);
                    
                    $sqlUpdate3     =        "UPDATE ".DB_PREFIX."products SET businessID = '".$businessID."'
                                              WHERE productID = '".$productID."'";
                    $this->ObjDatabase->setQuery($sqlUpdate3);
                    
                    $sqlUpdate4     =        "UPDATE ".DB_PREFIX."product_options 
                                                SET productOptionRegularPrice = '".$result['productOptionRegularPrice']."',
                                                    productOptionProductPrice = '".$result['productOptionProductPrice']."',
                                                    productOptionQuantity = '".$result['productOptionQuantity']."',
                                                    productQuantityUnlimited = '".$result['productQuantityUnlimited']."',
                                                    productOptionStatus = 'Active'
                                                WHERE productOptionID = '".$productOptionID."'";   
                    $this->ObjDatabase->setQuery($sqlUpdate4);
                    
                    return 1;
                }else{
                    return 0;
                }
            }
        }
        
        public function getBasicProductDetails($languageIDs,$productID){
            $sqlSelect              =           "SELECT product.productID,
                                                        product.productImage,
                                                        product.productMinBuyLimit,
                                                        product.productMaxGiftBuy,
                                                        product.productMaxBuyLimit,
                                                        product.InventoryTrackLevel,
                                                        productDet.productTitle,
                                                        productDet.productDescription,
                                                        productDet.productShortDescription,
                                                        productDet.productFinePrint,
                                                        productDet.productHighlights
                                                 FROM ".DB_PREFIX."products product
                                                 INNER JOIN ".DB_PREFIX."product_details productDet ON
                                                        (productDet.productID = product.productID AND
                                                         productDet.languageID = '".$languageIDs['Current']."')
                                                 WHERE product.productID = '".$productID."'";
            $result                   =          $this->ObjDatabase->readValue($sqlSelect);
            return $result;
        }
        
        public function getProductBusinessOptionsDetails($languageIDs = NULL, $productID, $businessID=0,$addBuyBox='no') {
        $currentLanguageID = $languageIDs['Current'];
        if($addBuyBox=="yes"){
            $sqlProdBusOptionJoin       =       "LEFT";
        }else{
            $sqlProdBusOptionJoin       =       "LEFT";
        }
        $sql = "
					SELECT
						productOpt.productOptionID,
                                                productOpt.productID,
						productOpt.optionSKU,
						productOpt.productOptionStatus,
						productOptDet.productOptionName,
                                                productOptBus.productOptionBusinessID,
                                                productOptBus.businessID,
                                                productOptBus.businessOptionSKU,
                                                productOptBus.productOptionRegularPrice,
                                                productOptBus.productOptionProductPrice,
                                                productOptBus.productOptionQuantity,
                                                productOptBus.productQuantityUnlimited,
                                                productOptBus.soldQuantity,
                                                productOptBus.busWareHouse,
                                                productOptBus.businessDispatchTime,
                                                productOptBus.busProductStatus,
                                                productOptBus.businessOptionDefault
					FROM
						" . DB_PREFIX . "product_options AS productOpt
					INNER JOIN
						" . DB_PREFIX . "product_option_details AS productOptDet
						ON productOpt.productOptionID=productOptDet.productOptionID
						AND productOptDet.languageID = '" . $currentLanguageID . "'
                                        $sqlProdBusOptionJoin JOIN
						" . DB_PREFIX . "products_options_business AS productOptBus ON
                                                (productOptBus.productOptionID=productOpt.productOptionID
						 AND productOptBus.businessID = '" . $businessID . "')
					WHERE
						productOpt.productID='" . (int) $productID . "'
                                                AND productOpt.productOptionStatus  = 'Active'";
        $sql .= "  
					ORDER BY
						productOptionDefault DESC,
						productOpt.productOptionID ";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        return $result;
    }
    
    public function getProductReqBusinessOptionsDetails($languageIDs = NULL, $productID, $businessID=0,$addBuyBox='no') {
        $currentLanguageID = $languageIDs['Current'];
        if($addBuyBox=="yes"){
            $sqlProdBusOptionJoin       =       "LEFT";
        }else{
            $sqlProdBusOptionJoin       =       "LEFT";
        }
        $sql = "
					SELECT
						productOpt.productOptionID,
                                                productOpt.productID,
						productOpt.optionSKU,
						productOpt.productOptionStatus,
						productOptDet.productOptionName,
                                                productOptBus.productReqOptionBusinessID,
                                                productOptBus.businessID,
                                                productOptBus.businessOptionSKU,
                                                productOptBus.productOptionRegularPrice,
                                                productOptBus.productOptionProductPrice,
                                                productOptBus.productOptionQuantity,
                                                productOptBus.productQuantityUnlimited,
                                                productOptBus.soldQuantity,
                                                productOptBus.busWareHouse,
                                                productOptBus.businessDispatchTime,
                                                productOptBus.busProductStatus,
                                                productOptBus.businessOptionDefault
					FROM
						" . DB_PREFIX . "product_options AS productOpt
					INNER JOIN
						" . DB_PREFIX . "product_option_details AS productOptDet
						ON productOpt.productOptionID=productOptDet.productOptionID
						AND productOptDet.languageID = '" . $currentLanguageID . "'
                                        $sqlProdBusOptionJoin JOIN
						" . DB_PREFIX . "products_req_options_business AS productOptBus ON
                                                (productOptBus.productOptionID=productOpt.productOptionID
						 AND productOptBus.businessID = '" . $businessID . "'
                                                 AND productOptBus.busProductStatus  != 'Delete')
					WHERE
						productOpt.productID='" . (int) $productID . "'
                                                AND productOpt.productOptionStatus  = 'Active'";
        $sql .= "  
					ORDER BY
						productOptionDefault DESC,
						productOpt.productOptionID ";
        $result = $this->ObjDatabase->readValuesSlave($sql);
        return $result;
    }
    
    public function addBusinessReqOptions($productOptionID,$busOptGroup,$productID=0,$productOptionBusinessID=0,$inventoryTrackLevel=""){
        $assignBusinessID   =       $busOptGroup['assignBusinessID'];
        $hiddenBusinessID   =       isset($busOptGroup['hiddenBusinessID']) ? $busOptGroup['hiddenBusinessID'] : 0;
        $busOptionDefault   =       "No"; 
        $busProductStatus   =       "Active";
        $groupPriceArr      =       isset($busOptGroup['group_price']) && !empty($busOptGroup['group_price']) ? $busOptGroup['group_price'] : array();
        $busOptRegPrice     =       isset($busOptGroup['businessOptionReqPrice']) ? $busOptGroup['businessOptionReqPrice'] : 0;
        $busOptSalePrice    =       isset($busOptGroup['businessOptionSalePrice']) ? $busOptGroup['businessOptionSalePrice'] : 0;
        
        if($inventoryTrackLevel=="No"){
            $busQuantity           = "";
            $busQuanUnlimited      = 1;
        }else{
            $busQuantity           = isset($busOptGroup['businessQuantity']) ? $busOptGroup['businessQuantity'] : "";
            $busQuanUnlimited      = 0;
        }
                
        if($busOptSalePrice<=0){
            $busOptSalePrice =      $busOptRegPrice;
        }
        
        if($productOptionBusinessID>0){
            $sqlUpdate          =       "UPDATE ".DB_PREFIX."products_req_options_business SET
                                                                  productOptionID = '".$productOptionID."',
                                                                  businessID      = '".$assignBusinessID."',
                                                                  businessOptionSKU = '".$busOptGroup['businessOptionSKU']."',
                                                                  productOptionRegularPrice = '".$busOptRegPrice."',
                                                                  productOptionProductPrice = '".$busOptSalePrice."',
                                                                  productOptionQuantity = '".$busQuantity."',
                                                                  productQuantityUnlimited = '".$busQuanUnlimited."',
                                                                  busWareHouse = '".$busOptGroup['businessWareHouse']."',
                                                                  businessDispatchTime = '".$busOptGroup['businessDispatchTime']."',
                                                                  businessOptionDefault = '".$busOptionDefault."',
                                                                  busProductStatus = '".$busProductStatus."'
                                                             WHERE productReqOptionBusinessID = '".$productOptionBusinessID."'";
            $resUpdate          =       $this->ObjDatabase->setQuery($sqlUpdate);
        }else{
            $sqlInsert          =       "INSERT INTO ".DB_PREFIX."products_req_options_business
                                                                  (productOptionID,
                                                                   businessID,
                                                                   businessOptionSKU,
                                                                   productOptionRegularPrice,
                                                                   productOptionProductPrice,
                                                                   productOptionQuantity,
                                                                   productQuantityUnlimited,
                                                                   busWareHouse,
                                                                   businessDispatchTime,
                                                                   businessOptionDefault,
                                                                   busProductStatus) VALUES
                                                                   ('".$productOptionID."',
                                                                    '".$assignBusinessID."',
                                                                    '".$busOptGroup['businessOptionSKU']."',
                                                                    '".$busOptRegPrice."',
                                                                    '".$busOptSalePrice."',
                                                                    '".$busQuantity."',
                                                                    '".$busQuanUnlimited."',
                                                                    '".$busOptGroup['businessWareHouse']."',
                                                                    '".$busOptGroup['businessDispatchTime']."',
                                                                    '".$busOptionDefault."',
                                                                    '".$busProductStatus."')";
            $resUpdate          =       $this->ObjDatabase->setQuery($sqlInsert);
        }
        
        if($assignBusinessID!=$hiddenBusinessID && $hiddenBusinessID>0){
            $selBusinessID  =       $hiddenBusinessID; 
        }else{
            $selBusinessID  =       $assignBusinessID; 
        }
        $sqlDelete          =       "DELETE FROM ".DB_PREFIX."variant_request_group_price 
                                     WHERE productOptionID = '".$productOptionID."'
                                     AND businessID = '".$selBusinessID."'";
        $resDelete          =       $this->ObjDatabase->setQuery($sqlDelete);
        
        if(count($groupPriceArr)>0){
            foreach($groupPriceArr as $groupPriceVal){
                $groupUserID            =       isset($groupPriceVal['userGroupID']) ? $groupPriceVal['userGroupID'] : "";
                $groupPrice             =       isset($groupPriceVal['specialPrice']) ? $groupPriceVal['specialPrice'] : 0;
                
                if($groupUserID!="" && $groupPrice>0){
                    $sqlCheck               =       "SELECT COUNT(*) as groupCnt,optionToGroupID FROM ".DB_PREFIX."variant_request_group_price
                                                     WHERE productOptionID = '".$productOptionID."'
                                                     AND businessID = '".$assignBusinessID."'
                                                     AND userGroupID = '".$groupUserID."'";
                    $resCheck               =       $this->ObjDatabase->readValue($sqlCheck);
                    
                    if($resCheck['groupCnt']<=0){
                        $sqlInsertGroupPrice    =       "INSERT INTO ".DB_PREFIX."variant_request_group_price
                                                                                  (productOptionID,
                                                                                   businessID,
                                                                                   userGroupID,
                                                                                   specialPrice) VALUES
                                                                                   ('".$productOptionID."',
                                                                                    '".$assignBusinessID."',
                                                                                    '".$groupUserID."',
                                                                                    '".$groupPrice."')";
                        $resInsertGroupPrice    =       $this->ObjDatabase->setQuery($sqlInsertGroupPrice);
                    }else{
                        $sqlUpdateGroupPrice    =       "UPDATE ".DB_PREFIX."variant_request_group_price SET
                                                                                    specialPrice = '".$groupPrice."'
                                                                            WHERE optionToGroupID = '".$resCheck['optionToGroupID']."'";
                        $resUpdateGroupPrice    =       $this->ObjDatabase->setQuery($sqlUpdateGroupPrice);
                    }
                }
            }
        }
        
    }
    
    public function deleteBusinessReqOptions($prodOptionBusID){
        $sqlDelete                  =               "DELETE FROM ".DB_PREFIX."products_req_options_business
                                                                WHERE productReqOptionBusinessID = '".$prodOptionBusID."'";
        $this->ObjDatabase->setQuery($sqlDelete);
    }
    
    public function deleteBusinessOptions($prodOptionBusID){
        $sqlDelete                  =               "DELETE FROM ".DB_PREFIX."products_options_business
                                                                WHERE productOptionBusinessID = '".$prodOptionBusID."'";
        $this->ObjDatabase->setQuery($sqlDelete);
    }
    
    public function updateBusinessReqStatus($prodOptionBusID){
        $sqlDelete                  =               "UPDATE ".DB_PREFIX."products_req_options_business
                                                                SET busProductStatus = 'Delete'
                                                                WHERE productReqOptionBusinessID = '".$prodOptionBusID."'";
        $this->ObjDatabase->setQuery($sqlDelete);
    }
                                                            
        public function getBuyboxBusinessProductIDs($productID,$businessID) {
        
            $sqlre="SELECT  pdtOptBus.productOptionProductPrice  as price FROM " . DB_PREFIX . "products_options_business AS pdtOptBus
                    LEFT JOIN  " . DB_PREFIX . "product_options AS pdtOpt 
              ON  pdtOptBus.productOptionID= pdtOpt.productOptionID AND pdtOptBus.businessID = '".$businessID."' "
                    . "WHERE pdtOpt.productID = '" . (int)$productID . "'";   
            //echo $sqlre;
            $price= $this->ObjDatabase->readValue($sqlre, MYSQLI_ASSOC);
            return $price;
    }
    
    public function getBuyBoxRequestProducts($languageIDs,$businessID,$limitFrom='',$limitTo=0,$params=array()){
        extract($params);
        $inclCalcRows           = (isset($limitTo) && $limitTo >=0) ? "SQL_CALC_FOUND_ROWS" : "";
        $sqlSelect              =           "SELECT $inclCalcRows
                                                    product.productID,
                                                    product.productImage,
                                                    productDet.productTitle,
                                                    businessDet.businessID,
                                                    businessDet.businessName,
                                                    productOpt.optionSKU,
                                                    productOptDet.productOptionName,
                                                    productReqBus.productReqOptionBusinessID,
                                                    productReqBus.businessOptionSKU,
                                                    productReqBus.productOptionRegularPrice,
                                                    productReqBus.productOptionProductPrice,
                                                    productReqBus.productOptionQuantity,
                                                    productReqBus.productQuantityUnlimited
                                                    FROM ".DB_PREFIX."products_req_options_business productReqBus
                                                    INNER JOIN ".DB_PREFIX."product_options productOpt ON
                                                        (productOpt.productOptionID = productReqBus.productOptionID)
                                                    INNER JOIN ".DB_PREFIX."product_option_details productOptDet ON
                                                        (productOptDet.productOptionID = productOpt.productOptionID AND
                                                         productOptDet.languageID = '".$languageIDs['Current']."')
                                                    INNER JOIN ".DB_PREFIX."products product ON
                                                        (product.productID = productOpt.productID)
                                                    INNER JOIN ".DB_PREFIX."product_details productDet ON
                                                        (productDet.productID = product.productID AND
                                                         productDet.languageID = '".$languageIDs['Current']."')
                                                    INNER JOIN ".DB_PREFIX."business_details businessDet ON
                                                        (businessDet.businessID = productReqBus.businessID AND
                                                         businessDet.languageID = '".$languageIDs['Current']."')
                                                    WHERE 1
                                                    AND product.productStatus IN ('Active','Inactive')
                                                    AND busProductStatus!='Delete'";
        if($businessID>0){
            $sqlSelect         .=           " AND productReqBus.businessID = '".$businessID."'";
        }
        if(isset($productName) && $productName!=""){
            $sqlSelect         .=           " AND (productDet.productTitle LIKE '%" . $this->escape($productName) . "%'
                                                   OR productOpt.optionSKU LIKE '%" . $this->escape($productName) . "%')";
        }
        $sqlSelect             .=           " GROUP BY productReqBus.productReqOptionBusinessID
                                              ORDER BY productReqBus.productReqOptionBusinessID DESC";
        if($limitTo>0){
            $sqlSelect         .=           " LIMIT  " . $limitFrom . "," . $limitTo . " ";
        }
        $result                 =               $this->ObjDatabase->readValuesSlave($sqlSelect);
        
        $resProducts            =               array();
        if(count($result)>0){
            $optionIncr         =               0;
            foreach($result as $res){
                $resProducts[$res['productID']]['productID']                                          =    $res['productID'];
                $resProducts[$res['productID']]['productImage']                                       =    $res['productImage'];
                $resProducts[$res['productID']]['productTitle']                                       =    $res['productTitle'];
                $resProducts[$res['productID']]['businessID']                                         =    $res['businessID'];
                $resProducts[$res['productID']]['businessName']                                       =    $res['businessName'];
                $resProducts[$res['productID']]['options'][$optionIncr]['optionSKU']                  =    $res['optionSKU'];
                $resProducts[$res['productID']]['options'][$optionIncr]['productOptionName']          =    $res['productOptionName'];
                $resProducts[$res['productID']]['options'][$optionIncr]['productReqOptionBusinessID'] =    $res['productReqOptionBusinessID'];
                $resProducts[$res['productID']]['options'][$optionIncr]['businessOptionSKU']          =    $res['businessOptionSKU'];
                $resProducts[$res['productID']]['options'][$optionIncr]['productOptionRegularPrice']  =    $res['productOptionRegularPrice'];
                $resProducts[$res['productID']]['options'][$optionIncr]['productOptionProductPrice']  =    $res['productOptionProductPrice'];
                $resProducts[$res['productID']]['options'][$optionIncr]['productOptionQuantity']      =    $res['productOptionQuantity'];
                $resProducts[$res['productID']]['options'][$optionIncr]['productQuantityUnlimited']   =    $res['productQuantityUnlimited'];
                $optionIncr++;
            }
        }
        return $resProducts;
        
    }
    
    public function getBuyboxProducts($languageIDs,$searchValue,$businessID){
        $sqlSelect             =             "SELECT product.productID,
                                                     product.productImage,
                                                     productDet.productTitle,
                                                     (SELECT GROUP_CONCAT(productCatDet.productCategoryName)
                                                        FROM " . DB_PREFIX . "product_to_category AS productToCat
                                                        INNER JOIN " . DB_PREFIX . "product_categories AS productCat ON	
                                                                        (productCat.productCategoryID=	productToCat.productCategoryID)
                                                        INNER JOIN " . DB_PREFIX . "product_category_details AS productCatDet ON	
                                                                        (productCat.productCategoryID=productCatDet.productCategoryID AND
                                                                        productCatDet.languageID = '" . $languageIDs['Current'] . "')
                                                        WHERE productToCat.productID = product.productID AND
                                                        productCat.productCategoryStatus='Active'
                                                        ORDER BY productCatDet.productCategoryName ASC) as productCategories
                                                     FROM ".DB_PREFIX."products product
                                                     INNER JOIN ".DB_PREFIX."product_details productDet ON
                                                        (productDet.productID = product.productID AND
                                                         productDet.languageID = '".$languageIDs['Current']."')
                                                     WHERE product.enableBuybox = 'Yes'
                                                     AND product.productStatus = 'Active'
                                                     AND (SELECT COUNT(pdtOptBus.productOptionBusinessID) 
                                                                    FROM ".DB_PREFIX."products_options_business pdtOptBus
                                                                    INNER JOIN ".DB_PREFIX."product_options pdtOptions ON
                                                                        (pdtOptions.productOptionID = pdtOptBus.productOptionID)
                                                                    WHERE pdtOptBus.businessID = '".$businessID."'
                                                                    AND pdtOptions.productID = product.productID)<=0";
        if(isset($searchValue) && $searchValue!=""){
            $sqlSelect         .=           " AND productDet.productTitle LIKE '%" . $this->escape($searchValue) . "%'";
        }
        $result                 =               $this->ObjDatabase->readValuesSlave($sqlSelect);
        return $result;
    }
    
    public function deleteProductBusRequest($productID){
        $sqlSelect              =            "SELECT GROUP_CONCAT(productOptionID) as productOptionIDs 
                                                                FROM ".DB_PREFIX."product_options 
                                                                WHERE productID = '".$productID."'";
        $productOptionIDs       =            $this->ObjDatabase->getField($sqlSelect);
        
        $sqlUpdate              =            "UPDATE ".DB_PREFIX."products_req_options_business
                                                                SET busProductStatus = 'Delete'
                                                                WHERE productOptionID IN ($productOptionIDs)";
        $result                 =               $this->ObjDatabase->setQuery($sqlUpdate);
    }
    
    public function getProductSetProductDeal($productID){
            $sqlSelect          =       "SELECT setAsProductDeal FROM ".DB_PREFIX."products WHERE productID = '".$productID."'";
            $result             =        $this->ObjDatabase->getField($sqlSelect);
            return $result;
    }
    
    public function getEnableBuybox($productID){
            $sqlSelect          =       "SELECT enableBuybox FROM ".DB_PREFIX."products WHERE productID = '".$productID."'";
            $result             =        $this->ObjDatabase->getField($sqlSelect);
            return $result;
    }
    
    public function getFreeProductCount($productID){
        $sqlSelect          =       "SELECT freeProductsCount FROM " . DB_PREFIX . "products WHERE productID = '".$productID."'";
        $result             =        $this->ObjDatabase->getField($sqlSelect);
        if($result<=0){
            $result         =        0;
        }
        return $result;
    }
    
    public function getProductIsProductDeal($productID){
            $sqlSelect          =       "SELECT isProductDeal FROM ".DB_PREFIX."products WHERE productID = '".$productID."'";
            $result             =        $this->ObjDatabase->getField($sqlSelect);
            return $result;
    }
	//List Products
	public function listProducts($params)
	{
		extract($params);
		
		$currentLanguageID	= $languageIDs['Current'];
		$limitFrom			= (isset($limitFrom) && $limitFrom >0) ? $limitFrom : 0;		
		$currDateTime		= date('Y-m-d');
		$alloptions			= isset($alloptions) ? $alloptions : '';
                $combination			= isset($combination) ? $combination : '';
                $searchMargin			= isset($searchMargin) ? $searchMargin : '';
		$sql = "
				SELECT
					SQL_CALC_FOUND_ROWS
					product.productID,
					productDet.productTitle,
					product.productImage";
		if($alloptions=="Yes")
		{
			$sql.=",
					product.multiOptionsAvailable";
		}	
		if($combination=="Yes")
		{
			$sql.=",
					(
						SELECT
							COUNT(proCom.combinationID)
						FROM
							" . DB_PREFIX . "product_combination AS proCom
						WHERE
							proCom.status!='D'
							AND proCom.productID = product.productID
					)AS combinationCount";
		}
		$sql.="			
				FROM 
					" . DB_PREFIX . "products AS product 
				LEFT JOIN 
					" . DB_PREFIX . "product_details AS productDet 
					ON product.productID = productDet.productID 
					AND productDet.languageID = '" . $currentLanguageID . "'
				WHERE
					product.productStatus = 'Active'  AND product.isProductDeal<>'Yes'";
               //$sql.= "         AND  product.productID NOT IN(SELECT distinct(productID) from ".DB_PREFIX."product_custom_option_link where productID=product.productID ) ";
               $sql.= " 	AND 
					(
						product.productStartTime <= '" . $currDateTime . "' 
						AND
						(
							product.productEndTime = '0000-00-00'
							OR
							product.productEndTime >=	'" . $currDateTime . "'
						)
					)
					AND	product.businessID IN
					(
						SELECT
							businessID
						FROM
							".DB_PREFIX."business
						WHERE
							businessStatus = 'Active'";
			if(isset($businessID) && $businessID!='')
			{
				$sql.="
							AND businessID = '".$this->escape($businessID)."'";
			}	
			$sql.="			
					)";
		if(isset($categoryID) && $categoryID)
		{
			$sql.="
					AND product.productID IN
					(
						SELECT
							productID
						FROM
							" . DB_PREFIX . "product_to_category
						WHERE
							productCategoryID = '".$this->escape($categoryID)."'	
					)";
		}
		if ((isset($searchProductKeyword) && $searchProductKeyword != '') || (isset($searchMargin) && $searchMargin != ''))
		{
			$searchProductKeyword = $this->escape($searchProductKeyword);
			$sql .= " 	
					AND
					(
						product.productID IN
						(
							SELECT
								productOpt.productID
							FROM
								" . DB_PREFIX . "product_options productOpt
                                                        INNER JOIN
                                                            ".DB_PREFIX."products_options_business AS prodOptBus
                                                                    ON	(
                                                                            prodOptBus.productOptionID = productOpt.productOptionID
                                                                            AND
                                                                            prodOptBus.businessOptionDefault='Yes'
                                                                    )";
                                                                
                                                         if($searchProductKeyword != '')      
							$sql .= " LEFT JOIN
								".DB_PREFIX."product_combination AS proCom 
								ON proCom.productID=productOpt.productID
								AND proCom.status='A'";
                                                                
							$sql .= " WHERE
								productOpt.productOptionStatus = 'Active'";
                                                                
                                                                
                                                          if ($searchMargin != '' && $searchMarginType=='val')
                                                           $sql .= " AND productOpt.productID = product.productID
                                                            AND  ((product.productCommissionRate * productOptBus.productOptionProductPrice)/100) >=".(float)$this->escape($searchMargin)."";
                                                            
                                                            
                                                         if($searchProductKeyword != '')        
							$sql .= "	AND
								(
									productOpt.optionSKU LIKE '%" . $searchProductKeyword . "%'
									OR proCom.combinationSKU LIKE '%" . $searchProductKeyword . "%'
								)";	
						$sql .= ")";
                                                
						if($searchProductKeyword != '')
                                                $sql .= " OR
							productDet.productTitle LIKE '%" . $searchProductKeyword . "%'";
					$sql .= ")";
		}
                if ((isset($searchMargin) && $searchMargin != '') && (isset($searchMarginType) && $searchMarginType=='per'))
		{
                                 
                $sql	.= " AND product.productCommissionRate >= ".(float)$this->escape($searchMargin)."";
                }
		if(isset($brandID) && $brandID>0){
			$sql 	.= " AND product.brandID ='".$brandID."'";
		}
		$sql.="
				ORDER BY
					product.productID DESC";
		if (isset($limitTo) && $limitTo)
		{
			$sql .= " 
				LIMIT  
					" . $limitFrom . "," . $limitTo . "";
		}//echo $sql;
		return $this->ObjDatabase->readValues($sql);	
	}
	public function getProductIdFromVariantCodes($variantCodes) {
		$sql = "SELECT optionSKU FROM " . DB_PREFIX . "product_options WHERE optionSKU IN ('" . implode("','", $variantCodes) . "') 
				AND productOptionDefault = 'Yes' ";
        return $this->ObjDatabase->getFields($sql);
	}
	//Lease Price Import
	public function InsertProductLeasePrice($inert_details=array(),$trp='')
	{
		if(!empty($inert_details))
		{	
			foreach($inert_details as $key => $data) {
                                if($trp=='Y') {
                                    $sql = "
					INSERT INTO " . DB_PREFIX . "product_lease_price
					( 
						variantCode,
						mileage,						
						Trp12,
						Trp24,
						Trp36
					) ";
                                        $sql .= "	VALUES 
					(
						'" .  $this->escape($data['modelCode']). "',
						'" .  $this->escape($data['mileage']). "',						
						'" .  $this->escape(str_replace(",", "",$data['Trp12'])). "',
						'" .  $this->escape(str_replace(",", "",$data['Trp24'])). "',
						'" .  $this->escape(str_replace(",", "",$data['Trp36'])). "'
					) ON DUPLICATE KEY UPDATE						
						Trp12='".$this->escape(str_replace(",", "",$data['Trp12']))."',
						Trp24='".$this->escape(str_replace(",", "",$data['Trp24']))."',
						Trp36='".$this->escape(str_replace(",", "",$data['Trp36']))."'
					";
                                } else {
                                    $sql = "
					INSERT INTO " . DB_PREFIX . "product_lease_price
					( 
						variantCode,
						mileage,
						withoutTrp12,
						withoutTrp24,
						withoutTrp36
					) ";
                                    $sql .= "	VALUES 
					(
						'" .  $this->escape($data['modelCode']). "',
						'" .  $this->escape($data['mileage']). "',
						'" .  $this->escape(str_replace(",", "",$data['withoutTrp12'])). "',
						'" .  $this->escape(str_replace(",", "",$data['withoutTrp24'])). "',
						'" .  $this->escape(str_replace(",", "",$data['withoutTrp36'])). "'
					) ON DUPLICATE KEY UPDATE
						withoutTrp12='".$this->escape(str_replace(",", "",$data['withoutTrp12']))."',
						withoutTrp24='".$this->escape(str_replace(",", "",$data['withoutTrp24']))."',
						withoutTrp36='".$this->escape(str_replace(",", "",$data['withoutTrp36']))."'
					";
                                }				
				$this->ObjDatabase->setQuery($sql);//echo $sql.'<br>';//exit;
			}
			
			$sqlUpd = "UPDATE `" . DB_PREFIX . "import_run_details` SET latestUpdatedDate=NOW() WHERE type='Lease Price Import'";
			$this->ObjDatabase->setQuery($sqlUpd);
		}
	}
	//Lease Price Import
	public function InsertProductFinanceRate($insert_details=array())
	{
		if(!empty($insert_details))
		{	
			foreach($insert_details as $key => $data) {
				$sql = "
					INSERT INTO " . DB_PREFIX . "finance_rate
					( 
						variantCode,
						financeRate,
						shortDescription,
						detailedDescription	
					)
					VALUES 
					(
						'" .  $this->escape($data['variantCode']). "',
						'" .  $this->escape(str_replace("%", "",$data['financeRate'])). "',
						'" .  $this->escape($data['shortDescription']). "',
						'" .  $this->escape($data['detailedDescription']). "'
					) ON DUPLICATE KEY UPDATE
						financeRate='".$this->escape(str_replace("%", "",$data['financeRate']))."',
						shortDescription='".$this->escape($data['shortDescription'])."',
						detailedDescription='".$this->escape($data['detailedDescription'])."'
					";
				$this->ObjDatabase->setQuery($sql);//echo $sql.'<br>';exit;
			}
			
			$sqlUpd = "UPDATE `" . DB_PREFIX . "import_run_details` SET latestUpdatedDate=NOW() WHERE type='Finance Rate Import'";
			$this->ObjDatabase->setQuery($sqlUpd);
		}
	}
	public function InsertProductServiceDetails($insert_details=array())
	{
		if(!empty($insert_details))
		{	
			foreach($insert_details as $key => $data) {
				$sql = "
					INSERT INTO " . DB_PREFIX . "service_package
					( 
						variantCode,
						longDescription	
					)
					VALUES 
					(
						'" .  $this->escape($data['variantCode']). "',
						'" .  $this->escape($data['longDescription']). "'
					) ON DUPLICATE KEY UPDATE
						longDescription='".$this->escape($data['longDescription'])."'
					";
				$this->ObjDatabase->setQuery($sql);//echo $sql.'<br>';exit;
			}
			
			$sqlUpd = "UPDATE `" . DB_PREFIX . "import_run_details` SET latestUpdatedDate=NOW() WHERE type='Service Package Import'";
			$this->ObjDatabase->setQuery($sqlUpd);
		}
	}	
	public function listLeasePrices($params=array()) {
		extract($params);
        $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM `" . DB_PREFIX . "product_lease_price` WHERE 1 ";
		
		if (isset($variantCode) && $variantCode != '') {
            $sql .= "
					AND
					variantCode like '%" . $this->escape($variantCode) . "%'";
        }
		if (isset($year) && $year != '') {
            $sql .= "
					AND
					variantCode like '%" . '-'.$this->escape($year) . "%'";
        }
		
		if (isset($limitTo)) {
            $sql .= " 
				LIMIT  
					" . $limitFrom . ",
					" . $limitTo . "
				";
        }
        $result   = $this->ObjDatabase->readValuesSlave($sql);//echo $sql;
        return $result;
    }
	public function listfinanceRates($params=array()) {
		extract($params);
        $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM `" . DB_PREFIX . "finance_rate` WHERE 1 ";
		
		if (isset($variantCode) && $variantCode != '') {
            $sql .= "
					AND
					variantCode like '%" . $this->escape($variantCode) . "%'";
        }
		if (isset($year) && $year != '') {
            $sql .= "
					AND
					variantCode like '%" . '-'.$this->escape($year) . "%'";
        }
		if (isset($limitTo)) {
            $sql .= " 
				LIMIT  
					" . $limitFrom . ",
					" . $limitTo . "
				";
        }
        $result   = $this->ObjDatabase->readValuesSlave($sql);
        return $result;
    }
	public function listServicePackages($params=array()) {
		extract($params);
        $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM `" . DB_PREFIX . "service_package` WHERE 1 ";
		
		if (isset($variantCode) && $variantCode != '') {
            $sql .= "
					AND
					variantCode like '%" . $this->escape($variantCode) . "%'";
        }
		if (isset($limitTo)) {
            $sql .= " 
				LIMIT  
					" . $limitFrom . ",
					" . $limitTo . "
				";
        }
        $result   = $this->ObjDatabase->readValuesSlave($sql);
        return $result;
    }
	public function getServicePackage($variantCode) {
		if (isset($variantCode) && $variantCode != '') {
			$sql = "SELECT * FROM `" . DB_PREFIX . "service_package` WHERE 1 ";
            $sql .= "
					AND
					variantCode LIKE '" . $this->escape($variantCode) . "'";
		$result   = $this->ObjDatabase->readValueSlave($sql);
        return $result;			
        }
    }
		//Lease Price Import
	public function InsertProductOptionProfiles($insert=array(),$profileCodes=array())
	{
		$sqlDel = "DELETE FROM `" . DB_PREFIX . "product_option_profiles` 
				   WHERE variantCode='".$insert[0]['variantCode']."' AND year='".$insert[0]['year']."' ";
		$this->ObjDatabase->setQuery($sqlDel);
		
		$sql = "
				INSERT INTO " . DB_PREFIX . "product_option_profiles
				( 
					variantCode,
					year,
					profileCode,
					value,
					type	
				) VALUES ";
		foreach($insert as $key => $data) {
			$sql .= "
				(
					'" .  $this->escape($data['variantCode']). "','" .  $this->escape($data['year']). "',
					'" .  $this->escape($data['profileCode']). "','" .  $this->escape($data['value']). "',
					'" .  $this->escape($data['type']). "'
				) ,	";
		}
		$sql = substr(trim($sql), 0, -1);
		$this->ObjDatabase->setQuery($sql);
		
		$saParams = implode(",", $profileCodes);
		$sqlUpd = "	UPDATE `" . DB_PREFIX . "cosy_image_params` 
					SET saParams='".$saParams."' 
					WHERE variantCode='".$insert[0]['variantCode']."'
					AND year='".$insert[0]['year']."'";
		$this->ObjDatabase->setQuery($sqlUpd);
		
	}
	public function dropTable() {
            $sql = "drop table ".DB_PREFIX."autoline_data";
            return $this->ObjDatabase->setQuery($sql);
        }	
        public function updateProductStatus($productStatus='',$productID='') {
            if($productID>0) {
                $sql = "update ".DB_PREFIX."products set productStatus='".$productStatus."' where productID='".$productID."'";
                return $this->ObjDatabase->setQuery($sql);
            }
        }
        
        public function getProductImages($combinationHash,$imageType,$isAjax='no',$angle='',$imagesize='large') {
            if($imageType=='stripe' OR $imageType=='bonnet')
			{
				$imageType 	= 'extr';
				$angle 		= '60';
				$isAjax 	= 'yes';
			}
			if($isAjax == 'no'){
                $sql = " SELECT vehicleImage FROM ".DB_PREFIX."vehicle_images WHERE combinationHash='".$combinationHash."' AND imageType = '".$imageType."' ";
				if($angle!=''){
					$sql .= " AND angle = '".$angle."' ";
				}
                $sql .=     " GROUP BY vehicleImage ORDER BY angle ASC ";
                return $this->ObjDatabase->readValues($sql);
            }else{
                $global_http_url = $this->getSettingValue('site_settings', 'global_http_url');
                $uploadImagesTo = $this->getSettingValue('site_settings', 'upload_images_to');
                if ($uploadImagesTo == 'amazon') {
                    $enableSSLCheckout = $this->getSettingValue('site_settings', 'enable_ssl_checkout');
                    $cdnBaseUrlImage   = $this->getSettingValue('site_settings', 'cdn_baseurl_image');
                } else if ($uploadImagesTo == 'rackspace') {
                    $enableSSLCheckout = $this->getSettingValue('site_settings', 'enable_ssl_checkout');
                    $cdnBaseUrlImage   = ($enableSSLCheckout == 'Enable') ? $this->getSettingValue('site_settings', 'rackspace_cdn_base_httpsurl_image') : $this->getSettingValue('site_settings', 'rackspace_cdn_base_httpurl_image');
                }
                if (isset($cdnBaseUrlImage) && $cdnBaseUrlImage != "") {
                    $viewpublicpath= rtrim($cdnBaseUrlImage, '/') . '/' . __DIR_PUBLIC; 
                } else {
                    $viewpublicpath= rtrim($global_http_url). '/' . __DIR_PUBLIC; 
                }
                $sql = " SELECT CONCAT('".$viewpublicpath . '/' . __UPLOADS_FOLDER."catalog/vehicles/".$imagesize."/',vehicleImage) AS Imageslist  FROM ".DB_PREFIX."vehicle_images WHERE combinationHash='".$combinationHash."' AND imageType = '".$imageType."' ";
                if($angle!=''){
					$sql .= " AND angle = '".$angle."' ";
				}
                $sql .=     " GROUP BY vehicleImage ORDER BY angle ASC ";
                return $this->ObjDatabase->readValues($sql,MYSQLI_ASSOC);
                
                
            }
            
        }
        
        public function selectProductSpecification($variantCode,$year) {
            
                $sql = " SELECT *  FROM ".DB_PREFIX."product_option_profiles WHERE variantCode='".$variantCode."' AND year = '".$year."' ORDER BY optionProfileID ASC ";
                return $this->ObjDatabase->readValues($sql,MYSQLI_ASSOC);
        }
	 public function financeRateCalculator($productOptionRegularPrice='',$variantCode='') {
		 $mainPrice 				= $productOptionRegularPrice;
		 $downPaymentPercentage 	= $this->getSettingValue('product_cart_settings', 'finance_down_payment');
		 $downPayment				= ($mainPrice *  $downPaymentPercentage)/100;
		 $financeAmount				=  $mainPrice - $downPayment;
		 // if($financeAmount <  50000) {
			  // $differenceValue 		= 50000 - $financeAmount;
			  // $downPayment			= $downPayment - $differenceValue;
			  // $financeAmount		= $financeAmount + $differenceValue;
		 // }
		$processingFeesPercentage 	= $this->getSettingValue('product_cart_settings', 'finance_processing_fees');
		$processingFees				= ($financeAmount *  $processingFeesPercentage)/100;
		if($processingFees >= 2500) {
			$processingFees			= 2500 * 1.05; 
	    } else if($processingFees <= 500) {
			$processingFees			= 500 * 1.05; 
		}
		$totalFinanceAmount			= $financeAmount + $processingFees;
		$financeTerm				= $this->getSettingValue('product_cart_settings', 'finance_term');

		$sql          				= "	SELECT financeRate FROM ".DB_PREFIX."finance_rate 
										WHERE variantCode = '".$variantCode."'";
		$financeRate         		= $this->ObjDatabase->getField($sql);
		$financeRate         		= $financeRate/100;
		if(!empty($financeRate)) 	{
			$installment			= (($totalFinanceAmount*$financeRate*$financeTerm/12)+$totalFinanceAmount+200)/$financeTerm;
		} else
			$installment 			= 0;
		//echo $variantCode.'--'.$financeTerm.'--'.$processingFees.'--'.$financeRate .'--'.$installment;exit;
		return $installment;
	 }
	 public function getfinanceRate($variantCode='') {
		 $finance = '';
		if (isset($variantCode) && $variantCode != '') { 
        $sql = "	SELECT financeRate,detailedDescription FROM ".DB_PREFIX."finance_rate WHERE 1";
		
            $sql .= "
					AND variantCode = '".$variantCode."' ";
        $finance   = $this->ObjDatabase->readValue($sql);
		}
        return $finance;
    }
	public function getLeaseRate($params) {
		extract($params);
		if($tyreChange == 'yes')
			$field = 'TRP'.$duration;
		else if($tyreChange == 'no')
			$field = 'withoutTrp'.$duration;
        $sql = "	SELECT " . $field . " FROM ".DB_PREFIX."product_lease_price WHERE 1";
		
		if (isset($variantCode) && $variantCode != '') {
            $sql .= "
					AND variantCode = '".$variantCode."' ";
        }
		if (isset($mileage) && $mileage != '') {
            $sql .= "
					AND mileage = '".$mileage."' ";
        }
        $rate   = $this->ObjDatabase->getField($sql);//echo $sql;
        return $rate;
    }
    public function saveCombinations($productID,$exteriorcode,$interiorcode,$tempVar,$status,$vsbID='') {
        $check = 0;//$this->checkCombinationsExists($productID,$exteriorcode,$interiorcode,$status,$vsbID,'Check');
        if($check<=0) {
            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option_combination 
				(customOptionID,
				productID,
				extVariantCode, 
				intVariantCode, 
				status,
                                vsbID
				) 
				VALUES 
				('" . $tempVar . "',
				'" . $productID . "', 
				'" . $exteriorcode . "', 
				'" . $interiorcode . "','".$status."','".$vsbID."')");
                            $customCombID          = $this->ObjDatabase->getInsertId();
                            return $customCombID;
        } else {
           return $check;
        }
    }
    public function saveCombinationsMini($productID,$bonnetStripeCode,$roofCapCode,$tempVar,$status,$vsbID='') {
        $check = 0;//$this->checkCombinationsExists($productID,$exteriorcode,$interiorcode,$status,$vsbID,'Check');
        if($check<=0) {
            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option_combination_mini 
				(customOptionID,
				productID,
				bonnetStripeCode, 
				roofCapCode, 
				status,
                                vsbID
				) 
				VALUES 
				('" . $tempVar . "',
				'" . $productID . "', 
				'" . $bonnetStripeCode . "', 
				'" . $roofCapCode . "','".$status."','".$vsbID."')");
                            $customCombID          = $this->ObjDatabase->getInsertId();
                            return $customCombID;
        } else {
           return $check;
        }
    }
    public function deleteCustomCombo($productID) {
        $sql = "Delete from " . DB_PREFIX . "product_custom_option_combination where productID='".$productID."' ";
        $this->ObjDatabase->setQuery($sql);
        return true;
    }
    public function checkCombinationsExists($productID,$exteriorcode,$interiorcode,$status,$vsbID='',$check='',$tempVar='') {
        $sql = "select * from " . DB_PREFIX . "product_custom_option_combination  where productID='".$productID."'";
        $sql .= " and extVariantCode='".$exteriorcode."' and intVariantCode='".$interiorcode."' ";
        if(!empty($check)) {
            $sql .= " and vsbID='".$vsbID."' ";
        }
        
        $res  = $this->ObjDatabase->readValue($sql);
        if(empty($res)) {
            return 0;
        } else {
            $customOptionCombID = $res['customOptionCombID'];
            if($check=='') {
               return $res['customOptionCombID'];
            }
            if($res['status']==$status) {
                $sql  = " Update " . DB_PREFIX . "product_custom_option_combination set status='".$status."' ";
                if($tempVar!='') {
                    $sql .= " ,customOptionID = '" . $tempVar . "' ";
                }                
                $sql .= " where customOptionCombID='".$customOptionCombID."'";               
                $res  = $this->ObjDatabase->setQuery($sql);
                return $customOptionCombID;
            } else {
                
                $sql  = " Update " . DB_PREFIX . "product_custom_option_combination set status='".$status."' ";
                if($tempVar!='') {
                    $sql .= " ,customOptionID = '" . $tempVar . "' ";
                }                
                $sql .= " where customOptionCombID='".$customOptionCombID."'";               
                $res  = $this->ObjDatabase->setQuery($sql);
                return $customOptionCombID;
            }
        }
    }
    public function checkMiniCombinationsExists($productID,$bonnetStripeCode,$roofcapcode,$status,$vsbID='',$check='') {
        $sql = "select * from " . DB_PREFIX . "product_custom_option_combination_mini  where productID='".$productID."'";
        $sql .= " and bonnetStripeCode='".$bonnetStripeCode."' and roofCapCode='".$roofcapcode."' ";
        if(!empty($check)) {
            $sql .= " and vsbID='".$vsbID."' ";
        }        
        $res  = $this->ObjDatabase->readValue($sql);
        if(empty($res)) {
            return 0;
        } else {
            $customOptionCombID = $res['customOptionCombID'];
            if($check=='') {
               return $res['customOptionCombID'];
            }
            if($res['status']==$status) {
                return $customOptionCombID;
            } else {
                
                $sql                = "update " . DB_PREFIX . "product_custom_option_combination_mini set status='".$status."' where customOptionCombID='".$customOptionCombID."'";
               
                $res  = $this->ObjDatabase->setQuery($sql);
                return $customOptionCombID;
            }
        }
    }
    public function updateCombinationStatus($customOptionCombID,$productID='',$mini='') {
        if(!empty($customOptionCombID)) {
            $customOptionCombID = array_unique($customOptionCombID);
            if($mini=='') {
                $sql                = "update " . DB_PREFIX . "product_custom_option_combination set status='D' where customOptionCombID NOT IN ('" . implode("','", $customOptionCombID) . "') and productID = '".$productID."' ";
            } else {
                $sql                = "update " . DB_PREFIX . "product_custom_option_combination_mini set status='D' where customOptionCombID NOT IN ('" . implode("','", $customOptionCombID) . "') and productID = '".$productID."' ";
            } 
            $res  = $this->ObjDatabase->setQuery($sql);
            return 1;
        }
        return 0;
        
    }
    public function updateVariantStatus($customOptionID,$varIDs=array()) {
        if(!empty($varIDs)) {
            $varIDs = array_unique($varIDs);
            $sql                = "update " . DB_PREFIX . "product_custom_option_variant set status='D',isDefault='0' where customOptionVariantID NOT IN ('" . implode("','", $varIDs) . "') and customOptionID = '".$customOptionID."' ";           
            $res  = $this->ObjDatabase->setQuery($sql);
            return 1;
        }
        return 0;
        
    }
    public function updateLastProcessed($productID,$counter){

            $sql	=	"UPDATE	" . DB_PREFIX . "crone_execution_details	set executionTime=NOW(),rowsAffected='".$counter."',
                                            lastAffectedID='".$productID."' where cronType='autoline'";
            $res  = $this->ObjDatabase->setQuery($sql);
            return 1;				
    }
    public function getVSBFromComb($productID,$combID) {
        $sql = "select comb.vsbID from " . DB_PREFIX . "product_custom_option_combination comb 
                where comb.productID='".$productID."' and comb.customOptionID='".$combID."' and comb.status='A' Limit 0,1 ";
        $result = $this->ObjDatabase->readValue($sql);
        return !empty($result['vsbID']) ? $result['vsbID'] : 0;
    }
    public function changeStatusInactive($productIDs) {
        $sql = "update " . DB_PREFIX . "products set productStatus='Inactive' where productID NOT IN (" . implode(",",$productIDs) . ")  and productStatus='Active' ";                
        $this->ObjDatabase->setQuery($sql);
    }
    public function deleteCustomOptions($productID,$currentLanguageID,$customOptionArr=array()) {
       
        $custIDs = '';
        if(!empty($customOptionArr)) {
            $custIDs = " and custoptlink.customOptionID NOT IN ('" . implode("','", $customOptionArr) . "')";            
        }        
       
        $this->ObjDatabase->setQuery("
					DELETE productCustValDet
					FROM
						" . DB_PREFIX . "product_custom_option_variant productCustVal
					LEFT JOIN
						" . DB_PREFIX . "product_custom_option_variant_details productCustValDet
						ON productCustVal.customOptionVariantID = productCustValDet.customOptionVariantID						
					LEFT JOIN
						" . DB_PREFIX . "product_custom_option custopt
						ON custopt.customOptionID = productCustVal.customOptionID
                                        LEFT JOIN
						" . DB_PREFIX . "product_custom_option_link custoptlink
						ON custoptlink.customOptionID = custopt.customOptionID        
					WHERE
						custoptlink.productID = '" . $productID . "' ".$custIDs."
						
						
				");
        
            //Delete Select/MultiSelect data	
            $this->ObjDatabase->setQuery("
								DELETE productCustVal
								FROM
									" . DB_PREFIX . "product_custom_option_variant productCustVal								
                                                                LEFT JOIN
                                                                        " . DB_PREFIX . "product_custom_option custopt
                                                                        ON custopt.customOptionID = productCustVal.customOptionID
                                                                LEFT JOIN
                                                                        " . DB_PREFIX . "product_custom_option_link custoptlink
                                                                        ON custoptlink.customOptionID = custopt.customOptionID     	
                                                                                        WHERE
									custoptlink.productID = '" . $productID . "' ".$custIDs."						
									
							");
            $this->ObjDatabase->setQuery("
								DELETE productCustVal
								FROM
									" . DB_PREFIX . "product_custom_option_details productCustVal	
                                                                LEFT JOIN
                                                                        " . DB_PREFIX . "product_custom_option custopt
                                                                        ON custopt.customOptionID = productCustVal.customOptionID            
                                                                LEFT JOIN
                                                                        " . DB_PREFIX . "product_custom_option_link custoptlink
                                                                        ON custoptlink.customOptionID = custopt.customOptionID     	
                                                                                        WHERE
									custoptlink.productID = '" . $productID . "' ".$custIDs."						
									
							");
            $this->ObjDatabase->setQuery("
								DELETE productCustVal
								FROM
									" . DB_PREFIX . "product_custom_option productCustVal								                                                                
                                                                LEFT JOIN
                                                                        " . DB_PREFIX . "product_custom_option_link custoptlink
                                                                        ON custoptlink.customOptionID = productCustVal.customOptionID     	
                                                                                        WHERE
									custoptlink.productID = '" . $productID . "' ".$custIDs."						
									
							");
            $sqlDel = "Delete custoptlink from `" . DB_PREFIX . "product_custom_option_link` custoptlink where custoptlink.productID='".$productID."' ".$custIDs." ";
            $this->ObjDatabase->setQuery($sqlDel);
            //$sqlDel = "Delete from `" . DB_PREFIX . "product_custom_option_combination` where productID='".$productID."'";
            //$this->ObjDatabase->setQuery($sqlDel);
            /*$sqlUpd = "update `" . DB_PREFIX . "product_custom_option_combination` set status='D' where productID='".$productID."'";
            $this->ObjDatabase->setQuery($sqlUpd);*/
            return true;
    }
	public function autolineUpdate() {
        $sql    = "SELECT
						cronDetails.executionTime
				FROM
						" . DB_PREFIX . "crone_execution_details as cronDetails
				WHERE
						cronDetails.cronType='autoline' ";
        $result = $this->ObjDatabase->readValueSlave($sql, MYSQLI_ASSOC);
        return $result['executionTime'];
    }
    public function stripeBonnetUpdate($variant='',$stripeCodes='',$bonnetCodes='') {

		$sqlUpd = "	UPDATE `" . DB_PREFIX . "cosy_image_params` 
					SET stripe='".$stripeCodes."' , bonnet='".$bonnetCodes."' 
					WHERE variantCode='".$variant."' ";
		//echo $sqlUpd; exit;
		$this->ObjDatabase->setQuery($sqlUpd);
	}
	public function UpdateImportRunDetails($type,$body = "")
	{
		if(!empty($type))
		{	
			$sqlUpd = "UPDATE `" . DB_PREFIX . "import_run_details` SET latestUpdatedDate=NOW() ";
			if($body!="") {
				$sqlUpd .= " , emailHtml = '" . $this->escape($body, FALSE) . "'";
			}
			$sqlUpd .= "WHERE type='" . $this->escape($type) . "'";
			$this->ObjDatabase->setQuery($sqlUpd);
		}
	}	
	public function getImportRunDetails($type) {
		if(!empty($type))
		{
			$sql = "SELECT * FROM " . DB_PREFIX . "import_run_details WHERE type='" . $this->escape($type) . "'";
			$result  = $this->ObjDatabase->readValue($sql);
			return $result;
		}
	}
	public function getDashboardMissing($params) {
		extract($params);
		$sql = "SELECT 
					   (SELECT
							COUNT(optionSKU)
							FROM " . DB_PREFIX . "product_options AS productOpt 
							INNER JOIN " . DB_PREFIX . "products AS product 
								ON productOpt.productID = product.productID
							WHERE (productOpt.productOptionStatus = 'Active') AND (product.brandID='2')
								AND productStatus IN ('Active', 'Inactive', 'Review')	
								AND optionSKU NOT IN (
								SELECT CONCAT(variantCode, '-', year)
								FROM " . DB_PREFIX . "product_option_profiles AS profiles 
								WHERE profileCode!=''
							)
						) AS profilesCount,
						(SELECT
							COUNT(optionSKU)
							FROM " . DB_PREFIX . "product_options AS productOpt 
							INNER JOIN " . DB_PREFIX . "products AS product 
								ON productOpt.productID = product.productID
							WHERE (productOpt.productOptionStatus = 'Active') AND (product.brandID='2') 
								AND productStatus IN ('Active', 'Inactive', 'Review')	
								AND optionSKU NOT IN (
								SELECT CONCAT(variantCode, '-', year)
								FROM " . DB_PREFIX . "cosy_image_params AS image 
								WHERE status!='New'
							)
						) AS imagesCount
						";
		$result  = $this->ObjDatabase->readvalue($sql,MYSQLI_ASSOC);
		if ($leasePrivilege) {
			$sql = "SELECT 
						(SELECT
							COUNT(optionSKU)
							FROM " . DB_PREFIX . "product_options AS productOpt 
							INNER JOIN " . DB_PREFIX . "products AS product 
								ON productOpt.productID = product.productID
							WHERE (productOpt.productOptionStatus = 'Active') AND (product.brandID='2') 
								AND productStatus IN ('Active', 'Inactive', 'Review')	
								AND optionSKU NOT IN (
								SELECT variantCode
								FROM " . DB_PREFIX . "product_lease_price 
								WHERE mileage!=''
							)
						) AS leaseCount
			";
			$lease  = $this->ObjDatabase->getField($sql);
			$result['leaseCount']  = isset($lease) ? $lease : 0;
		}	
		if ($financePrivilege) {
			$sql = "SELECT 
						(SELECT
							COUNT(optionSKU)
							FROM " . DB_PREFIX . "product_options AS productOpt 
							INNER JOIN " . DB_PREFIX . "products AS product 
								ON productOpt.productID = product.productID
							WHERE (productOpt.productOptionStatus = 'Active') AND (product.brandID='2') 
								AND productStatus IN ('Active', 'Inactive', 'Review')	
								AND optionSKU NOT IN (
								SELECT variantCode
								FROM " . DB_PREFIX . "finance_rate
								WHERE financeRate!=''
							)
						) AS financeCount
			";
			$finance  = $this->ObjDatabase->getField($sql);
			$result['financeCount']  = isset($finance) ? $finance : 0;
		}
		//print_r($result );
		return $result;		
	}
   
}
// End of Class
