<?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 WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: AttributeModel.php, v 1.2 2012/12/24 17:50:11
class CustomOptionModel extends ProductModel {
    //lists input types for attribute
    public function listAtrributeInputTypes($languageXml, $forListing = '') {
        $inputTypeDataArray                                  = array();
        $dataString                                          = '';
        $inputTypeDataArray['text']['GROUP_LABEL']           = $languageXml['lblTextGroup'];
        $inputTypeDataArray['text']['data']['textbox']       = $languageXml['lblTextbox'];
        $inputTypeDataArray['text']['data']['textarea']      = $languageXml['lblTextarea'];
        $inputTypeDataArray['select']['GROUP_LABEL']         = $languageXml['lblSelectGroup'];
        $inputTypeDataArray['select']['data']['select']      = $languageXml['lblSelectBox'];
        $inputTypeDataArray['select']['data']['multiselect'] = $languageXml['lblCheckBox'];
        $inputTypeDataArray['date']['GROUP_LABEL']           = $languageXml['lblDateGroup'];
        $inputTypeDataArray['date']['data']['date']          = $languageXml['lbldate'];
        $inputTypeDataArray['date']['data']['datetime']      = $languageXml['lblDateTime'];
        $inputTypeDataArray['date']['data']['time']          = $languageXml['lblTime'];
        $inputTypeDataArray['file']['GROUP_LABEL']           = $languageXml['lblFileGroup'];
        $inputTypeDataArray['file']['data']['file']          = $languageXml['lblFile'];
        foreach ($inputTypeDataArray as $inputTypes => $inputTypeData) {
            $i = 0;
            foreach ($inputTypeData['data'] as $inputTypeDataKey => $inputTypeDataInd) {
                if ($forListing == 'Yes') {
                    $inputTypeArray[$inputTypeDataKey] = $inputTypeDataInd;
                } else {
                    $inputTypeArray[$inputTypeData['GROUP_LABEL']][$i][0] = $inputTypeDataKey;
                    $inputTypeArray[$inputTypeData['GROUP_LABEL']][$i][1] = $inputTypeDataInd;
                }
                $i++;
            }
        }
        return $inputTypeArray;
    }
    //lists Validation Rules for attribute
    public function listAtrributeValidationRules($languageXml) {
        $validationArray = array();
        $attributeRules  = $this->attributeRules($languageXml);
        $i               = 0;
        foreach ($attributeRules as $validationRule => $validationText) {
            $validationArray[$i][0] = $validationRule;
            $validationArray[$i][1] = $validationText;
            $i++;
        }
        return $validationArray;
    }
    //Attribute Rules
    public function attributeRules($languageXml) {
        $ruleArray['isAlphaNumericWithSpace'] = $languageXml['lblAttrValidateAlphaNumeric'];
        $ruleArray['email']                   = $languageXml['lblAttrValidateEmail'];
        $ruleArray['isFloatWithoutZero']      = $languageXml['lblAttrValidateNumber'];
        $ruleArray['isWholeNumberWithZero']   = $languageXml['lblAttrValidateWholeNumberWithZero'];
        $ruleArray['isFloat']                 = $languageXml['lblAttrValidateDecimalNumber'];
        $ruleArray['isNumber']                = $languageXml['lblAttrValidateInteger'];
        $ruleArray['isPercentage']            = $languageXml['lblAttrValidatePercentage'];
        return $ruleArray;
    }
    //save attribute data
    public function saveGlobalOption($languageIDs, $paramArray) {
        $ObjImage                           = new ImageModel();
        $defultLanguageID                   = $languageIDs['Default'];
        $currentLanguageID                  = $languageIDs['Current'];
        $productID                          = $this->escape($paramArray['productID']);
        //Get params from paramArray
        $customOptionID                     = isset($paramArray['customOptionID']) ? $this->escape($paramArray['customOptionID']) : '';
        $customOptionName                   = $this->escape($paramArray['customOptionName']);
        $helpText                           = $this->escape($paramArray['helpText']);
        $inputType                          = $this->escape($paramArray['inputType']);
        $validateRuleRequired               = isset($paramArray['validateRuleRequired']) ? $this->escape($paramArray['validateRuleRequired']) : '';
        $validateRule                       = (isset($paramArray['validateRule'])) ? $this->escape($paramArray['validateRule']) : '';
        $validationMessage                  = isset($paramArray['validationMessage']) ? $this->escape($paramArray['validationMessage']) : '';
        $allowedExtensions                  = isset($paramArray['allowedExtensions']) ? $this->escape($paramArray['allowedExtensions']) : '';
        $maxFileSize                        = isset($paramArray['maxFileSize']) ? $this->escape($paramArray['maxFileSize']) : '';
        $priceDiff                          = (isset($paramArray['priceDiff'])) ? $this->escape($paramArray['priceDiff']) : '';
        $priceDiffType                      = (isset($paramArray['priceDiffType'])) ? $this->escape($paramArray['priceDiffType']) : '';
        $attrOptionAddCount                 = (isset($paramArray['attrOptionAddCount'])) ? $this->escape($paramArray['attrOptionAddCount']) : '';
        $status                             = $this->escape($paramArray['status']);
        $paramArray['includeInCombination'] = (isset($paramArray['includeInCombination'])) ? $paramArray['includeInCombination'] : '';
        $variantThumbImage                  = "";
        $includeInCombination               = '';
        if ($inputType == 'select') {
            $includeInCombination = (trim($paramArray['includeInCombination']) == 'Yes') ? "Yes" : "No";
        } else
            $includeInCombination = "No";
        $attributeOptionsReqd = 1;
        if ($inputType == 'textbox' || $inputType == 'textarea' || $inputType == 'date' || $inputType == 'time' || $inputType == 'datetime' || $inputType == 'file') {
            $attributeOptionsReqd = 0;
        }
        //Set Constraints
        if ($inputType == 'date' || $inputType == 'time' || $inputType == 'datetime' || $inputType == 'file' || $inputType == 'select' || $inputType == 'multiselect') {
            $validateRule = '';
        }
        //Set Validation 
        if ($validateRuleRequired == 'Yes' && $validateRule != '') {
            $validateRule = "required~*" . $validateRule;
        } elseif ($validateRuleRequired == 'Yes' && $validateRule == '') {
            $validateRule = "required";
        } elseif ($validateRuleRequired == '' && $validateRule == '') {
            $validationMessage = '';
        }
        //Save Attribute 
        if ($customOptionID > 0) //Update
            {
            //Attribute table
            $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option
			SET 	
			inputType='" . $inputType . "',
			validateRule='" . $validateRule . "',
			priceDiff='" . $priceDiff . "',
			priceDiffType='" . $priceDiffType . "',
			include_in_combination='" . $includeInCombination . "',
			status = '" . $status . "' 
			WHERE customOptionID = '" . $customOptionID . "'");
            //Attribute Detail									  
            $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option_details
			SET
			customOptionName='" . $customOptionName . "',
			validationMessage='" . $validationMessage . "',
			helpText = '" . $helpText . "' 
			WHERE customOptionID = '" . $customOptionID . "' AND languageID ='" . $currentLanguageID . "'");
        } else //Insert
            {
            //Attribute table			
            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option 
			(
			inputType,
			isGlobal,
			validateRule,
			include_in_combination,	
			priceDiff,
			priceDiffType,
			status
			) 
			VALUES 
			( 
			'" . $inputType . "',												 
			'1',
			'" . $validateRule . "',
			'" . $includeInCombination . "',
			'" . $priceDiff . "',
			'" . $priceDiffType . "',
			'" . $status . "')");
            $customOptionID      = $this->ObjDatabase->getInsertId();
            //Attribute Detail
            $insertAttrDetailSql = "INSERT INTO " . DB_PREFIX . "product_custom_option_details 
			(customOptionID, 
			languageID, 
			customOptionName, 
			validationMessage,
			helpText
			) 
			VALUES";
            foreach ($languageIDs['AllList'] as $langIds) {
                $insertAttrDetailValueSql[] = "('" . $customOptionID . "', 
			'" . $langIds . "', 
			'" . $customOptionName . "',
			'" . $validationMessage . "', 
			'" . $helpText . "')";
            }
            $insertAttrDetailSql = $insertAttrDetailSql . implode(",", $insertAttrDetailValueSql);
            $this->ObjDatabase->setQuery($insertAttrDetailSql);
        }
        //Save Attribute Options
        if ($attributeOptionsReqd == 1 && !empty($paramArray['attrOptionsGroup'])) {
            foreach ($paramArray['attrOptionsGroup'] as $rowKey => $row) // Traverse through all posted options
                {
                $customOptionVariantID = (int) $row['customOptionVariantID'];
                if ($row['is_delete'] == 1) // Option is deleted
                    {
                    if ($customOptionVariantID > -1) // Option already present in db. Delete it
                        {
                        $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "product_custom_option_variant WHERE customOptionVariantID='" . $customOptionVariantID . "'");
                        $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "product_custom_option_variant_details WHERE customOptionVariantID='" . $customOptionVariantID . "'");
                    }
                } else {
                    $valueTitle        = $this->escape($row['varValue']);
                    $sortOrder         = $this->escape($row['sortOrder']);
                    $priceDiff         = $this->escape($row['priceDiff']);
                    $priceDiffType     = $this->escape($row['priceDiffType']);
                    $weightDiff        = $this->escape($row['weightDiff']);
                    $weightDiffType    = $this->escape($row['weightDiffType']);
                    $vsbID             = (isset($row['vsbID'])) ? $row['vsbID'] : '';
                    $variantCode       = (isset($row['variantCode'])) ? $this->escape($row['variantCode']) : '';
                    $isDefault         = (isset($row['isDefault'])) ? $this->escape($row['isDefault']) : '';
                    $attrFile          = "";
                    $attrFileType      = "";
                    $updateFileSection = 1;
                    if ($inputType == 'select') {
                        if ($includeInCombination == 'Yes') {
                            $priceDiff      = 0;
                            $priceDiffType  = 'N';
                            $weightDiff     = 0;
                            $weightDiffType = 'N';
                        }
                        $variantThumbImageType = $paramArray['OptionVariantThumb_' . $rowKey];
                        if (($paramArray["OptionVariantThumb_" . $rowKey . "_temp"] != '')) {
                            if ($variantThumbImageType)
                                $variantThumbImage = $variantThumbImageType;
                            if ($variantThumbImage) {
                                //$ObjImage->resizeImage(__ROOT_PATH . '/' . $paramArray["OptionVariantThumb_" . $rowKey . "_temp"], "", 20, 20);
                                $ObjImage->copy_file($paramArray["OptionVariantThumb_" . $rowKey . "_temp"], "/" . __UPLOADS_FOLDER . "catalog/custom-option-variant/" . $variantThumbImage);
                            }
                            if ($customOptionVariantID > -1) {
                                $this->deleteVariantImage($customOptionVariantID);
                            }
                            @unlink(__ROOT_PATH . '/' . $paramArray["OptionVariantThumb_" . $rowKey . "_temp"]);
                        } else {
                            if ($variantThumbImageType != '')
                                $variantThumbImage = $variantThumbImageType;
                            else
                                $variantThumbImage = '';
                        }
                    }
                    if ($customOptionVariantID > -1) // Option already present in db. Update it
                        {
                        //Attribute options
                        $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option_variant
			SET 	priceDiff='" . $priceDiff . "',
			priceDiffType='" . $priceDiffType . "',
			variantThumbImage='" . $variantThumbImage . "',
			weightDiff='" . $weightDiff . "',
			weightDiffType = '" . $weightDiffType . "',
			sortOrder = '" . $sortOrder . "',
			isDefault = '" . $isDefault . "' ,variantCode='".$variantCode."',vsbID='".$vsbID."'
			WHERE customOptionVariantID = '" . $customOptionVariantID . "'");
                        //Attribute option Detail
                        $attrOptionDetailSql = "UPDATE " . DB_PREFIX . "product_custom_option_variant_details
			SET 	value='" . $valueTitle . "'";
                        $attrOptionDetailSql .= " WHERE customOptionVariantID = '" . $customOptionVariantID . "' AND languageID ='" . $currentLanguageID . "'";
                        $this->ObjDatabase->setQuery($attrOptionDetailSql);
                    } else // New option. Insert it
                        {
                        //Attribute options
                        $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option_variant 
			(customOptionID,
			variantThumbImage,
			priceDiff, 
			priceDiffType, 
			weightDiff,
			weightDiffType,
			sortOrder,
			isDefault,
                        variantCode,
                        vsbID
			) 
			VALUES 
			('" . $customOptionID . "',
			'" . $variantThumbImage . "', 
			'" . $priceDiff . "', 
			'" . $priceDiffType . "', 
			'" . $weightDiff . "',
			'" . $weightDiffType . "',															   
			'" . $sortOrder . "',
			'" . $isDefault . "','".$variantCode."','".$vsbID."')");
                        $customOptionVariantID          = $this->ObjDatabase->getInsertId();
                        //Attribute option Detail
                        $insertAttrOptionDetailSql      = "INSERT INTO " . DB_PREFIX . "product_custom_option_variant_details 
			(customOptionVariantID, 
			languageID, 
			value
			) 
			VALUES";
                        $insertAttrDetailOptionValueSql = '';
                        foreach ($languageIDs['AllList'] as $langIds) {
                            $insertAttrDetailOptionValueSql[] = "('" . $customOptionVariantID . "', 
			'" . $langIds . "', 
			'" . $valueTitle . "')";
                        }
                        $insertAttrOptionDetailSql = $insertAttrOptionDetailSql . implode(",", $insertAttrDetailOptionValueSql);
                        $this->ObjDatabase->setQuery($insertAttrOptionDetailSql);
                    }
                    if (isset($variantThumbImage) && $variantThumbImage == '') {
                        $this->deleteVariantImage($customOptionVariantID);
                    }
                }
            }
        }
        if ($inputType == 'file') {
            $validateRule = '';
            if ($validateRuleRequired == 'Yes') {
                $validateRule = 'required~*';
            }
            if ($maxFileSize != '') {
                $validateRule .= "checkFileSize->" . $maxFileSize . "~*";
            }
            $validateRule .= "isValidFileExtension";
            if ($allowedExtensions != '')
                $validateRule .= "->" . $allowedExtensions;
        }
        $this->updateOptionRule($customOptionID, $validateRule);
        return $customOptionID;
    }
    //list Custom Options
    public function listCustomOptions($languageIDs, $paramArray = array()) {
        $defultLanguageID          = $languageIDs['Default'];
        $currentLanguageID         = $languageIDs['Current'];
        //Get params from paramArray
        $customOptionID            = $this->escape(isset($paramArray['customOptionID']) ? $paramArray['customOptionID'] : '');
        $customOptionName          = $this->escape(isset($paramArray['customOptionName']) ? $paramArray['customOptionName'] : '');
        $status                    = $this->escape(isset($paramArray['status']) ? $paramArray['status'] : '');
        $isGlobal                  = $this->escape(isset($paramArray['isGlobal']) ? $paramArray['isGlobal'] : '');
        $excludeImportedAttributes = $this->escape(isset($paramArray['excludeImportedAttributes']) ? $paramArray['excludeImportedAttributes'] : '');
        $sortBy                    = $this->escape(isset($paramArray['sortBy']) ? $paramArray['sortBy'] : '');
        $orderBy                   = $this->escape(isset($paramArray['orderBy']) ? $paramArray['orderBy'] : '');
        $productID                 = $this->escape(isset($paramArray['productID']) ? $paramArray['productID'] : '');
        $productRequestID          = $this->escape(isset($paramArray['productRequestID']) ? $paramArray['productRequestID'] : '');
        $unique                    = $this->escape(isset($paramArray['unique']) ? $paramArray['unique'] : '');
        //$isGlobal             			= $this->escape(isset($paramArray['isGlobal']) ? $paramArray['isGlobal']  : '');
        /*if($unique!='') {
            $sql                       = "
				SELECT
					proCusOpt.*,
					proCusOptDet.*
        } else {
            $sql                       = " SELECTproCusOpt.*,proCusOptDet.* ";"
        }*/
        $sql     = "
				SELECT
					proCusOpt.*,
					proCusOptDet.*						 
				FROM
					" . DB_PREFIX . "product_custom_option proCusOpt
				LEFT JOIN
					" . DB_PREFIX . "product_custom_option_details proCusOptDet
					ON proCusOpt.customOptionID=proCusOptDet.customOptionID
					AND proCusOptDet.languageID = '" . $currentLanguageID . "'						 
				WHERE
					proCusOpt.status!='D'";
        if ($isGlobal != '') {
            $sql .= "
					AND  proCusOpt.isGlobal='1'";
        }
        if ($customOptionID != '') {
            $sql .= "
					AND proCusOpt.customOptionID='" . $customOptionID . "'";
        }
        if ($customOptionName != '') {
            $sql .= "
					AND proCusOptDet.customOptionName LIKE'%" . $customOptionName . "%'";
        }
        if ($status != '') {
            $sql .= "
					AND proCusOpt.status='" . $status . "'";
        }
        //Exclude Alredy Imported 
        if ($excludeImportedAttributes == 'Yes') {
            if ($productRequestID) {
                $sql .= " 
					AND proCusOpt.customOptionID NOT IN 
					(
						SELECT
							customOptionID
						FROM
							" . DB_PREFIX . "product_request_custom_option_link  
						WHERE
							productRequestID='" . $productRequestID . "'
					)";
            } else {
                $sql .= " 
					AND proCusOpt.customOptionID NOT IN 
					(
						SELECT
							customOptionID
						FROM " . DB_PREFIX . "product_custom_option_link  
						WHERE
							productID='" . $productID . "'
					)";
            }
        }
        $sql .= " 
				GROUP BY
					proCusOpt.customOptionID";
        //Order the listing on the basis of priority during GroupID and scope search
        if ($sortBy == '') {
            $sql .= "
				ORDER BY
					proCusOptDet.customOptionName ASC";
        } elseif ($sortBy != '') {
            if ($sortBy == 'customOptionName') {
                $sql .= "
				ORDER BY
					proCusOptDet.customOptionName " . $orderBy;
            }
        } else //Default : on the basis of customOptionID
            {
            $sql .= "
				ORDER BY
					proCusOpt.customOptionID DESC";
        }        
        return $this->ObjDatabase->readValuesSlave($sql);
    }
    //Change Attribute Status
    public function updateOptionStatus($POST) {
        $status = $POST['changeStatus'];
        if ($status != '') {
            if (isset($POST['checkcustomOptionIDs']) && count($POST['checkcustomOptionIDs']) > 0) {
                for ($i = 0; $i < count($POST['checkcustomOptionIDs']); $i++) {
                    $customOptionIDData = explode("_", $POST['checkcustomOptionIDs'][$i]);
                    $customOptionID     = $customOptionIDData[0];
                    $customOptionType   = $customOptionIDData[1];
                    $update             = 1;
                    if ($status == "D" || $status == "I") {
                        if (strtolower($customOptionType) == 'select') {
                            $comboData  = $this->getcombinationData('', '', "global");
                            $vaiantData = $this->getvariantData($customOptionID);
                            if (count(array_intersect($vaiantData, $comboData)) > 0) {
                                $update = 0;
                            }
                        }
                    }
                    if ($update == 1) {
                        $sql = "
									UPDATE
										" . DB_PREFIX . "product_custom_option
									SET
										status = '$status' 
									WHERE
										customOptionID = '" . $customOptionID . "';";
                        $this->ObjDatabase->setQuery($sql);
                    }
                }
                return true;
            } else {
                $customOptionID   = $POST['id'];
                $customOptionType = $POST['type'];
                $update           = 1;
                if ($status == "D" || $status == "I") {
                    if (!empty($POST['productRequestID'])) {
                        $comboData  = $this->getcombinationData('', $POST['productRequestID'], "");
                        $vaiantData = $this->getvariantData($customOptionID, $POST['productRequestID']);
                    } else {
                        $comboData  = $this->getcombinationData('', '', "global");
                        $vaiantData = $this->getvariantData($customOptionID);
                    }
                    if (!empty($customOptionType) && strtolower($customOptionType) == 'select') {
                        if (count(array_intersect($vaiantData, $comboData)) > 0) {
                            $update = 0;
                        }
                    }
                }
                if (!empty($POST['productRequestID'])) {
                    if ($update == 1) {
                        $sql = "
						UPDATE
							" . DB_PREFIX . "product_request_custom_option
						SET
							status = '$status' 
						WHERE
							customOptionID ='" . $customOptionID . "';";
                        $this->ObjDatabase->setQuery($sql);
                        return 1;
                    } elseif ($update == 0)
                        return 2;
                } else {
                    if ($update == 1) {
                        $sql = "
						UPDATE
							" . DB_PREFIX . "product_custom_option
						SET
							status = '$status' 
						WHERE
							customOptionID = '" . $customOptionID . "';";
                        $this->ObjDatabase->setQuery($sql);
                        return 1;
                    } elseif ($update == 0)
                        return 2;
                }
            }
        }
        return false;
    }
    //list Attribute variant
    public function listOptionVariant($languageIDs, $paramArray) {
        $defultLanguageID         = $languageIDs['Default'];
        $currentLanguageID        = $languageIDs['Current'];
        //Get params from paramArray
        $customOptionID           = $this->escape($paramArray['customOptionID']);
        $customOptionVariantID    = isset($paramArray['customOptionVariantID']) ? $this->escape($paramArray['customOptionVariantID']) : '';
        $customOptionVariantCode  = isset($paramArray['customOptionVariantCode']) ? $this->escape($paramArray['customOptionVariantCode']) : '';
        $customOptionVariantImg   = isset($paramArray['customOptionVariantImg']) ? $this->escape($paramArray['customOptionVariantImg']) : '';
        $resAtributeOptionDetails = array();
        if ($customOptionID > 0) {
            $sqlSelectAttributeOptions = "
				SELECT
					proCustOptVar.*,
					proCustOpt.inputType as inputType,
					proCustOptVarDet.value as varValue,
					proCustOptVarDet.*	 
				FROM
					" . DB_PREFIX . "product_custom_option_variant proCustOptVar
				LEFT JOIN
					" . DB_PREFIX . "product_custom_option_variant_details proCustOptVarDet
					ON proCustOptVar.customOptionVariantID=proCustOptVarDet.customOptionVariantID
					AND proCustOptVarDet.languageID = '" . $currentLanguageID . "'
				LEFT JOIN
					" . DB_PREFIX . "product_custom_option proCustOpt
					ON proCustOptVar.customOptionID=proCustOpt.customOptionID
				WHERE
					proCustOptVar.customOptionID='" . $customOptionID . "'";
            if ($customOptionVariantID != '') {
                $sqlSelectAttributeOptions .= " 
					AND proCustOptVar.customOptionVariantID='" . $customOptionVariantID . "'";
            }
            if ($customOptionVariantCode != '') {
                $sqlSelectAttributeOptions .= " 
					AND proCustOptVar.variantCode='" . $this->escape($customOptionVariantCode) . "'";
            }
            if($customOptionVariantImg!='') {
                $sqlSelectAttributeOptions .= " AND proCustOptVar.variantCode!='' AND proCustOptVar.variantThumbImage!='' ";
            }
            $sqlSelectAttributeOptions .= " AND proCustOptVar.status!='D' AND proCustOpt.status!='D' ";            
            $sqlSelectAttributeOptions .= " 
				GROUP BY
					proCustOptVar.customOptionVariantID
				ORDER BY
					proCustOptVar.sortOrder ASC";
            //echo $sqlSelectAttributeOptions;exit;
            $resAtributeOptionDetails = $this->ObjDatabase->readValuesSlave($sqlSelectAttributeOptions);
        }
        return $resAtributeOptionDetails;
    }
    //Import Global Attribute as Custom Attribute
    public function importGlobalOptions($languageIDs, $paramArray) {
        $ObjImage                = new ImageModel();
        $defultLanguageID        = $languageIDs['Default'];
        $currentLanguageID       = $languageIDs['Current'];
        $AsLinkcustomOptionIDs   = array();
        //Get params from paramArray
        $customOptionIDs         = $this->escape($paramArray['customOptionIDs']);
        $AsLinkcustomOptionIDstr = (isset($paramArray['AsLinkcustomOptionIDs'])) ? $this->escape($paramArray['AsLinkcustomOptionIDs']) : '';
        $productID               = $this->escape($paramArray['productID']) <= 0 ? 0 : $this->escape($paramArray['productID']);
        $productRequestID        = $this->escape($paramArray['productRequestID']) <= 0 ? 0 : $this->escape($paramArray['productRequestID']);
        $proUriKey               = (isset($paramArray['proUriKey'])) ? $paramArray['proUriKey'] : '';
        if ($customOptionIDs && ($productID > 0 || $productRequestID > 0)) {
            $customOptionIDs = explode(",", $customOptionIDs);
            if ($AsLinkcustomOptionIDstr) {
                $AsLinkcustomOptionIDs = explode(",", $AsLinkcustomOptionIDstr);
            }
            foreach ($customOptionIDs as $customOptionID) {
                if (in_array($customOptionID, $AsLinkcustomOptionIDs)) {
                    $sqlImportAsLink = "
						INSERT INTO
							" . DB_PREFIX . "product_custom_option_link 
							(									   
								customOptionID,
								productID									   
							)
						VALUES
						( 
							" . $customOptionID . ",		
							" . $productID . "
						)";
                    $this->ObjDatabase->setQuery($sqlImportAsLink);
                } else {
                    //option Table Import
                    $sqlImportAttribute = "
					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_custom_option
						WHERE
							customOptionID = '" . $customOptionID . "'";
                    $this->ObjDatabase->setQuery($sqlImportAttribute);
                    $custominsertID   = $this->ObjDatabase->getInsertId();
                    $sqlImportlinking = "
					INSERT INTO
						" . DB_PREFIX . "product_custom_option_link 
						(									   
							customOptionID,
							productID									   
						)
					VALUES
					   ( 
							" . $custominsertID . ",		
							" . $productID . "
						)";
                    $this->ObjDatabase->setQuery($sqlImportlinking);
                    //Option Details Table Import
                    $sqlImportoptionDet = "
					INSERT INTO 
						" . DB_PREFIX . "product_custom_option_details
						(
							customOptionID,
							languageID,
							customOptionName,
							validationMessage,
							helpText
						)
					SELECT 
						" . $custominsertID . ",		
						languageID,
						customOptionName,
						validationMessage,
						helpText								  
					FROM
						" . DB_PREFIX . "product_custom_option_details
					WHERE
						customOptionID = '" . $customOptionID . "'";
                    $this->ObjDatabase->setQuery($sqlImportoptionDet);
                    $inputTypesql   = "
						SELECT 									  
							inputType
						FROM
							" . DB_PREFIX . "product_custom_option
						WHERE
							customOptionID = '" . $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_custom_option_variant
						WHERE
							customOptionID='" . $customOptionID . "'";
                        $resAttrOptions   = $this->ObjDatabase->readValuesSlave($sqlSelectOptions);
                        if (!empty($resAttrOptions)) {
                            foreach ($resAttrOptions as $options) {
                                $currentValueID         = $options['customOptionVariantID'];
                                $variantthumbImagesql   = "
								SELECT 									  
									variantThumbImage										  
								FROM
									" . DB_PREFIX . "product_custom_option_variant
								WHERE
									customOptionVariantID = '" . $currentValueID . "'";
                                $variantthumbImage_arry = $this->ObjDatabase->readValueSlave($variantthumbImagesql);
                                if ($variantthumbImage_arry['variantThumbImage']) {
                                    $extension_pos = strrpos($variantthumbImage_arry['variantThumbImage'], '.'); // find position of the last dot, so where the extension starts
                                    $sep_pos       = strrpos($variantthumbImage_arry['variantThumbImage'], '__');
                                    $thumbImage    = substr($variantthumbImage_arry['variantThumbImage'], 0, $sep_pos) . '__' . rand() . substr($variantthumbImage_arry['variantThumbImage'], $extension_pos);
                                    if ($ObjImage->file_exist("uploads/catalog/custom-option-variant/" . $variantthumbImage_arry['variantThumbImage'])) {
                                        $ObjImage->copy_file(__CORE_PUBLIC_UPLOADS_PATH . "catalog/custom-option-variant/" . $variantthumbImage_arry['variantThumbImage'], '/' . __UPLOADS_FOLDER . "catalog/custom-option-variant/" . $thumbImage);
                                    } else {
                                        $thumbImage = '';
                                    }
                                }
                                //Option Variant Table Import
                                $sqlImportAttributeOptions = "
									INSERT INTO
										" . DB_PREFIX . "product_custom_option_variant
										(											   
											customOptionID,
											variantThumbImage,
											priceDiff,
											priceDiffType,
											weightDiff,
											weightDiffType,
											sortOrder,
											isDefault,
											status
										)
										SELECT 											  
											" . $custominsertID . ",
											'" . $thumbImage . "',
											priceDiff,											   
											priceDiffType,
											weightDiff,
											weightDiffType,
											sortOrder,
											isDefault,
											status											   
										FROM
											" . DB_PREFIX . "product_custom_option_variant
										WHERE
											customOptionVariantID = '" . $currentValueID . "'";
                                $this->ObjDatabase->setQuery($sqlImportAttributeOptions);
                                $customOptionVariantID    = $this->ObjDatabase->getInsertId();
                                //Select Option Details
                                $sqlSelectOptionDetailIDs = "
										SELECT
											GROUP_CONCAT(customOptionVariantDetailsID) AS valueDetailsIDs 
										FROM
											" . DB_PREFIX . "product_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) {
                                        //Attribute 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_custom_option_variant_details
												WHERE
													customOptionVariantID IN (" . $currentValueID . ")";
                                        $this->ObjDatabase->setQuery($sqlImportAttributeOptDet);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //list Custom Product Option
    public function listCustomProductOption($languageIDs, $paramArray = array(),$type='') {
        $currentLanguageID  = $languageIDs['Current'];
        $excludeVariant     = isset($paramArray['excludeVariant']) ? $this->escape($paramArray['excludeVariant']) : '';
        $excludeVariant     = isset($paramArray['excludeVariant']) ? $this->escape($paramArray['excludeVariant']) : '';
        $variantInputs      = $this->getMultiVariants();
        //Get params from paramArray
        $customOptionID     = isset($paramArray['customOptionID']) ? $this->escape($paramArray['customOptionID']) : '';
        $customOptionName   = isset($paramArray['customOptionName']) ? $this->escape($paramArray['customOptionName']) : '';
        if($type=='') {
            $paramArray['status'] = 'A'; 
        }        
        $status             = isset($paramArray['status']) ? $this->escape($paramArray['status']) : '';
        $productID          = $this->escape($paramArray['productID']);
        $sqlSelectAttribute = "SELECT CO.customOptionID,COD.customOptionName,CO.isGlobal,CO.priceDiff,CO.priceDiffType,COD.validationMessage,COD.helpText,CO.validateRule,CO.inputType,CO.status,COL.customOptionLinkID";
        if ($excludeVariant == 'Yes') {
            $sqlSelectAttribute .= ",
		COD.*";
        }
        $sqlSelectAttribute .= " FROM " . DB_PREFIX . "product_custom_option_link  COL 
		LEFT JOIN " . DB_PREFIX . "product_custom_option CO ON (COL.customOptionID = CO.customOptionID)
		LEFT JOIN " . DB_PREFIX . "product_custom_option_details COD ON 
		(CO.customOptionID=COD.customOptionID	
		AND languageID='" . $currentLanguageID . "')						
		WHERE CO.status!='D'";
        if ($customOptionID != '') {
            $sqlSelectAttribute .= " AND CO.customOptionID='" . $customOptionID . "'";
        }
        if ($excludeVariant == 'Yes') {
            $sqlSelectAttribute .= " AND CO.inputType IN (" . $variantInputs . ") AND CO.include_in_combination='Yes' ";
        }
        if ($customOptionName != '') {
            $sqlSelectAttribute .= " AND COD.customOptionName='" . $customOptionName . "'";
        }
        if ($status != '') {
            $sqlSelectAttribute .= " AND CO.status='" . $status . "'";
        }
        if ($productID != '') {
            $sqlSelectAttribute .= " AND COL.productID='" . $productID . "'";
        }
        $sqlSelectAttribute .= " ORDER BY COL.sortOrder ASC";
        return $this->ObjDatabase->readValuesSlave($sqlSelectAttribute);
    }
    //Save Custom Attribute
    public function saveCustomOptions($languageIDs, $paramArray,$autoline='',$variantSave='') {
        $currentLanguageID                  = $languageIDs['Current'];
        $ObjImage                           = new ImageModel();
        $customOptionID                     = (isset($paramArray['customOptionID'])) ? $this->escape($paramArray['customOptionID']) : '';
        $customOptionName                   = (isset($paramArray['customOptionName'])) ? $this->escape($paramArray['customOptionName']) : '';
        $helpText                           = (isset($paramArray['helpText'])) ? $this->escape($paramArray['helpText']) : '';
        $inputType                          = (isset($paramArray['inputType'])) ? $this->escape($paramArray['inputType']) : '';
        $validateRuleRequired               = (isset($paramArray['validateRuleRequired'])) ? $this->escape($paramArray['validateRuleRequired']) : '';
        $validateRule                       = (isset($paramArray['validateRule'])) ? $this->escape($paramArray['validateRule']) : '';
        $validationMessage                  = (isset($paramArray['validationMessage'])) ? $this->escape($paramArray['validationMessage']) : '';
        $allowedExtensions                  = (isset($paramArray['allowedExtensions'])) ? $this->escape($paramArray['allowedExtensions']) : '';
        $maxFileSize                        = (isset($paramArray['maxFileSize'])) ? $this->escape($paramArray['maxFileSize']) : '';
        $priceDiff                          = (isset($paramArray['priceDiff'])) ? $this->escape($paramArray['priceDiff']) : '';
        $priceDiffType                      = (isset($paramArray['priceDiffType'])) ? $this->escape($paramArray['priceDiffType']) : '';
        $attrOptionAddCount                 = (isset($paramArray['attrOptionAddCount'])) ? $this->escape($paramArray['attrOptionAddCount']) : '';
        $status                             = (isset($paramArray['status'])) ? $this->escape($paramArray['status']) : '';
        $paramArray['includeInCombination'] = (isset($paramArray['includeInCombination'])) ? $paramArray['includeInCombination'] : '';
        
        $variantThumbImage                  = "";
        $includeInCombination               = "";
        if ($inputType == 'select') {
            $includeInCombination = (trim($paramArray['includeInCombination']) == 'Yes') ? "Yes" : "No";
        } else
            $includeInCombination = "No";
        $productID            = $this->escape($paramArray['productID']) <= 0 ? 0 : $this->escape($paramArray['productID']);
        $productRequestID     = $this->escape($paramArray['productRequestID']) <= 0 ? 0 : $this->escape($paramArray['productRequestID']);
        $attributeOptionsReqd = 1;
        if ($inputType == 'textbox' || $inputType == 'textarea' || $inputType == 'date' || $inputType == 'datetime' || $inputType == 'file') {
            $attributeOptionsReqd = 0;
        }
        //Set Constraints
        if ($inputType == 'date' || $inputType == 'time' || $inputType == 'datetime' || $inputType == 'file' || $inputType == 'select' || $inputType == 'multiselect') {
            $validateRule = '';
        }
        //Set Validation 
        if ($validateRuleRequired == 'Yes' && $validateRule != '') {
            $validateRule = "required~*" . $validateRule;
        } elseif ($validateRuleRequired == 'Yes' && $validateRule == '') {
            $validateRule = "required";
        } elseif ($validateRuleRequired == '' && $validateRule == '') {
            $validationMessage = '';
        }
        if ($productID > 0 || $productRequestID > 0) {
            //Save Attribute 
            if(($variantSave=='' && $autoline=='') || ($autoline!='' && $variantSave=='No')) {          
            
                if ($customOptionID > 0) //Update
                {
                    
                        //Attribute table
                        $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option
                                        SET 	
                                        inputType='" . $inputType . "',
                                        validateRule='" . $validateRule . "',
                                        include_in_combination='" . $includeInCombination . "',
                                        priceDiff='" . $priceDiff . "',
                                        priceDiffType='" . $priceDiffType . "',
                                        status = '" . $status . "' 
                                        WHERE customOptionID = '" . $customOptionID . "'");
                        //Attribute Detail									  
                        $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option_details
                                        SET 	customOptionName='" . $customOptionName . "',
                                        validationMessage='" . $validationMessage . "',
                                        helpText = '" . $helpText . "' 
                                        WHERE customOptionID = '" . $customOptionID . "' AND languageID ='" . $currentLanguageID . "'");
                } else //Insert
                {
                    
                    //Attribute table
                    $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option 
                                    (
                                    inputType,
                                    validateRule,
                                    include_in_combination,	
                                    isGlobal,
                                    priceDiff,
                                    priceDiffType,
                                    status
                                    ) 
                                    VALUES 
                                    ( 
                                    '" . $inputType . "',
                                    '" . $validateRule . "',
                                    '" . $includeInCombination . "',				    
                                    '0',
                                    '" . $priceDiff . "',
                                    '" . $priceDiffType . "',
                                    '" . $status . "')");
                    $customOptionID      = $this->ObjDatabase->getInsertId();
                    //Attribute Detail
                    $insertAttrDetailSql = "INSERT INTO " . DB_PREFIX . "product_custom_option_details 
                                    (customOptionID, 
                                    languageID, 
                                    customOptionName, 
                                    validationMessage,
                                    helpText
                                    ) 
                                    VALUES";
                    foreach ($languageIDs['AllList'] as $langIds) {
                        $insertAttrDetailValueSql[] = "('" . $customOptionID . "', 
                                    '" . $langIds . "', 
                                    '" . $customOptionName . "',
                                    '" . $validationMessage . "', 
                                    '" . $helpText . "')";
                    }
                    $insertAttrDetailSql = $insertAttrDetailSql . implode(",", $insertAttrDetailValueSql);
                    $this->ObjDatabase->setQuery($insertAttrDetailSql);
                    $sqlImportAsLink = "INSERT INTO " . DB_PREFIX . "product_custom_option_link 
                                    (									   
                                    customOptionID,
                                    productID									   
                                    )
                                    VALUES( 
                                    " . $customOptionID . ",		
                                    " . $productID . "
                                    )";
                    $this->ObjDatabase->setQuery($sqlImportAsLink);
                }
            }
            if($autoline!='') {
                if($variantSave=='No') {
                    $attributeOptionsReqd = 0;
                } else {
                    $attributeOptionsReqd = 1;
                }
                
            }            
            
            //Save Attribute Options
            if ($attributeOptionsReqd == 1 && !empty($paramArray['attrOptionsGroup'])) {
                
                foreach ($paramArray['attrOptionsGroup'] as $rowKey => $row) // Traverse through all posted options
                    {                    
                    $customOptionVariantID = (int) $row['customOptionVariantID'];
                    if ($row['is_delete'] == 1) // Option is deleted
                        {
                        if ($customOptionVariantID > -1) // Option already present in db. Delete it	
                            {
                            $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "product_custom_option_variant WHERE customOptionVariantID='" . $customOptionVariantID . "'");
                            $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "product_custom_option_variant_details WHERE customOptionVariantID='" . $customOptionVariantID . "'");
                        }
                    } else {
                        $valueTitle        = $this->escape($row['varValue']);
                        $sortOrder         = $this->escape($row['sortOrder']);
                        $priceDiff         = $this->escape($row['priceDiff']);
                        $priceDiffType     = $this->escape($row['priceDiffType']);
                        $weightDiff        = $this->escape($row['weightDiff']);
                        $weightDiffType    = $this->escape($row['weightDiffType']);
                        $vsbID             = (isset($row['vsbID'])) ? $row['vsbID'] : '';
                        $variantCode       = (isset($row['variantCode'])) ? $this->escape($row['variantCode']) : '';
                        $bmwCode       = (isset($row['bmwcode'])) ? $this->escape($row['bmwcode']) : '';
                        $isDefault         = (isset($row['isDefault'])) ? $this->escape($row['isDefault']) : '';
                        $varStatus         = (isset($row['varStatus'])) ? $row['varStatus'] : 'A';
                        $attrFile          = "";
                        $attrFileType      = "";
                        $updateFileSection = 1;
                        //option image section
                        if ($inputType == 'select' && $autoline=='') {
                            if ($includeInCombination == 'Yes') {
                                $priceDiff      = 0;
                                $priceDiffType  = 'N';
                                $weightDiff     = 0;
                                $weightDiffType = 'N';
                            }
                            //ThumbNail
                            $variantThumbImageType = $paramArray['OptionVariantThumb_' . $rowKey];
                            /*if($variantThumbImageType)
                            $variantThumbImage  = $variantThumbImageType;*/
                            /*if(($paramArray["OptionVariantThumb_". $rowKey . "_temp"]!=''))
                            {			
                            if ($variantThumbImage)
                            {  
                            copy($paramArray["OptionVariantThumb_". $rowKey . "_temp"], __CORE_PUBLIC_UPLOADS_PATH."catalog/custom-option-variant/".$variantThumbImage); 
                            $ObjImage->resizeImage(__CORE_PUBLIC_UPLOADS_PATH."catalog/custom-option-variant/".$variantThumbImage,"", 20,20);
                            }
                            if($customOptionVariantID > -1)				
                            $this->deleteVariantImage($customOptionVariantID);   
                            @unlink(__ROOT_PATH.'/'.$paramArray["OptionVariantThumb_". $rowKey . "_temp"]);
                            
                            }*/
                            if (($paramArray["OptionVariantThumb_" . $rowKey . "_temp"] != '')) {
                                if ($variantThumbImageType)
                                    $variantThumbImage = $variantThumbImageType;
                                if ($variantThumbImage) {
                                    $ObjImage->resizeImage(__ROOT_PATH . '/' . $paramArray["OptionVariantThumb_" . $rowKey . "_temp"], "", 20, 20);
                                    $ObjImage->copy_file($paramArray["OptionVariantThumb_" . $rowKey . "_temp"], "/" . __UPLOADS_FOLDER . "catalog/custom-option-variant/" . $variantThumbImage);
                                }
                                if ($customOptionVariantID > -1) {
                                    $this->deleteVariantImage($customOptionVariantID);
                                }
                                @unlink(__ROOT_PATH . '/' . $paramArray["OptionVariantThumb_" . $rowKey . "_temp"]);
                            } else {
                                if ($variantThumbImageType != '')
                                    $variantThumbImage = $variantThumbImageType;
                                else
                                    $variantThumbImage = '';
                            }
                        } 
                        if ($customOptionVariantID > -1) // Option already present in db. Update it
                            {
                             //Attribute options
                            if($autoline!='') {
                                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option_variant
                                                            SET
                                                            priceDiff='" . $priceDiff . "',                                                            
                                                            priceDiffType='" . $priceDiffType . "',
                                                            weightDiff='" . $weightDiff . "',
                                                            weightDiffType = '" . $weightDiffType . "', 
                                                            sortOrder = '" . $sortOrder . "',
                                                            isDefault = '" . $isDefault . "' ,variantCode= '" . $variantCode . "',vsbID= '" . $vsbID . "',bmwCode= '" . $bmwCode . "',status='".$varStatus."' 
                                                            WHERE customOptionVariantID = '" . $customOptionVariantID . "'");
                            } else {
                                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option_variant
                                                                SET
                                                                priceDiff='" . $priceDiff . "',
                                                                variantThumbImage='" . $variantThumbImage . "',
                                                                priceDiffType='" . $priceDiffType . "',
                                                                weightDiff='" . $weightDiff . "',
                                                                weightDiffType = '" . $weightDiffType . "',
                                                                sortOrder = '" . $sortOrder . "',
                                                                isDefault = '" . $isDefault . "' ,variantCode= '" . $variantCode . "',vsbID= '" . $vsbID . "',bmwCode= '" . $bmwCode . "' 
                                                                WHERE customOptionVariantID = '" . $customOptionVariantID . "'");
                            }
                            
                            //Attribute option Detail
                            $attrOptionDetailSql = "UPDATE " . DB_PREFIX . "product_custom_option_variant_details
					  SET 	value='" . $valueTitle . "'";
                            $attrOptionDetailSql .= " WHERE customOptionVariantID = '" . $customOptionVariantID . "' AND languageID ='" . $currentLanguageID . "'";
                            $this->ObjDatabase->setQuery($attrOptionDetailSql);
                        } else // New option Insertion
                            {
                            $varStatus = ($autoline!='') ? $varStatus:'A';
                            //Attribute options
                            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_custom_option_variant 
				(customOptionID,
				variantThumbImage,
				priceDiff, 
				priceDiffType, 
				weightDiff,
				weightDiffType,
				sortOrder,
				isDefault,
                                variantCode,
                                vsbID,
                                bmwCode,
                                status
				) 
				VALUES 
				('" . $customOptionID . "',
				'" . $variantThumbImage . "', 
				'" . $priceDiff . "', 
				'" . $priceDiffType . "', 
				'" . $weightDiff . "',
				'" . $weightDiffType . "',															   
				'" . $sortOrder . "',
				'" . $isDefault . "','" . $variantCode . "','" . $vsbID . "','" . $bmwCode . "','".$varStatus."')");
                            $customOptionVariantID          = $this->ObjDatabase->getInsertId();
                            //Attribute option Detail
                            $insertAttrOptionDetailSql      = "INSERT INTO " . DB_PREFIX . "product_custom_option_variant_details 
				(customOptionVariantID, 
				languageID, 
				value
				) 
				VALUES";
                            $insertAttrDetailOptionValueSql = '';
                            foreach ($languageIDs['AllList'] as $langIds) {
                                $insertAttrDetailOptionValueSql[] = "('" . $customOptionVariantID . "', 
					'" . $langIds . "', 
					'" . $valueTitle . "')";
                            }
                            $insertAttrOptionDetailSql = $insertAttrOptionDetailSql . implode(",", $insertAttrDetailOptionValueSql);
                            $this->ObjDatabase->setQuery($insertAttrOptionDetailSql);
                        }
                    }
                    //option image section
                }
            }
        }
        if ($inputType == 'file') {
            $validateRule = '';
            if ($validateRuleRequired == 'Yes') {
                $validateRule = 'required~*';
            }
            if ($maxFileSize != '') {
                $validateRule .= "checkFileSize->" . $maxFileSize . "~*";
            }
            $validateRule .= "isValidFileExtension";
            if ($allowedExtensions != '')
                $validateRule .= "->" . $allowedExtensions;
        }
        $this->updateOptionRule($customOptionID, $validateRule);
        if($autoline!='') {
            if($variantSave=='No') {
                return $customOptionID; 
            } else {
                return $customOptionVariantID;
            }
        }
    }
    //Change Custom Attribute Status
    public function updateProOptionStatus($POST) {
        $productID        = $POST['productID'];
        $productRequestID = $POST['productRequestID'];
        if (isset($POST['checkOptionIDs']) && count($POST['checkOptionIDs']) > 0) {
            for ($i = 0; $i < count($POST['checkOptionIDs']); $i++) {
                $optionID            = $POST['checkOptionIDs'][$i];
                $sqlUpdateAttrStatus = "DELETE FROM  " . DB_PREFIX . "product_custom_option_link 
		WHERE `productID` ='" . $productID . "' AND `customOptionID` ='" . $optionID . "'";
                $updateAttrStatus    = $this->ObjDatabase->setQuery($sqlUpdateAttrStatus);
            }
        } else {
            $optionID = $POST['id'];
            $isGlobal = $POST['isGlobal'];
            if ($productRequestID > 0) {
                $sqlUpdateAttrStatus = "DELETE FROM  " . DB_PREFIX . "product_request_custom_option_link 
		WHERE `productRequestID` ='" . $productRequestID . "' AND `customOptionID` ='" . $optionID . "'";
            } else {
                $sqlUpdateAttrStatus = "DELETE FROM  " . DB_PREFIX . "product_custom_option_link 
		WHERE `productID` ='" . $productID . "' AND `customOptionID` ='" . $optionID . "'";
            }
            $updateAttrStatus = $this->ObjDatabase->setQuery($sqlUpdateAttrStatus);
            if ($isGlobal != 1) {
                $POST['changeStatus'] = 'D';
                $this->updateOptionStatus($POST);
            }
        }
        if ($updateAttrStatus)
            echo "1";
        else
            echo "0";
        exit();
    }
    //Assign Custom Attribute Values to Product
    public function assignCustomOptionToProduct($languageIDs, $productID, $POST, $productRequestID = '') {
        $currentLanguageID = $languageIDs['Current'];
        //Save POST Details
        if ($POST) {
            //Traverse through POST Values
            foreach ($POST as $postKey => $postValue) {
                //Update Priority
                if ($postKey == "customAttributes") {
                    $i = 0;
                    foreach ($postValue as $attrID => $priority) {
                        $i++;
                        if ($priority['priority'] > 0) {
                            $priority = $priority['priority'];
                        } else {
                            $priority = $i;
                        }
                        if ($productRequestID)
                            $sqlUpdateAttrPriority = "UPDATE  " . DB_PREFIX . "product_request_custom_option_link  SET sortOrder = '" . $priority . "' 
				WHERE customOptionID ='" . $attrID . "' AND productRequestID='" . $productRequestID . "'";
                        else
                            $sqlUpdateAttrPriority = "UPDATE  " . DB_PREFIX . "product_custom_option_link  SET sortOrder = '" . $priority . "' 
				WHERE customOptionID ='" . $attrID . "' AND productID='" . $productID . "'";
                        $updateAttrPriority = $this->ObjDatabase->setQuery($sqlUpdateAttrPriority);
                    }
                }
            }
        }
    }
    //Check Forbidden Files
    public function checkForbiddenFile($file) {
        // List of forbidden file extensions (for uploaded files)
        $forbidden_file_extensions = array(
            'php',
            'php3',
            'pl',
            'com',
            'exe',
            'bat',
            'cgi',
            'htaccess'
        );
        $forbidden_mime_types      = array(
            'text/x-php',
            'application/octet-stream',
            'text/x-perl',
            'text/x-python',
            'text/x-shellscript'
        );
    }
    public function updateOptionRule($optId, $validateRule) {
        $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_custom_option
				SET	      
				validateRule='" . $validateRule . "'
				WHERE customOptionID = '" . $optId . "'");
    }
    public function getMultiVariants() {
        return $variantInputs = "'select'";
    }
    public function addProductCombo($selectedBusinessID=0) {
        $ObjImage      = new ImageModel();
        $ObjProduct    = new ProductModel();
        $ObjProductReq = new ProductRequestModel();
        if (substr($_POST['selectedAttrIDs'], -1) == '*') {
            $SortedAttrIDs = substr($_POST['selectedAttrIDs'], 0, -2);
        }
        $SortedAttrIDs = explode('~*', $SortedAttrIDs);
        if (count($SortedAttrIDs) > 0) {
            $productID  = $this->escape($_POST['productID']);
            $businessID = $this->escape($_POST['businessID']);
            if (!empty($_POST['productRequestID']))
                $productRequestID = $this->escape($_POST['productRequestID']);
            else
                $productRequestID = '';
            $tablePrefix = '';
            $id          = $productID;
            if (!empty($productRequestID)) {
                $tablePrefix = "request_";
                $id          = $productRequestID;
            }
            $combination     = $id . "_" . implode('_', $SortedAttrIDs);
            $combinationHash = $this->makeHAsh($combination);
            $combinationID   = $_POST['combinationID'];
            $comboexist      = $this->isComboAlreadyExists($combination, $combinationID, $productRequestID);
            $comboSKU        = $this->escape($_POST['combinationSKU']);
            $comboskuexist   = $this->isComboSKUAlreadyExists($comboSKU, $combinationID, $productID, $productRequestID, $businessID);
            if ((!$comboexist) && ($comboskuexist == 0)) {
                if (!empty($_POST['combo_image'])) {
                    if ($combinationID) {
                        if ((($_POST["combo_thumbImage_temp"] == "")) && (($_POST["combo_image_temp"] == ""))) {
                            $imageComboFlag = 1;
                        } else {
                            $imageComboFlag = 0;
                        }
                    } else {
                        $imageComboFlag = 0;
                    }
                    if ($imageComboFlag != 1) {
                        $comboImage = $this->getImageName($_POST['combo_image']);
                        if ($productRequestID)
                            $comboImage_Loc = "/" . __UPLOADS_FOLDER . "catalog-request/product-combination/";
                        else
                            $comboImage_Loc = "/" . __UPLOADS_FOLDER . "catalog/product-combination/";
                        $paramMedia['productImage'] = $_POST["combo_image"];
                        if (($_POST["combo_thumbImage"] != '') && ($_POST["combo_thumbImage_temp"] == '')) {
                            $paramMedia['thumbFlag'] = 1;
                            $paramMedia['resImage']  = $_POST['hidComboMain'];
                        }
                        $paramMedia['mainImage_temp']  = $_POST["combo_image_temp"];
                        $paramMedia['thumbImage_temp'] = $_POST["combo_thumbImage_temp"];
                        $paramMedia['mediaParam']      = $_POST['mediaParam'];
                        $paramMedia['mainImage']       = $comboImage;
                        $paramMedia['destFolder']      = "product-combination";
                        if ($comboImage && $combinationID) {
                            $this->deleteComboMedia($combinationID, $productRequestID, "1");
                        }
                        if ($comboImage) {
                            if ($productRequestID)
                                $comboImage = $ObjProductReq->generateRequestMedia($paramMedia);
                            else
                                $comboImage = $ObjProduct->generateMedia($paramMedia);
                        }
                    }
                } else {
                    if ($combinationID) {
                        $imageComboFlag = 1;
                        $this->deleteComboMedia($combinationID, $productRequestID);
                    }
                }
                //Update
                if(!isset($_POST['combinationGroup'])){
                    $_POST['combinationGroup'][0]['combinationMerchant']     =  $businessID;
                    $_POST['combinationGroup'][0]['combinationDiffType']     =  $_POST['combinationPriceDiffType'];
                    $_POST['combinationGroup'][0]['combinationPrice']        =  $_POST['combinationPrice'];;
                    $_POST['combinationGroup'][0]['combinationMerchantSKU']  =  $_POST['combinationSKU'];;
                    $_POST['combinationGroup'][0]['combinationQuantity']     =  $_POST['combinationQty'];;
                }
                //echo "<pre>"; print_r($_POST); exit;
                if ($combinationID) {
                    $sql = "
						UPDATE
							" . DB_PREFIX . "product_" . $tablePrefix . "combination
						SET 	
							productID='" . $id . "',
							combination='" . $combination . "',
							combinationHash='" . $combinationHash . "',
							combinationSKU='" . $this->escape($_POST['combinationSKU']) . "',
							combinationBarCode='" . $this->escape($_POST['combinationBarCode']) . "',
							combinationQty='" . $this->escape($_POST['combinationQty']) . "',
							combinationPrice='" . $this->escape($_POST['combinationPrice']) . "',
							combinationPriceDiffType='" . $this->escape($_POST['combinationPriceDiffType']) . "',	
							combinationWeight='" . $this->escape($_POST['combinationWeight']) . "',
							combinationWeightDiffType='" . $this->escape($_POST['combinationWeightDiffType']) . "',
							combinationHeight='" . $this->escape($_POST['combinationHeight']) . "',
							combinationWidth='" . $this->escape($_POST['combinationWidth']) . "',
							combinationLength='" . $this->escape($_POST['combinationLength']) . "',
							status = '" . $this->escape($_POST['status']) . "' 
						WHERE  	
							combinationID = '" . $combinationID . "'";
                    $this->ObjDatabase->setQuery($sql);
                    $this->groupTierPriceUpdate($combinationID, $tablePrefix);
                    $addComboBusiness    =   $this->addCombinationBusiness($combinationID,$_POST['combinationGroup'],$selectedBusinessID);
                    $action = "2";
                }
                //Insert
                else {
                    $sql = "
						INSERT INTO " . DB_PREFIX . "product_" . $tablePrefix . "combination 
							(
							`productID`, 
							`combination`, 
							`combinationHash`, 
							`combinationSKU`,
							`combinationBarCode`, 
							`combinationQty`, 
							`combinationPrice`,
							`combinationPriceDiffType`, 
							`status`,
							`combinationWeight`,
							`combinationWeightDiffType`,
							`combinationHeight`,
							`combinationWidth`,
							`combinationLength`
							)
						VALUES 
							( 
							'" . $id . "',
							'" . $combination . "',
							'" . $combinationHash . "',
							'" . $this->escape($_POST['combinationSKU']) . "',
							'" . $this->escape($_POST['combinationBarCode']) . "',
							'" . $this->escape($_POST['combinationQty']) . "',
							'" . $this->escape($_POST['combinationPrice']) . "',
							'" . $this->escape($_POST['combinationPriceDiffType']) . "',
							'" . $this->escape($_POST['status']) . "',
							'" . $this->escape($_POST['combinationWeight']) . "',
							'" . $this->escape($_POST['combinationWeightDiffType']) . "',
							'" . $this->escape($_POST['combinationHeight']) . "',
							'" . $this->escape($_POST['combinationWidth']) . "',
							'" . $this->escape($_POST['combinationLength']) . "'
							)";
                    $this->ObjDatabase->setQuery($sql);
                    $combinationID = $this->ObjDatabase->getInsertId();
                    $this->groupTierPriceUpdate($combinationID, $tablePrefix);
                    $addComboBusiness    =   $this->addCombinationBusiness($combinationID,$_POST['combinationGroup'],$selectedBusinessID);
                    $action = "1";
                }
                if (isset($comboImage)) {
                    if ($productRequestID) {
                        $sql = "
							INSERT INTO `" . DB_PREFIX . "product_request_media` 
								(
								`productObjectID`, 
								`productMedia`,
								`productMediaType`,
								`productObjectType`,
								`productRequestID`
								) 
							VALUES 
								(
								'" . $combinationID . "', 
								'" . $comboImage . "',
								'I',
								'C',
								'" . $productRequestID . "'
								)";
                        $this->ObjDatabase->setQuery($sql);
                    } else {
                        $sql = "
							INSERT INTO `" . DB_PREFIX . "product_media` 
								(
								`productObjectID`, 
								`productMedia`,
								`productMediaType`,
								`productObjectType`,
								`productID`
								) 
							VALUES 
								(
								'" . $combinationID . "',
								'" . $comboImage . "',
								'I',
								'C',
								'" . $productID . "'
								)";
                        $this->ObjDatabase->setQuery($sql);
                    }
                }
            } elseif ($comboexist) {
                $action = "3";
            } elseif ($comboskuexist) {
                $action = "4";
            }
        }
        return $action;
    }
    public function groupTierPriceUpdate($combinationID, $tablePrefix) {
        $combinationGroup = isset($_POST['combinationGroup'][0]) ? $_POST['combinationGroup'][0] : '';
        $group_price      = isset($combinationGroup['group_price']) ? $combinationGroup['group_price'] : '';
        $tier_price       = isset($combinationGroup['tier_price']) ? $combinationGroup['tier_price'] : '';
        if (!empty($group_price)) {
            $groupPrice = array();
            foreach ($group_price as $group_price) {
                if ($group_price['specialPrice'] > 0) {
                    array_push($groupPrice, "('" . $combinationID . "','" . $group_price['userGroupID'] . "','" . $group_price['specialPrice'] . "')");
                }
            }
            $sql = "
				DELETE FROM 
					`" . DB_PREFIX . "combination_" . $tablePrefix . "group_price` 
				WHERE
					combinationID = '" . $combinationID . "'
			";
            $this->ObjDatabase->setQuery($sql);
            $sql = "
				INSERT INTO `" . DB_PREFIX . "combination_" . $tablePrefix . "group_price`
					(
					`combinationID`, 
					`userGroupID`, 
					`specialPrice`
					)
				VALUES
					" . implode(",", $groupPrice) . "
			";
            $this->ObjDatabase->setQuery($sql);
        }
        if (!empty($tier_price)) {
            $groupPrice = array();
            foreach ($tier_price as $tier_price) {
                if ($tier_price['quantity'] > 0 && $tier_price['tierPrice'] > 0) {
                    array_push($groupPrice, "(
						'" . $combinationID . "',
						'" . $tier_price['userGroupID'] . "',
						'" . $tier_price['quantity'] . "',
						'" . $tier_price['tierPrice'] . "'
						)");
                }
            }
            $sql = "
				DELETE FROM 
					`" . DB_PREFIX . "combination_" . $tablePrefix . "tier_price` 
				WHERE
					combinationID = '" . $combinationID . "' 
			";
            $this->ObjDatabase->setQuery($sql);
            $sql = "
				INSERT INTO `" . DB_PREFIX . "combination_" . $tablePrefix . "tier_price`
					(
					`combinationID`, 
					`userGroupID`, 
					`quantity`, 
					`tierPrice`
					)
				VALUES
					" . implode(",", $groupPrice) . "
			";
            $this->ObjDatabase->setQuery($sql);
        }
    }
    public function getProductCustomOptions($languageIDs, $productID,$customOptionID='',$showAllProducts='') {
        $currentLanguageID = $languageIDs['Current'];
		if($showAllProducts=='Yes') {
			$updprodstatus = " IN ('A','I') ";
		} else {
			$updprodstatus = " = 'A' ";				
		}
        if ($productID > 0) {
            $sql    = "SELECT 
		proCusOpt.*, 
		proCusOptDet.customOptionName, 
		proCusOptDet.validationMessage, 
		proCusOptDet.helpText
		FROM 
		" . DB_PREFIX . "product_custom_option as proCusOpt  
		LEFT JOIN 
		" . DB_PREFIX . "product_custom_option_details as proCusOptDet 
		ON 
		proCusOpt.customOptionID = proCusOptDet.customOptionID 
		AND proCusOptDet.languageID = " . (int) $currentLanguageID . " 
		LEFT JOIN 
		" . DB_PREFIX . "product_custom_option_link as proCusOptLin
		ON
		proCusOptLin.customOptionID=proCusOpt.customOptionID
		WHERE 
		proCusOptLin.productID =" . (int) $productID . " ";
            if($customOptionID!='') {
                $sql    .= "	AND proCusOpt.customOptionID = '".$customOptionID."' ";
            }
            
             $sql    .= "	AND proCusOpt.status ".$updprodstatus."
		ORDER BY 
		proCusOptLin.sortOrder";
            $result = $this->ObjDatabase->readValuesSlave($sql);
            if (count($result) > 0) {
                return $result;
            } else {
                return array();
            }
        }
    }
    public function getCustomCombinations($productID,$variantID='',$type='',$showAllProducts='') {
         if($showAllProducts=='Yes') {
			$updprodcombstatus = " IN ('A','I') ";
		} else {
			$updprodcombstatus = " = 'A' ";				
		}
        $tableName = ($type=='')?'':'_mini';
        $sql = "select comb.customOptionID from " . DB_PREFIX . "product_custom_option_combination".$tableName." comb 
                where productID='".$productID."' and comb.status ".$updprodcombstatus." ";
        if($variantID!='') {
            $sql .= " and comb.customOptionID LIKE '".$variantID."\_%' ";
        }
        $sql .= " group by comb.customOptionID ";
        
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    public function getProductCustomOptionsCount($productID,$type='',$languageIDs=array(),$showAllProducts='') {
        if ($productID > 0) {
			if($showAllProducts=='Yes') {
				$updprodcombstatus = " IN ('A','I') ";
			} else {
				$updprodcombstatus = " = 'A' ";				
			}
            $sql    = "
				SELECT 
				proCusOpt.customOptionID ";
            if($type!='') {
                $sql    .= ",proCusOptDet.customOptionName ";
            }
            $sql    .= "		FROM 
				" . DB_PREFIX . "product_custom_option 		AS proCusOpt  ";
            if($type!='') {
                $sql    .= " LEFT JOIN 
				" . DB_PREFIX . "product_custom_option_details AS proCusOptDet
				ON (proCusOptDet.customOptionID=proCusOpt.customOptionID and proCusOptDet.languageID='".$languageIDs['Current']."') ";
            }
            $sql    .= "        LEFT JOIN 
				" . DB_PREFIX . "product_custom_option_link AS proCusOptLin
				ON proCusOpt.customOptionID=proCusOptLin.customOptionID
				WHERE 
				proCusOptLin.productID = " . (int) $productID . "
				AND 
				proCusOpt.status ".$updprodcombstatus." ";
			if($type!='') {
                $sql    .= "AND (proCusOptDet.customOptionName ='Color' OR proCusOptDet.customOptionName ='Upholstery') ";
            }
			$sql    .= "	ORDER BY 
				proCusOptLin.sortOrder";
            $result = $this->ObjDatabase->readValuesSlave($sql);
            if($type=='') {
                 return count($result);
            } else {
                 return $result;
            }
        }
    }
    public function getCustomOptionVariants($languageIDs, $customOptionID,$variantArr=array(),$status='') {
        $currentLanguageID = $languageIDs['Current'];
        if ($customOptionID > 0) {
            $sql    = "SELECT  
			proCusOptVar.customOptionVariantID,
			proCusOptVarDet.value,
			proCusOptVar.customOptionID, 
			proCusOptVar.variantThumbImage, 
                        proCusOptVar.variantCode, 
			proCusOptVar.priceDiff, 
			proCusOptVar.priceDiffType, 
			proCusOptVar.weightDiff, 
			proCusOptVar.weightDiffType, 
			proCusOptVar.sortOrder,
			proCusOptVar.isDefault,
                        proCusOptVar.variantCode,
			proCusOptVar.status						 
			FROM 
			" . DB_PREFIX . "product_custom_option_variant as proCusOptVar 
			LEFT JOIN 
			" . DB_PREFIX . "product_custom_option_variant_details as proCusOptVarDet 
			ON proCusOptVar.customOptionVariantID = proCusOptVarDet.customOptionVariantID 
			AND proCusOptVarDet.languageID = " . (int) $currentLanguageID . " 
			WHERE 
			proCusOptVar.customOptionID =" . (int) $customOptionID . "   ";
            if(!empty($variantArr)) {
                $customVarIDs = implode(",", $variantArr);
                $sql .= " and proCusOptVar.customOptionVariantID IN (".$customVarIDs.") ";
            }
            $sql .= " and proCusOptVar.status!='D' ";
            if($status!='') {
                $sql .= " and proCusOptVar.status='A' ";
            }
            $sql .=    " ORDER BY 
			proCusOptVar.sortOrder, 
			proCusOptVar.customOptionVariantID";
            $result = $this->ObjDatabase->readValuesSlave($sql);
            return $result;
        }
    }
    public function getProductOptionDetails($params = array()) {
        extract($params);
        $defaultLanguageID        = $languageIDs['Default'];
        $currentLanguageID        = $languageIDs['Current'];
        $paramsArray              = array(
            'tableName' => 'products',
            'fieldName' => 'InventoryTrackLevel',
            'conditionField' => 'productID',
            'condition' => '=',
            'conditionValue' => $productID,
            'conditionFieldType' => 'int'
        );
        $resInventoryTrackLevel   = $this->getFieldValue($paramsArray);
        $paramsArray              = array(
            'tableName' => 'products',
            'fieldName' => 'showQuantityAvailable,productMinBuyLimit',
            'conditionField' => 'productID',
            'condition' => '=',
            'conditionValue' => $productID,
            'conditionFieldType' => 'int'
        );
        $resshowQuantityAvailable = $this->getFieldValue($paramsArray);
        $productQuantityUnlimited = ($resInventoryTrackLevel['InventoryTrackLevel'] == 'No') ? 1 : 0;
        
        $currBusinessID           = isset($currBusinessID) ? $currBusinessID : 0;
        if($currBusinessID>0){
            $sqlAppend            = " AND prodOptBus.businessID = '".$currBusinessID."'";
            $sqlTableAppend       =  "prodOptBus";
        }else{
            $sqlAppend            = " AND prodOptBus.businessOptionDefault='Yes'";
            $sqlTableAppend       =  "prodOptBus";
        }
        
        $sql                      = " 
			SELECT 
				$sqlTableAppend.productOptionRegularPrice,
				LEAST(
					COALESCE(
						varOffPri.offerPrice,
						$sqlTableAppend.productOptionProductPrice
					),
					COALESCE(
						varGroPri.specialPrice,
						$sqlTableAppend.productOptionProductPrice
					) 
				)
				AS offerPrice,
				ROUND(
					(
						(
							(
							$sqlTableAppend.productOptionRegularPrice-
								LEAST(
									COALESCE(
										varOffPri.offerPrice,
										$sqlTableAppend.productOptionProductPrice
									),
									COALESCE(
										varGroPri.specialPrice,
										$sqlTableAppend.productOptionProductPrice
									) 
								)
							)*100
						)/$sqlTableAppend.productOptionRegularPrice
					),2
				) AS productOptionOfferDiscount,
                                prodOptBus.businessID as optBusinessID,
				$sqlTableAppend.productOptionProductPrice,
                                $sqlTableAppend.dealPrice,
                                productOpt.productOptionCashBack,
                                business.businessKey,
                                businessDet.businessName,";
        if ($resInventoryTrackLevel['InventoryTrackLevel'] == 'Options') {
            $sql .= " 
					SUM(CAST(IFNULL(proCom.combinationQty,0) AS UNSIGNED)) as productOptionQuantity,
					" . $productQuantityUnlimited . " as productQuantityUnlimited, ";
        } else {
            $sql .= " 
					productOpt.productOptionQuantity,
					" . $productQuantityUnlimited . " as productQuantityUnlimited, ";
        }
        $sql .= "
					'" . $resInventoryTrackLevel['InventoryTrackLevel'] . "' as InventoryTrackLevel,
					'" . $resshowQuantityAvailable['showQuantityAvailable'] . "' as showQuantityAvailable,
					" . $resshowQuantityAvailable['productMinBuyLimit'] . " as productMinBuyLimit,
					productOpt.productOptionStatus,
					productOpt.productID,
					(productOpt.productOptionRegularPrice-productOpt.productOptionProductPrice) AS productOptionSavePrice,
					ROUND(((
						(productOpt.productOptionRegularPrice-productOpt.productOptionProductPrice)*100)
						/productOpt.productOptionRegularPrice))
						AS productOptionDiscount,
					productOpt.productOptionID
					FROM 
							" . DB_PREFIX . "product_options productOpt 
                                                LEFT JOIN
                                                        ".DB_PREFIX."products_options_business AS prodOptBus
                                                                ON	(
                                                                        prodOptBus.productOptionID = productOpt.productOptionID
                                                                        $sqlAppend
                                                                )
                                                LEFT JOIN
                                                        ".DB_PREFIX."business AS business
                                                                ON	(
                                                                        business.businessID = prodOptBus.businessID
                                                                )
                                                LEFT JOIN
                                                        ".DB_PREFIX."business_details AS businessDet
                                                                ON	(
                                                                        businessDet.businessID = business.businessID
                                                                        AND businessDet.languageID = '".$currentLanguageID."'
                                                                )
						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 . "'
								)	
							";
        if ($resInventoryTrackLevel['InventoryTrackLevel'] == 'Options') {
            $sql .= " 
						LEFT JOIN 
							" . DB_PREFIX . "product_combination AS proCom 
								ON (
									proCom.productID=" . (int) $productID . " 
									AND 
									proCom.status = 'A'
								) ";
        }
        $sql .= " 
					WHERE 
						productOpt.productOptionID=" . (int) $productOptionID . "
						AND 
						productOptionStatus='Active' ";
        return $this->ObjDatabase->readValueSlave($sql);
    }
    public function getProductOptionImages($productOptionID = 0) {
        $sql = "
				SELECT 
					deaMed.productMedia as productImage
				FROM 
					" . DB_PREFIX . "product_media as deaMed 
				WHERE 
					deaMed.productObjectID=" . (int) $productOptionID . "
					AND
					productObjectType='DO' 
				ORDER BY deaMed.productMediaPriority ASC ";
        return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
    }
    public function getCombinationImages($combinationHash = 0, $productOptionID = 0) {
        $paramsArray      = array(
            'tableName' => 'product_combination',
            'fieldName' => 'combinationID',
            'conditionField' => 'combinationHash',
            'condition' => '=',
            'conditionValue' => $combinationHash,
            'conditionFieldType' => ''
        );
        $rescombinationID = $this->getFieldValue($paramsArray);
        $sql              = "
				SELECT 
					deaMed.productMedia as productImage
				FROM 
					" . DB_PREFIX . "product_media as deaMed 
				WHERE 
					deaMed.productObjectID=" . (int) $rescombinationID['combinationID'] . "
					AND
					productObjectType='C' 
				ORDER BY deaMed.productMediaPriority ASC ";
        $result           = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        if (count($result) > 0) {
            return array(
                $result,
                'combination'
            );
        } else {
            $resultTemp = $this->getProductOptionImages($productOptionID);
            return array(
                $resultTemp,
                ''
            );
        }
    }
    public function getProductCombination($params = array()) {
        extract($params);
        $checkBusinessComb = isset($checkBusinessComb) ? $checkBusinessComb : "";
        $currentLanguageID = isset($languageIDs['Current']) ? $languageIDs['Current'] : '';
        if(isset($businessID) && $businessID>0){
            $sqlFields      =          "proCombBus.businessCombSKU as combinationSKU,
                                        IF(proCombBus.businessCombQuantity = '',1,0) as combinationQtyUnlimited,
                                        CAST(IFNULL(proCombBus.businessCombQuantity,0) AS UNSIGNED) as combinationQty,
                                        proCombBus.businessCombPrice as combinationPrice,
                                        proCombBus.businessCombPrice as actualPrice,
                                        proCombBus.businessCombDiff as combinationPriceDiffType";
            $sqlJoin        =          "INNER JOIN 
					" . DB_PREFIX . "product_combination_business as proCombBus 
						ON 	(
							proCombBus.combinationID = proCom.combinationID	
						)";
        }else{
            $sqlFields      =          "proCom.combinationSKU,
                                        IF(proCom.combinationQty = '',1,0) as combinationQtyUnlimited,
                                        CAST(IFNULL(proCom.combinationQty,0) AS UNSIGNED) as combinationQty,
                                        proCom.combinationPrice,
                                        proCom.combinationPrice as actualPrice,
                                        proCom.combinationPriceDiffType";
            $sqlJoin        =          "";
        }
        if (isset($purpose) && $purpose == "basic") {
            $selectFields = "
					proCom.combinationID,
					proCom.combination,
                                        proCom.status,
					$sqlFields";
        } else {
            $selectFields = "
					proCom.combination,
					proCom.combinationHash,
					proCom.combinationHeight,
					proCom.combinationID,
					proCom.combinationLength,
					proCom.combinationWeight,
					proCom.combinationWeightDiffType,
					proCom.combinationWidth,					
					proCom.status,
					proCom.productID,
                                        $sqlFields";
        }
        $sql = " SELECT
					" . $selectFields;
        $sql .= "	
				FROM 
						
						" . DB_PREFIX . "product_combination as proCom $sqlJoin";
        $sql .= "	WHERE 
					proCom.productID ='" . (int) $productID . "'";
        if(isset($businessID) && $businessID>0){
            $sql .= " 
					AND proCombBus.businessID = '".$businessID."'";
        }
        if (isset($status) && $status == 'A') {
            $sql .= " 
					AND proCom.status='A'";
        } else {
            $sql .= " 
					AND proCom.status!='D'";
        }
        $result = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        if (count($result) > 0) {
            if($checkBusinessComb=="Yes"){
                foreach($result as $key=>$res){
                    $busCombinations    =   $this->getProductBusinessCombination($languageIDs,$res['combinationID']);
                    $result[$key]['busCombinations'] = $busCombinations;
                }
            }
            return $result;
        } else {
            return array();
        }
    }
    public function getProductCustomCombination($params = array()) {
        extract($params);
        $checkBusinessComb = isset($checkBusinessComb) ? $checkBusinessComb : "";
        $currentLanguageID = isset($languageIDs['Current']) ? $languageIDs['Current'] : '';
        $selectFields      = " proCustComb.* ";
       
        $sql               = " SELECT " . $selectFields;
        $sql              .= " FROM " . DB_PREFIX . "product_custom_option_combination as proCustComb ";
        $sql              .= "	WHERE proCustComb.productID ='" . (int) $productID . "'";
        
        if (isset($status) && $status == 'A') {
            $sql .= " AND proCustComb.status='A'";
        } else {
            $sql .= " AND proCustComb.status!='D'";
        }
        $sql     .= " order by proCustComb.customOptionID ASC";
        $result = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        $resultSet = array();
        if (count($result) > 0) {
                $arr        = array();
                $resultinv  = array();
                foreach($result as $key=>$res){
                    
                    $custID             =   explode("_",$res['customOptionID']);
                    $sqlComb            =   "SELECT procustvardet.value,procustdet.customOptionName from " . DB_PREFIX . "product_custom_option_variant procustvar inner join " . DB_PREFIX . "product_custom_option_variant_details procustvardet on (procustvardet.customOptionVariantID=procustvar.customOptionVariantID and procustvardet.languageID='".$languageID."')";
                    $sqlComb            .=   " inner join " . DB_PREFIX . "product_custom_option prodcust on (prodcust.customOptionID=procustvar.customOptionID) ";
                    $sqlComb            .=   " inner join " . DB_PREFIX . "product_custom_option_details procustdet on (procustdet.customOptionID=prodcust.customOptionID and procustdet.languageID='".$languageID."') ";
                    $sqlComb            .=   " where procustvar.customOptionVariantID IN (".$custID[0].",".$custID[1].") order by procustdet.customOptionName ";
                   
                    $resComb            =   $this->ObjDatabase->readValues($sqlComb);
                    if(!empty($resComb)) {
                        //if($resComb[0]['customOptionName']=='Color') {
                            $result[$key]['custnameco']     = $resComb[0]['customOptionName'];
                            $result[$key]['custnamevalue1'] = $resComb[0]['value'];
                        //} if($resComb[1]['customOptionName']=='Upholstery') {
                            $result[$key]['custnameup']     = $resComb[1]['customOptionName'];
                            $result[$key]['custnamevalue2'] = $resComb[1]['value'];
                        //}
                        /*foreach($resComb as $rec) {
                            if($res['customOptionName']=='Color') {                                      
                                $result[$key]['custnameco']     = $rec['customOptionName'];
                                $result[$key]['custnamevalue1'] = $rec['value'];
                                
                            } else {
                                $result[$key]['custnameup']     = $rec['customOptionName'];
                                $result[$key]['custnamevalue2'] = $rec['value'];
                            }
                           
                        }*/
                    }
                    if(empty($arr) || (!empty($arr) && !in_array($res['customOptionID'],$arr))) {
                         $resultinv[$res['customOptionID']]['stock']                 = 1;
                    } elseif(!empty($arr) && in_array($res['customOptionID'],$arr)) {
                         $resultinv[$res['customOptionID']]['stock']                 = $resultinv[$res['customOptionID']]['stock'] + 1;
                    }
                    $arr[]  = $res['customOptionID'];
                    
                }
                
            $resultSet['results'] = $result;            
            $resultSet['stock']   = $resultinv;
            return $resultSet;
        } else {
            return array();
        }
    }
    public function getProductCustomCombinationMini($params = array()) {
        extract($params);
        $checkBusinessComb = isset($checkBusinessComb) ? $checkBusinessComb : "";
        $currentLanguageID = isset($languageIDs['Current']) ? $languageIDs['Current'] : '';
        $selectFields      = " proCustComb.* ";
       
        $sql               = " SELECT " . $selectFields;
        $sql              .= " FROM " . DB_PREFIX . "product_custom_option_combination_mini as proCustComb ";
        $sql              .= "	WHERE proCustComb.productID ='" . (int) $productID . "'";
        
        if (isset($status) && $status == 'A') {
            $sql .= " AND proCustComb.status='A'";
        } else {
            $sql .= " AND proCustComb.status!='D'";
        }
        $sql     .= " order by proCustComb.customOptionID ASC";
        $result = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        $resultSet = array();
        if (count($result) > 0) {
                $arr        = array();
                $resultinv  = array();
                foreach($result as $key=>$res){
                    
                    $custID             =   explode("_",$res['customOptionID']);
                    $varIDs             =   !empty($custID[0]) ? $custID[0]:'';
                    if(!empty($custID[1])) {                        
                        $varIDs         =   !empty($varIDs) ? $varIDs.",".$custID[1]:$custID[1];
                    } 
                    $sqlComb            =   "SELECT procustvardet.value,procustdet.customOptionName from " . DB_PREFIX . "product_custom_option_variant procustvar inner join " . DB_PREFIX . "product_custom_option_variant_details procustvardet on (procustvardet.customOptionVariantID=procustvar.customOptionVariantID and procustvardet.languageID='".$languageID."')";
                    $sqlComb            .=   " inner join " . DB_PREFIX . "product_custom_option prodcust on (prodcust.customOptionID=procustvar.customOptionID) ";
                    $sqlComb            .=   " inner join " . DB_PREFIX . "product_custom_option_details procustdet on (procustdet.customOptionID=prodcust.customOptionID and procustdet.languageID='".$languageID."') ";
                    $sqlComb            .=   " where procustvar.customOptionVariantID IN (".$varIDs.") order by procustdet.customOptionName desc ";
                   
                    $resComb            =   $this->ObjDatabase->readValues($sqlComb);
                    if(!empty($resComb)) {
                        //if($resComb[0]['customOptionName']=='Color') {
                            $result[$key]['custnameco']     = $resComb[0]['customOptionName'];
                            $result[$key]['custnamevalue1'] = $resComb[0]['value'];
                        //} if($resComb[1]['customOptionName']=='Upholstery') {
                            $result[$key]['custnameup']     = !empty($resComb[1]['customOptionName'])?$resComb[1]['customOptionName']:'';
                            $result[$key]['custnamevalue2'] = !empty($resComb[1]['value']) ? $resComb[1]['value']: '';
                        //}
                        /*foreach($resComb as $rec) {
                            if($res['customOptionName']=='Color') {                                      
                                $result[$key]['custnameco']     = $rec['customOptionName'];
                                $result[$key]['custnamevalue1'] = $rec['value'];
                                
                            } else {
                                $result[$key]['custnameup']     = $rec['customOptionName'];
                                $result[$key]['custnamevalue2'] = $rec['value'];
                            }
                           
                        }*/
                    }
                    if(empty($arr) || (!empty($arr) && !in_array($res['customOptionID'],$arr))) {
                         $resultinv[$res['customOptionID']]['stock']                 = 1;
                    } elseif(!empty($arr) && in_array($res['customOptionID'],$arr)) {
                         $resultinv[$res['customOptionID']]['stock']                 = $resultinv[$res['customOptionID']]['stock'] + 1;
                    }
                    $arr[]  = $res['customOptionID'];
                    
                }
                
            $resultSet['results'] = $result;            
            $resultSet['stock']   = $resultinv;
            return $resultSet;
        } else {
            return array();
        }
    }
    public function getProductCombinationByID($comboID,$businessID=0) {
        if($businessID>0){
            $sql = "
			SELECT 
				proCom.combinationID,
                                proCom.productID,
                                proCom.combination,
                                proCom.combinationHash,
                                proCom.combinationBarCode,
                                proCom.status,
                                proCom.combinationWeight,
                                proCom.combinationWeightDiffType,
                                proCom.combinationHeight,
                                proCom.combinationWidth,
                                proCom.combinationLength,
				productMedia,
				proCom.status as Combstatus,
                                proCombBus.businessCombSKU as combinationSKU,
                                proCombBus.businessCombQuantity as combinationQty,
                                proCombBus.businessCombPrice as combinationPrice,
                                proCombBus.businessCombDiff as combinationPriceDiffType
			FROM 
					" . DB_PREFIX . "product_combination as proCom
                                INNER JOIN 
					" . DB_PREFIX . "product_combination_business as proCombBus 
						ON 	(
							proCombBus.combinationID = proCom.combinationID	
						)
				LEFT JOIN 
					" . DB_PREFIX . "product_media as productMed 
						ON 	(
							proCom.combinationID = productMed.productObjectID	
						)
			WHERE 
				proCom.combinationID ='" . (int) $comboID . "'
                                AND proCombBus.businessID = '".$businessID."'";
            return $this->ObjDatabase->readValueSlave($sql);
        }else{
            $sql = "
                            SELECT 
                                    proCom.* ,
                                    productMedia,
                                    proCom.status as Combstatus
                            FROM 
                                            " . DB_PREFIX . "product_combination as proCom
                                    LEFT JOIN 
                                            " . DB_PREFIX . "product_media as productMed 
                                                    ON 	(
                                                            proCom.combinationID = productMed.productObjectID	
                                                    )
                            WHERE 
                                    proCom.combinationID ='" . (int) $comboID . "'";
            return $this->ObjDatabase->readValueSlave($sql);
        }
    }
    //To get oombination details	
    public function getCombinationVariants($languageIDs, $combination) {
        $combination    = explode('_', $combination);
        $customOptionID = $combination[0];
        unset($combination[0]);
        $variants          = implode(",", $combination);
        $currentLanguageID = $languageIDs['Current'];
        if ($variants) {
            $varArray = array();
            $sql      = "
				SELECT 
					proCusOptVarDet.value,
					proCusOptDet.customOptionName,
					proCusOptVar.customOptionVariantID
				FROM 
						" . DB_PREFIX . "product_custom_option_variant as proCusOptVar 
					LEFT JOIN 
						" . DB_PREFIX . "product_custom_option_variant_details as proCusOptVarDet 
							ON 	(
								proCusOptVar.customOptionVariantID = proCusOptVarDet.customOptionVariantID 
								AND 
								proCusOptVarDet.languageID = '" . (int) $currentLanguageID . "'
							)
					LEFT JOIN 
						" . DB_PREFIX . "product_custom_option_details as proCusOptDet 
							ON 	(
								proCusOptVar.customOptionID = proCusOptDet.customOptionID 
								AND 
								proCusOptDet.languageID = '" . (int) $currentLanguageID . "'	
							)
				WHERE 
					proCusOptVar.customOptionVariantID IN (" . $variants . ")";
            $result   = $this->ObjDatabase->readValuesSlave($sql);
            $i        = 0;
            foreach ($result as $resvariants) {
                $varArray[$i]['customOptionName'] = $resvariants['customOptionName'];
                $varArray[$i]['variantName']      = $this->fn_html_entity_decode($resvariants['value']);
                $varArray[$i]['variantID']        = $resvariants['customOptionVariantID'];
                $i++;
            }
            return $varArray;
        }
    }
    /*$paramsArray(	'tableName'=>'product_custom_option_variant',
    'fieldName'=>'customOptionVariantID',
    'conditionField'=>'customOptionVariantID',
    'condition'=>'=',
    'conditionValue'=>'5',
    'conditionFieldType'=>'int'
    )
    */
    public function getFieldValue($paramsArray = array()) {
        extract($paramsArray);
        $sql = "SELECT
				" . $fieldName . "
			FROM
				" . DB_PREFIX . $tableName;
        if ($conditionField != '' && $condition != '') {
            $sql .= " WHERE
					" . $conditionField . " " . $condition;
            if ($conditionFieldType == 'int') {
                $sql .= " " . (int) $conditionValue;
            } else {
                $sql .= "'" . $conditionValue . "'";
            }
        }
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result;
    }
    public function updateComboStatus($POST) {
        $comboID = $POST['comboID'];
        $status  = $POST['status'];
        if (!empty($POST['productRequestID']))
            $sqlUpdateAttrStatus = "UPDATE  " . DB_PREFIX . "product_request_combination SET `status` = '" . $status . "' 
					WHERE `combinationID` ='" . $comboID . "';";
        else
            $sqlUpdateAttrStatus = "UPDATE  " . DB_PREFIX . "product_combination SET `status` = '" . $status . "' 
					WHERE `combinationID` ='" . $comboID . "';";
        $updateAttrStatus = $this->ObjDatabase->setQuery($sqlUpdateAttrStatus);
        if ($status == 'D')
            $this->deleteComboMedia($comboID, $POST['productRequestID']);
        return true;
    }
    public function isComboAlreadyExists($combo, $comboID = NULL, $productRequestID = '') {
        if (!empty($productRequestID))
            $prefix = "request_";
        else
            $prefix = '';
        $combo = trim($combo);
        if ($comboID)
            $append = "AND `combinationID` != '" . $comboID . "'";
        else
            $append = '';
        $sql    = "SELECT 
		1 
		FROM 
		`" . DB_PREFIX . "product_" . $prefix . "combination` 
		WHERE 
		`combination` = '" . $combo . "' AND `status` != 'D' $append";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        if ($result)
            return true;
        else
            return false;
    }
    public function isComboSKUAlreadyExists($combosku, $comboID = NULL, $productID, $productRequestID = '', $businessID) {
        $combosku               = trim($combosku);
        $append                 = '';
        $skuFound               = 0;
        $result                 = 0;
        $resSelectProductOpt    = 0;
        $resultreq              = 0;
        $resSelectProductReqOpt = 0;
        if ($comboID) {
            $append = "AND `combinationID` != '" . $comboID . "'";
        }
        $sql    = "
			SELECT 
				1 
			FROM 
				" . DB_PREFIX . "product_combination proCombo
			LEFT JOIN
				" . DB_PREFIX . "products products
				ON(products.productID=proCombo.productID)
			WHERE 
				products.businessID=" . $businessID . "
				AND combinationSKU = '" . $combosku . "' 
				AND status != 'D' $append";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        if ($result == 0) //not in product_combination
            {
            $sql                 = "
				SELECT 
					1 
				FROM 
					" . DB_PREFIX . "product_options OPT
				LEFT JOIN " . DB_PREFIX . "products products ON(products.productID=OPT.productID)	
				WHERE 
				products.businessID=" . $businessID . " AND productOptionStatus!='Delete' 
				AND OPT.optionSKU = '" . $combosku . "'";
            $resSelectProductOpt = $this->ObjDatabase->numberOfRecords($sql);
            if ($resSelectProductOpt > 0) // in product_options
                {
                $skuFound = 1;
            }
        } elseif ($result > 0) // in product_combination
            {
            $skuFound = 1;
        }
        if ($productRequestID) // Request
            {
            if ($skuFound == 0) {
                $sql       = "
				SELECT 
					1 
				FROM 
					" . DB_PREFIX . "product_request_combination proCombo
				LEFT JOIN
					" . DB_PREFIX . "product_requests products 
					ON(products.productRequestID=proCombo.productID)
				WHERE 
					products.businessID=" . $businessID . " 
					AND combinationSKU = '" . $combosku . "' 
					AND status != 'D' $append";
                $resultreq = $this->ObjDatabase->numberOfRecords($sql);
            }
            if ($resultreq == 0) // not in product_request_combination
                {
                $sql                    = "
						SELECT 
							1 
						FROM 
							" . DB_PREFIX . "product_request_options OPT
						LEFT JOIN
							" . DB_PREFIX . "product_requests products 
							ON(products.productRequestID=OPT.productRequestID)	
						WHERE 
							products.businessID=" . $businessID . "
							AND productOptionStatus!='Delete' 
							AND OPT.optionSKU = '" . $combosku . "'";
                $resSelectProductReqOpt = $this->ObjDatabase->numberOfRecords($sql);
                if ($resSelectProductReqOpt > 0) {
                    $skuFound = 1;
                }
            } elseif ($resultreq > 0) // in product_request_combination
                {
                $skuFound = 1;
            }
            if ($skuFound == 1) {
                return 1;
            } else {
                return 0;
            }
        } else {
            if ($skuFound == 1) {
                return 1;
            } else {
                return 0;
            }
        }
    }
    public function getComboImageByID($comboID, $type = '') {
        if ($type)
            $table_prefix = "request_";
        else
            $table_prefix = "";
        $sql    = "
		SELECT 
		deaMed.productMedia as productImage
		FROM 
		" . DB_PREFIX . "product_" . $table_prefix . "media as deaMed 
		WHERE 
		deaMed.productObjectID=" . (int) $comboID . "
		AND
		productObjectType='C'";
        $result = $this->ObjDatabase->readValueSlave($sql);
        return $result['productImage'];
    }
    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 deleteComboMedia($combinationID, $requestID, $del = "0") {
        $ObjImage = new ImageModel();
        if ($del == "0") {
            if (!empty($requestID)) {
                $sql = "SELECT 									  
			productMedia
			FROM
			`" . DB_PREFIX . "product_request_media` WHERE productObjectID='" . $combinationID . "' AND  productObjectType='C'";
            } else {
                $sql = "SELECT 									  
			productMedia
			FROM									
			`" . DB_PREFIX . "product_media` WHERE productObjectID='" . $combinationID . "'  AND  productObjectType='C'";
            }
            $result = $this->ObjDatabase->readValueSlave($sql);
            if ($result['productMedia']) {
                if ($requestID) {
                    $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog-request/product-combination/preview-main/" . $result['productMedia']);
                    $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog-request/product-combination/large/" . $result['productMedia']);
                } else {
                    $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog/product-combination/thumb/" . $result['productMedia']);
                    $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog/product-combination/large/" . $result['productMedia']);
                    $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog/product-combination/preview/" . $result['productMedia']);
                    $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog/product-combination/small/" . $result['productMedia']);
                    $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog/product-combination/preview-main/" . $result['productMedia']);
                }
            }
        }
        if ($requestID)
            $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_request_media` WHERE productObjectID='" . $combinationID . "' AND  productObjectType='C'");
        else
            $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_media` WHERE productObjectID='" . $combinationID . "' AND  productObjectType='C'");
    }
    public function deleteVariantImage($customOptionVariantID) {
        $ObjImage            = new ImageModel();
        $variantmainImagesql = "SELECT 									  
			variantThumbImage									
			
			FROM
			" . DB_PREFIX . "product_custom_option_variant
			WHERE
			customOptionVariantID = '" . $customOptionVariantID . "'";
        $variantthumb_arry   = $this->ObjDatabase->readValueSlave($variantmainImagesql);
        if ($variantthumb_arry['variantThumbImage']) {
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog/custom-option-variant/" . $variantthumb_arry['variantThumbImage']);
        }
    }
    public function getInputShortKeys() {
        return $exportKeys = array(
            'textbox' => 'I',
            'textarea' => 'A',
            'select' => 'S',
            'multiselect' => 'C',
            'date' => 'D',
            'datetime' => 'W',
            'time' => 'T',
            'file' => 'F'
        );
    }
    public function getcombinationData($productID = '', $requestID = '', $section = '') {
        if ($requestID) {
            $ctable_prefix = "request_";
            $dtable_prefix = "_request";
            $field_prefix  = "Request";
            $productID     = $requestID;
        } else {
            $ctable_prefix = "";
            $dtable_prefix = "";
            $field_prefix  = "";
        }
        $variant_arry = array();
        $sql          = "SELECT 
				    combination 	 
				    FROM 
				    " . DB_PREFIX . "product_" . $ctable_prefix . "combination proComb
				    LEFT JOIN 
				    " . DB_PREFIX . "product" . $dtable_prefix . "s product
				    ON (proComb.productID = product.product" . $field_prefix . "ID) 				     
				    WHERE ";
        if ($section == '')
            $sql .= " product.product" . $field_prefix . "ID='" . $productID . "' AND proComb.status!='D'";
        else
            $sql .= " proComb.status!='D'";
        $result = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        if (!empty($result)) {
            foreach ($result as $combination) {
                $combination = explode('_', $combination['combination']);
                unset($combination[0]);
                $variants[] = implode(",", $combination);
            }
            $variants1    = implode(",", $variants);
            $variant_arry = explode(",", $variants1);
            $variant_arry = array_unique($variant_arry);
        }
        return $variant_arry;
    }
    public function getVariantsForOptions($customOptionID, $languageIDs) {
        $currentLanguageID = $languageIDs['Current'];
        if (count($customOptionID) > 0) {
            $customOptionID = implode(",", $customOptionID);
            $sql            = "SELECT 
						proCusOptVar.customOptionVariantID,
						proCusOptVar.customOptionID,
						proCusOptVarDet.value,
						proCusOptVar.customOptionID
						priceDiff,
						priceDiffType,
						weightDiff,
						weightDiffType
				    FROM 
							" . DB_PREFIX . "product_custom_option_variant as proCusOptVar 
						LEFT JOIN 
							" . DB_PREFIX . "product_custom_option_variant_details as proCusOptVarDet 
								ON 	(
									proCusOptVar.customOptionVariantID = proCusOptVarDet.customOptionVariantID 
									AND 
									proCusOptVarDet.languageID = " . (int) $currentLanguageID . " 
								)
				    WHERE 
						proCusOptVar.customOptionID IN (" . $customOptionID . ")   
				    ORDER BY 
						proCusOptVar.sortOrder, 
						proCusOptVar.customOptionVariantID";
            $result         = $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
            return $result;
        } else
            return array();
    }
    public function getvariantData($customOptionID, $requestID = '') {
        if ($requestID)
            $table_prefix = "request_";
        else
            $table_prefix = "";
        $sql    = "SELECT 
				    group_concat(`customOptionVariantID` separator ',') as `variant`
				    FROM 
				    " . DB_PREFIX . "product_" . $table_prefix . "custom_option_variant  WHERE 
				    customOptionID=" . $customOptionID;
        $result = $this->ObjDatabase->readValueSlave($sql);
        return explode(",", $result['variant']);
    }
    function fn_html_entity_decode($data) {
        return html_entity_decode($data);
    }
    public function getImageName($img_file) {
        $info      = pathinfo($img_file);
        $file_name = basename($img_file, '.' . $info['extension']);
        return $file = $file_name . "." . $info['extension'];
    }
    
    public function addCombinationBusiness($combinationID,$combGroup,$selectedBusinessID=0){
        $sqlDelete      =       "DELETE FROM `".DB_PREFIX."product_combination_business`
                                 WHERE combinationID = '".$combinationID."'";
        if($selectedBusinessID>0){
            $sqlDelete  .=       " AND businessID = '".$selectedBusinessID."'";
        }
        $resDelete      =       $this->ObjDatabase->setQuery($sqlDelete);
        
        
        if(count($combGroup)>0){
            foreach($combGroup as $group){
                $combinationMerchant      =     $group['combinationMerchant'];
                $sqlSelect                =     "SELECT COUNT(*) as combCnt FROM `".DB_PREFIX."product_combination_business`
                                                 WHERE combinationID = '".$combinationID."'
                                                 AND businessID = '".$combinationMerchant."'";
                $combCount                =      $this->ObjDatabase->getField($sqlSelect);
                if($combCount<=0){
                    if($group['combinationDiffType']=="N"){
                        $groupCombPrice   =     0;
                    }else{
                        $groupCombPrice   =     $group['combinationPrice'];
                    }
                    $sqlInsert            =     "INSERT INTO `".DB_PREFIX."product_combination_business`
                                                                         (combinationID,
                                                                          businessID,
                                                                          businessCombSKU,
                                                                          businessCombQuantity,
                                                                          businessCombPrice,
                                                                          businessCombDiff) VALUES
                                                                          ('".$combinationID."',
                                                                           '".$group['combinationMerchant']."',
                                                                           '".$this->escape($group['combinationMerchantSKU'])."',
                                                                           '".$group['combinationQuantity']."',
                                                                           '".$groupCombPrice."',
                                                                           '".$this->escape($group['combinationDiffType'])."')";
                    $resInsert             =     $this->ObjDatabase->setQuery($sqlInsert);
                }
            }
        }
    }
    
    public function getProductBusinessCombination($languageIDs,$combinationID){
        $sqlSelect  =   "SELECT prodCombBus.*,
                         IF(prodCombBus.businessCombQuantity = '',1,0) as businessCombQtyUnlimited,
                         businessDet.businessName
                         FROM ".DB_PREFIX."product_combination_business prodCombBus 
                         LEFT JOIN ".DB_PREFIX."business_details businessDet ON
                         (businessDet.businessID = prodCombBus.businessID AND
                          businessDet.languageID = '".$languageIDs['Current']."')
                         WHERE prodCombBus.combinationID = '".$combinationID."'
                         ORDER BY prodCombBus.combBusinessID ASC";
        $result     =   $this->ObjDatabase->readValuesSlave($sqlSelect);
        return $result;
    }
    public function checkProductCustomOption($languageIDs,$customOptionName='',$productID='') {
        $sql = "select prodcust.customOptionID from " . DB_PREFIX . "product_custom_option_link prodcust inner join
                " . DB_PREFIX . "product_custom_option pcust on (pcust.customOptionID=prodcust.customOptionID) inner join
                " . DB_PREFIX . "product_custom_option_details pcustdet on (pcustdet.customOptionID=pcust.customOptionID AND
                pcustdet.languageID = '".$languageIDs['Current']."') where  pcust.isGlobal='0'    
                ";
        if ($customOptionName != '') {
            $sql .= " AND pcustdet.customOptionName LIKE'%" . $this->escape($customOptionName) . "%'";
        }
        if ($productID>0) {
            $sql .= " AND prodcust.productID ='" . $productID . "'";
        }
        $sql .= " AND pcust.status !='D'";     
        
        $result     =   $this->ObjDatabase->readValue($sql);
        return $result;
    }
    public function getMaxVariantSortOrder($customOptionID='') {
        
        if($customOptionID>0) {
            $sql = "select custvar.sortOrder from " . DB_PREFIX . "product_custom_option_variant custvar inner join
                " . DB_PREFIX . "product_custom_option pcust on (pcust.customOptionID=custvar.customOptionID)
                where  custvar.customOptionID='".$customOptionID."' order by custvar.sortOrder desc limit 0,1  
                ";
                        
            $result     =   $this->ObjDatabase->readValue($sql);           
            return !empty($result)?$result['sortOrder']+1:0;
        }
    }
    public function getIsDefaultVariant($customOptionID='',$variantID='',$status='') {
        
        if($customOptionID>0) {
            $sql = "select custvar.isDefault from " . DB_PREFIX . "product_custom_option_variant custvar inner join
                " . DB_PREFIX . "product_custom_option pcust on (pcust.customOptionID=custvar.customOptionID)
                where  custvar.customOptionID='".$customOptionID."' and custvar.isDefault='1'   
                ";  
            if($variantID!='') {
                $sql .= " and custvar.customOptionVariantID!='".$variantID."' and custvar.status='A' ";
            }
            if($status!='') {
                $sql .= " and custvar.status='A' ";
            }
            $sql .= " limit 0,1";
            $result     =   $this->ObjDatabase->readValue($sql);
            return $result;
        }
    }
    public function updateIsDefaultVariant($customOptionID='',$variantID='',$type='') {
        
        if($customOptionID>0) {
            if($type=='') {
                $sql = "update " . DB_PREFIX . "product_custom_option_variant set isDefault='1' where customOptionID='".$customOptionID."' and status='A' ";              
            } else {
                $sql = "update " . DB_PREFIX . "product_custom_option_variant set isDefault='0' where customOptionID='".$customOptionID."' and status='I' ";              
            }
            $sql .= " LIMIT 1";
            $result     =   $this->ObjDatabase->setQuery($sql);
            
        }
        return true;
    }
	
    public function getVariantDetails($customOptionVariantID='') {

        if($customOptionVariantID>0) {
            $sql = "select * from " . DB_PREFIX . "product_custom_option_variant custvar 
                where  custvar.customOptionVariantID='".$customOptionVariantID."'  limit 0,1  
                ";                        
            $result     =   $this->ObjDatabase->readValue($sql);
            return $result;
        }
    }
}