<?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: ProductRequestModel.php, v 1.0 2011/06/14 20:52:11
//
class ProductRequestModel extends Model {
    //FUNCTION TO LIST DEAL REQUESTS
    public function listProductRequests($params) {
        extract($params);
        $currentLanguageID = $languageIDs['Current'];
        switch ($sortBy) {
            case "skey":
                $sortBy = "CAST( productReq.productRequestKey AS SIGNED INTEGER)";
                break;
            case "stitle":
                $sortBy = "productReqDet.productTitle";
                break;
            case "sbusiness":
                $sortBy = "busDet.businessName";
                break;
            case "screated":
                $sortBy = "productReq.productCreatedDate";
                break;
            default:
                $sortBy = "productReq.productCreatedDate DESC";
                break;
        }
        if ($sortBy != "productReq.productCreatedDate") {
            $orderBy .= " ,productCreatedDate DESC ";
        }
        $sql = "SELECT ";
        if ($limitTo) {
            $sql .= "SQL_CALC_FOUND_ROWS ";
        }
        $sql .= "
			productReq.productRequestID,
			productReq.productStartTime,
			productReq.productEndTime,			
			productReq.productImage,
			productReq.productStatus,			
			productReq.productCreatedDate,
			productReq.productDefaultCurrency,
			productReqDet.productTitle,
			productReqOpt.productOptionRegularPrice,
			productReqOpt.productOptionProductPrice,			
			productTyp.productTypeID,
			productTyp.productTypeKey,
			productTypDet.productTypeName,
			busDet.businessName,
			productReqOpt.optionSKU,
			productReq.requestToProductID
			FROM 
				" . DB_PREFIX . "product_requests AS productReq 
			LEFT JOIN 
				" . DB_PREFIX . "product_request_details	AS productReqDet 
					ON (productReq.productRequestID = productReqDet.productRequestID AND productReqDet.languageID = '" . $currentLanguageID . "')
			LEFT JOIN
				" . DB_PREFIX . "product_types 			AS productTyp  
					ON productReq.productTypeID = productTyp.productTypeID
			LEFT JOIN 
				" . DB_PREFIX . "product_type_details 		AS productTypDet 
					ON (productTyp.productTypeID = productTypDet.productTypeID AND productTypDet.languageID = '" . $currentLanguageID . "') ";
        $sql .= "
			LEFT JOIN 
				" . DB_PREFIX . "business_details 		AS busDet 
					ON (productReq.businessID = busDet.businessID AND busDet.languageID = '" . $currentLanguageID . "') ";
        $sql .= "
			LEFT JOIN 
				" . DB_PREFIX . "product_request_options AS productReqOpt
					ON (productReq.productRequestID = productReqOpt.productRequestID
					AND productReqOpt.productOptionDefault='Yes')
			LEFT JOIN 
					" . DB_PREFIX . "product_request_options	AS productOptFull
					ON 	(
						productOptFull.productRequestID = productReq.productRequestID  AND productOptFull.productOptionStatus='Active'
						)			
					LEFT JOIN
						" . DB_PREFIX . "product_request_combination as proCom 
					ON 
					(proCom.productID=productReq.productRequestID AND proCom.status='A') 
			WHERE  1 ";
        if ($searchProductStatus) {
            $sql .= "AND productReq.productStatus = '" . $searchProductStatus . "' ";
        } else {
            $sql .= "AND productReq.productStatus = 'Pending' ";
        }
        if (isset($businessID)) {
            $sql .= "AND productReq.businessID = '" . $businessID . "' ";
        }
        if ($searchProductType) {
            $sql .= "AND productReq.productTypeID = '" . $searchProductType . "' ";
        }
        if ($searchProductKeyword != '') {
            $find                 = array(
                "_",
                "%"
            );
            $replace              = array(
                "\_",
                "\%"
            );
            $searchProductKeyword = str_replace($find, $replace, $searchProductKeyword);
            $sql .= "AND (
							productReqDet.productTitle  LIKE '%" . addslashes($searchProductKeyword) . "%'
						OR	productOptFull.optionSKU LIKE '%" . addslashes($searchProductKeyword) . "%'
						OR	proCom.combinationSKU LIKE '%" . addslashes($searchProductKeyword) . "%'
						) ";
        }
        if (isset($searchBusinessName) && $searchBusinessName != '') {
            $sql .= "AND busDet.businessName LIKE '%" . addslashes($searchBusinessName) . "%' ";
        }
        if ($searchProductFromDate) {
            $sql .= "AND DATE_FORMAT(productReq.productCreatedDate, '%Y-%m-%d') >= '" . $searchProductFromDate . "' ";
        }
        if ($searchProductToDate) {
            $sql .= "AND DATE_FORMAT(productReq.productCreatedDate, '%Y-%m-%d') <= '" . $searchProductToDate . "' ";
        }
        $sql .= " GROUP BY productReq.productRequestID ";
        if ($sortBy) {
            $sql .= " ORDER BY $sortBy ";
        }
        if ($orderBy) {
            $sql .= "$orderBy ";
        }
        if ($limitTo) {
            $sql .= "LIMIT " . $limitFrom . "," . $limitTo . " ";
        }
        //echo $sql;
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    //END OF FUNCTION	
    //FECTH DEAL DETAILS
    public function getProductRequestDetails($params) {
        extract($params);
        $currentLanguageID = $languageIDs['Current'];
        $sql               = "SELECT 
			productTyp.productTypeKey,productReq.*,productReqDet.*,productReqOpt.*,productReqOptDet.*,
			bus.*,timez.*,tax.*,productTypDet.*";
        $sql .= "
		FROM 
			`" . DB_PREFIX . "product_requests` productReq ";
        $sql .= " 
		LEFT JOIN 
			`" . DB_PREFIX . "product_request_details` productReqDet 
			 ON (productReq.productRequestID = productReqDet.productRequestID 									 
			 AND 
			 productReqDet.languageID = '" . $currentLanguageID . "')
		LEFT JOIN 
			`" . DB_PREFIX . "product_request_options` productReqOpt 
			ON (productReq.productRequestID = productReqOpt.productRequestID AND productReqOpt.productOptionDefault = 'Yes')
		LEFT JOIN 
			`" . DB_PREFIX . "product_request_option_details` productReqOptDet 
			ON (productReqOpt.productRequestOptionID = productReqOptDet.productRequestOptionID AND 
			productReqOptDet.languageID = '" . $currentLanguageID . "')";
        $sql .= " LEFT JOIN 
			`" . DB_PREFIX . "business` bus ON (productReq.`businessID`=bus.`businessID`)
		LEFT JOIN 
			`" . DB_PREFIX . "timezones` timez ON (productReq.`productTimeZone`=timez.`timeZoneID`)
		LEFT JOIN 
			" . DB_PREFIX . "tax_classes AS tax ON (tax.taxClassID = productReq.taxClassID)
		LEFT JOIN 
			" . DB_PREFIX . "product_types productTyp ON (productReq.productTypeID=productTyp.productTypeID) 
		LEFT JOIN 
			`" . DB_PREFIX . "product_type_details`productTypDet 
			ON (productReq.`productTypeID`=productTypDet.`productTypeID` AND productTypDet.languageID = '" . $currentLanguageID . "') 
		LEFT JOIN 
			" . DB_PREFIX . "currencies AS currencies 
			ON (currencies.currencyID=productReq.productDefaultCurrency)	
		WHERE 
			productReq.productRequestID	= '" . (int) $selectedProductID . "' limit 1";
        $result = $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
        return $result;
    }
    //FUNCTION TO CHECK DEAL REQUEST WITH LANGUAGE ID EXISTS
    function isProductRequestWithLanguageIDExists($languageID, $productRequestID) {
        $sql    = "SELECT 
						1 
					FROM 
						`" . DB_PREFIX . "product_request_details` 
					WHERE 
						`languageID` = '" . $languageID . "' AND `productRequestID` = '" . $productRequestID . "' limit 1";
        $result = $this->ObjDatabase->numberOfRecords($sql);
        if ($result)
            return true;
        else
            return false;
    }
    //END OF FUNCTION
    public function listProductReqOptions($languageIDs = NULL, $productID, $status = NULL, $default = NULL, $productOptionID = '') {
        $defaultLanguageID = $languageIDs['Default'];
        $currentLanguageID = $languageIDs['Current'];
        $sql               = "SELECT
					
			productOpt.productRequestOptionID as option_id,
			productOpt.productRequestOptionID as defaultOpion,
			productOpt.*";
        if ($languageIDs)
            $sql .= ",productOptDet.productOptionName,productOptDet.*";
        $sql .= " FROM
				" . DB_PREFIX . "product_request_options AS productOpt";
        if ($languageIDs) {
            $sql .= " LEFT JOIN
				" . DB_PREFIX . "product_request_option_details AS productOptDet ON
					productOpt.productRequestOptionID=productOptDet.productRequestOptionID
					AND productOptDet.languageID = '" . $currentLanguageID . "'";
        }
        $sql .= " WHERE
					productOpt.productRequestID='" . (int) $productID . "'";
        if ($default) {
            $sql .= " AND productOpt.productOptionDefault  = '" . $default . "'";
        }
        if ($status) {
            $sql .= " AND productOpt.productOptionStatus  = '" . $status . "'";
        } else {
            $sql .= " AND productOpt.productOptionStatus  != 'Delete'";
        }
        $sql .= "  ORDER BY
				productOpt.productRequestOptionID";
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    public function productRequestByLang($languageID, $productRequestID) {
        $sql    = "
		SELECT 
			productReqDet.productTitle,
			productReqDet.productFinePrint,
			productReqDet.productHighlights,
			productReqDet.productDescription													
			productReqDet.languageID
		FROM `" . DB_PREFIX . "product_request_details` as productReqDet
		WHERE  
			productReqDet.productRequestID = '" . $productRequestID . "' 
			AND productReqDet.languageID = '" . $languageID . "' LIMIT 1";
        $result = $this->ObjDatabase->readValue($sql);
        return $result;
    }
    //SAVING DEAL REQUESTS(ADD/EDIT)
    public function saveProductRequest($languageIDs, $POST, $businessID, $productRequestID = NULL) {
        $ObjProduct = new ProductModel();
        if ($productRequestID) {
            $languageID = $languageIDs['Current'];
        } else {
            $languageID = $languageIDs['Default'];
        }
        $productTypeID           = '1';
        $taxClassID              = $POST['taxClassID'];
        $brandID                 = $this->escape($_POST['brandID']);
        $productTimeZone         = $POST['productTimeZone'];
        $productStartTime        = (isset($POST['productStartTime']) && $POST['productStartTime'] != '') ? date("Y-m-d", strtotime($POST['productStartTime'])) : '';
        $productEndTime          = (isset($POST['productEndTime']) && $POST['productEndTime'] != '') ? date("Y-m-d", strtotime($POST['productEndTime'])) : '';
        $productMinBuyLimit      = $POST['productMinBuyLimit'];
        $productMaxBuyLimit      = ($POST['productMaxBuyLimit'] != '') ? $POST['productMaxBuyLimit'] : 'NULL';
        $productMinQntyReqToTipp = (isset($POST['productMinQntyReqToTipp'])) ? $POST['productMinQntyReqToTipp'] : '';
        $measurementLength       = $POST['measurementLength'];
        $measurementWeight       = $POST['measurementWeight'];
        $productQuantityNotifyAt = (!empty($POST['productQuantityNotifyAt'])) ? $POST['productQuantityNotifyAt'] : 1;
        $productShowNosBought    = (isset($POST['productShowNosBought'])) ? $POST['productShowNosBought'] : '';
        $productDefaultCurrency  = $POST['productDefaultCurrency'];
        $productImage            = $POST['productImage'];
        $inventoryTrackLevel     = $POST['InventoryTrackLevel'];
        $productStatus           = (isset($POST['productStatus'])) ? $POST['productStatus'] : '';
        $productMaxGiftBuy       = (isset($POST['productMaxGiftBuy']) && $POST['productMaxGiftBuy'] != '') ? $POST['productMaxGiftBuy'] : 'NULL';
        $productTitle            = $this->escape($POST['productTitle']);
        $productFinePrint        = (isset($POST['productFinePrint'])) ? $this->escape($POST['productFinePrint'], FALSE) : '';
        $productHighlights       = $this->escape($POST['productHighlights'], FALSE);
        $productDescription      = $this->escape($POST['productDescription'], FALSE);
        $productMetaTitle        = $this->escape($POST['productMetaTitle']);
        $productMetaDescription  = $this->escape($POST['productMetaDescription']);
        $productMetaKeywords     = $this->escape($POST['productMetaKeywords']);
        $searchTags              = $this->escape($POST['searchTags']);
        $productUrl              = $this->escape($POST['productUrl']);
        $taxPayableToBusiness    = (isset($POST['taxToBusiness'])) ? $POST['taxToBusiness'] : '';
        $outofStockStatus        = (isset($POST['outofStockStatus'])) ? $POST['outofStockStatus'] : '';
        $showCountTimer          = (isset($POST['showCountTimer'])) ? $this->escape($POST['showCountTimer']) : '';
        $attributeSetID          = (isset($POST['attributeSetID'])) ? $this->escape($POST['attributeSetID']) : '';
        $showQuantityAvailable   = $this->escape($POST['showQuantityAvailable']);
        $productReturnable       = (isset($POST['productReturnable'])) ? $POST['productReturnable'] : 'No';
        $productReturnPeriod     = $POST['returnPeriod'];
        if (isset($POST['enableMultipleOptions']) && $POST['enableMultipleOptions'] == 'Yes') {
            $enableMultipleOptions = 'Yes';
        } else {
            $enableMultipleOptions = 'No';
        }
        //All languages 
        $allLanguages = $languageIDs['AllList'];
        $businessID   = ($businessID > 0) ? $businessID : $POST['businessID'];
        if ($productRequestID == '') {
            $sql = "INSERT INTO `" . DB_PREFIX . "product_requests`(
                                `productTypeID`, 
                                `businessID`,				
				`brandID`,
				`attributeSetID`,
				`taxClassID`,
                                `productTimeZone`, 
                                `productStartTime`, 
				`productDefaultCurrency`,
				`measurementLength`,
				`measurementWeight`,
				`productQuantityNotifyAt`,
                                `productEndTime`, 
                                `productMinBuyLimit`, 
                                `productMaxBuyLimit`,
                                `productMaxGiftBuy`, 
                                `productMinQntyReqToTipp`,
				`multiOptionsAvailable`,					
                                `productShowNosBought`,                                
                                `productImage`,
                                `productStatus`, 
                                `productCreatedDate`,
				`showCountTimer`,
				`productUrl`,
				`showQuantityAvailable`,
				`productReturnable`,
				`productReturnPeriod`,
				`InventoryTrackLevel`
                                  ) 
                                  VALUES (
                                '" . $productTypeID . "', 
                                '" . $businessID . "',
				'" . $brandID . "',
				'" . $attributeSetID . "',
				'" . $taxClassID . "',
                                '" . $productTimeZone . "', 
                                '" . $productStartTime . "', 
				'" . $productDefaultCurrency . "',
                                '" . $measurementLength . "',
				'" . $measurementWeight . "',
				'" . $productQuantityNotifyAt . "',				
                                '" . $productEndTime . "', 
                                '" . $productMinBuyLimit . "', 
                                " . $productMaxBuyLimit . ",
                                " . $productMaxGiftBuy . ", 
                                '" . $productMinQntyReqToTipp . "', 
				'" . $enableMultipleOptions . "',									
                                '" . $productShowNosBought . "',                                
                                '" . $productImage . "',
                                'Pending', 
                                NOW(),
				'" . $showCountTimer . "',				
				'" . $productUrl . "',
				'" . $showQuantityAvailable . "',
				'" . $productReturnable . "',
				'" . $productReturnPeriod . "',
				'" . $inventoryTrackLevel . "'
                                   )";
            $this->ObjDatabase->setQuery($sql);
            $lastInsertProductID = $this->ObjDatabase->getInsertId();
            foreach ($allLanguages as $language) {
                $sql = "INSERT INTO `" . DB_PREFIX . "product_request_details` (
                                            `languageID`, 
                                            `productRequestID`, 
                                            `productTitle`,
                                            `productFinePrint`, 
                                            `productHighlights`, 
                                            `productDescription`,
					    `productMetaTitle`,
					`productMetaDescription`,
					`productMetaKeywords`,
					`searchTags`
                                         ) 
                                         VALUES
					( 
					'" . $language . "', 
					'" . $lastInsertProductID . "', 
					'" . $productTitle . "',                                             
					'" . $productFinePrint . "', 
					'" . $productHighlights . "', 
					'" . $productDescription . "',
					'" . $productMetaTitle . "',
					'" . $productMetaDescription . "',
					'" . $productMetaKeywords . "',
					'" . $searchTags . "'
                                        )";
                $this->ObjDatabase->setQuery($sql);
            }
            if ($productRequestID == '') {
                $productOptionCount = (isset($POST["productOptionCount"])) ? $POST["productOptionCount"] : '';
                $options            = $POST['productOptionsGroup'];
                $this->saveProductRequestOptions($languageIDs, $options, $lastInsertProductID, $enableMultipleOptions);
            }
            if (!empty($POST['productCategoryID'])) {
                $this->saveProductRequestToCategory($lastInsertProductID, $POST);
            }
            return $lastInsertProductID;
        } else {
            $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_requests` SET `productTypeID`='" . $productTypeID . "', `businessID`='" . $businessID . "',
						     `productTimeZone`='" . $productTimeZone . "', `productStartTime`='" . $productStartTime . "', `productEndTime`='" . $productEndTime . "', 
			`productDefaultCurrency`='" . $productDefaultCurrency . "',
			`brandID`='" . $brandID . "',
			`taxClassID`='" . $taxClassID . "',
			`measurementLength`='" . $measurementLength . "',
			`measurementWeight`='" . $measurementWeight . "',
			`productQuantityNotifyAt`='" . $productQuantityNotifyAt . "',
			`showQuantityAvailable`='" . $showQuantityAvailable . "',
			`multiOptionsAvailable`='" . $enableMultipleOptions . "',			
			`productMinBuyLimit`='" . $productMinBuyLimit . "',
			`productMaxBuyLimit`=" . $productMaxBuyLimit . ",
			`productMaxGiftBuy`=" . $productMaxGiftBuy . ",
			`productMinQntyReqToTipp`='" . $productMinQntyReqToTipp . "',
			`productShowNosBought`='" . $productShowNosBought . "',			
			`showCountTimer`='" . $showCountTimer . "',
			`InventoryTrackLevel`='" . $inventoryTrackLevel . "',
			`productImage`='" . $productImage . "',
			`productUrl`='" . $productUrl . "',
			`outofStockStatus`='" . $outofStockStatus . "',
			`productReturnable`='" . $productReturnable . "',
			`productReturnPeriod`='" . $productReturnPeriod . "'
			WHERE `productRequestID` = '" . $productRequestID . "'");
            $this->destroyProductrequestToCategory($productRequestID);
            if (!empty($POST['productCategoryID'])) {
                $this->saveProductRequestToCategory($productRequestID, $POST);
            }
            if ($this->isProductRequestWithLanguageIDExists($languageID, $productRequestID)) {
                $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_request_details` SET `productTitle`='" . $productTitle . "',
					     `productFinePrint`='" . $productFinePrint . "',
					     `productHighlights`='" . $productHighlights . "',
					     `productDescription`='" . $productDescription . "',`productMetaTitle`='" . $productMetaTitle . "',
						`productMetaDescription`='" . $productMetaDescription . "',
						`productMetaKeywords`='" . $productMetaKeywords . "',
						`searchTags`='" . $searchTags . "'
					     WHERE
					     `productRequestID` = '" . $productRequestID . "' AND `languageID`='" . $languageID . "'");
            } else {
                $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_request_details`
					     (`languageID`, `productRequestID`, `productTitle`,
					      `productFinePrint`,
					     `productHighlights`, `productDescription`,`productMetaTitle`,
						`productMetaDescription`,
						 `productMetaKeywords`,
						 `searchTags`
					     )
					     VALUES
			('" . $languageID . "', '" . $productRequestID . "', '" . $productTitle . "', '" . $productFinePrint . "', '" . $productHighlights . "', '" . $productDescription . "','" . $productMetaTitle . "',
			'" . $productMetaDescription . "',
			'" . $productMetaKeywords . "',
			'" . $searchTags . "')");
            }
            $productOptionCount = (isset($POST["productOptionCount"])) ? $POST["productOptionCount"] : '';
            $options            = $POST['productOptionsGroup'];
            $this->saveProductRequestOptions($languageIDs, $options, $productRequestID, $enableMultipleOptions);
            if ($enableMultipleOptions == 'Yes')
                $this->deleteExistCombo($productRequestID);
            return $productRequestID;
        }
    }
    //END OF FUNCTION
    //FUNCTION TO SAVE DEAL REQUEST OPTIONS
    public function saveProductRequestOptions($languageIDs, $options, $productRequestID, $enableMultipleOptions = 'No') {
        $languageID        = $languageIDs['Current'];
        $DefaultLanguageID = $languageIDs['Default'];
        $optionsToInsert   = array();
        $optionsToDelete   = array();
        $optionsToUpdate   = array();
        foreach ($options as $rowHash => $row) // Traverse through all posted options
            {
            $option_id    = (int) $row['option_id'];
            $option_count = (int) $row['realOptionCount'];
            if ($row['is_delete'] == 1) // Option is deleted
                {
                if ($row['option_id'] > -1) // Option already present in db. Delete it
                    {
                    $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_request_option_details` WHERE `productRequestOptionID`='" . $row['option_id'] . "'");
                    $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_request_options` WHERE `productRequestOptionID`='" . $row['option_id'] . "'");
                }
            } else {
                $productOptionRegularPrice = $this->escape($row['productOptionRegularPrice']);
                $optionSKU                 = $this->escape($row['optionSKU']);
                $optionBarCode             = $this->escape($row['optionBarCode']);
                $productOptionProductPrice = $this->escape($row['productOptionProductPrice']);
                $productOptionQuantity     = (int) $row['productOptionQuantity'];
                $productQuantityUnlimited  = ($row['productOptionQuantity'] == "") ? "1" : "0";
                $productOptionStatus       = $this->escape($row['productOptionStatus']);
                $packageWeight             = $this->escape($row['packageWeight']);
                $packageLength             = $this->escape($row['packageLength']);
                $packageWidth              = $this->escape($row['packageWidth']);
                $packageHeight             = $this->escape($row['packageHeight']);
                $sortOrder                 = $this->escape($row['productOptionImageSort']);
                $productOptionDefault      = (isset($row['defaultOpion'])) ? $this->escape($row['defaultOpion']) : '';
                if ($enableMultipleOptions != 'Yes') {
                    $productOptionName    = $this->escape($_POST['productTitle']);
                    $productOptionDefault = 'Yes';
                } else {
                    $productOptionName = $this->escape($row['productOptionName']);
                }
                if ($productOptionProductPrice == '') {
                    $productOptionProductPrice = $productOptionRegularPrice;
                }
                $productOptionDefault = ($productOptionDefault == "Yes") ? "Yes" : "No";
                if ($row['option_id'] > -1) // Option already present in db. Update it
                    {
                    $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_request_options`
                                               SET
							`optionSKU`='" . $optionSKU . "',
							`optionBarCode`='" . $optionBarCode . "',
							`productOptionRegularPrice`='" . $productOptionRegularPrice . "',
							`productOptionProductPrice`='" . $productOptionProductPrice . "', 
							`productOptionQuantity`='" . $productOptionQuantity . "',														
							`packageWeight`='" . $packageWeight . "',	
							`packageLength`='" . $packageLength . "',														
							`packageWidth`='" . $packageWidth . "',
							`packageHeight`='" . $packageHeight . "',
							`productQuantityUnlimited` = '" . $productQuantityUnlimited . "' ,
							`productOptionStatus`='" . $productOptionStatus . "',
							`productOptionDefault`='" . $productOptionDefault . "' 
                                                WHERE 
                                                    `productRequestOptionID` = '" . $option_id . "'");
                    $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_request_option_details` 
                                                          SET 
                                                            `productOptionName`='" . $productOptionName . "'
                                                          WHERE `productRequestOptionID`='" . $option_id . "' 
                                                          AND `languageID`='" . $languageID . "'");
                    $this->SaveProductRequestOptionImages($option_count, $_POST, $productRequestID, $option_id, $sortOrder);
                    $this->groupTierRequestPriceUpdate($row, $option_id);
                } else // New option. Insert it
                    {
                    $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_request_options` 
												 (`productRequestID`,
												 `optionSKU`,
												  `optionBarCode`,
												`productOptionRegularPrice`, 
												`productOptionProductPrice`,
												`productOptionQuantity`,
												`packageWeight`,
												 `packageLength`,
												 `packageWidth`,
												 `packageHeight`,
												`productQuantityUnlimited`,
												`productOptionStatus`,
												`productOptionDefault`) 
												 VALUES 
												 ('" . $productRequestID . "',
												 '" . $optionSKU . "',
												  '" . $optionBarCode . "',
												  '" . $productOptionRegularPrice . "', 
												  '" . $productOptionProductPrice . "',												 											 
												  '" . $productOptionQuantity . "',												
												  '" . $packageWeight . "',
												  '" . $packageLength . "',
												  '" . $packageWidth . "',
												  '" . $packageHeight . "',												  
												  '" . $productQuantityUnlimited . "', 
												  '" . $productOptionStatus . "',
												  '" . $productOptionDefault . "')");
                    $last_insert_productOptionID = $this->ObjDatabase->getInsertId();
                    foreach ($languageIDs['AllList'] as $langIds) {
                        $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_request_option_details` 
													 (`productRequestOptionID`, 
													  `languageID`, 
													  `productOptionName`													  
													 ) 
													 VALUES 
													 ('" . $last_insert_productOptionID . "', 
													  '" . $langIds . "', 
													  '" . $productOptionName . "'
													 
													 )");
                    }
                    $this->SaveProductRequestOptionImages($option_count, $_POST, $productRequestID, $last_insert_productOptionID, $sortOrder);
                    $this->groupTierRequestPriceUpdate($row, $last_insert_productOptionID);
                }
            }
        }
    }
    public function groupTierRequestPriceUpdate($row, $option_id) {
        if (!empty($row['group_price'])) {
            $groupPrice = array();
            foreach ($row['group_price'] as $group_price) {
                if ($group_price['specialPrice'] > 0) {
                    array_push($groupPrice, "('" . $option_id . "','" . $group_price['userGroupID'] . "','" . $group_price['specialPrice'] . "')");
                }
            }
            $sql = "
				DELETE FROM 
					`" . DB_PREFIX . "variant_request_group_price` 
				WHERE
					productOptionID = '" . $option_id . "'
			";
            $this->ObjDatabase->setQuery($sql);
            $sql = "
				INSERT INTO `" . DB_PREFIX . "variant_request_group_price`
					(
					`productOptionID`, 
					`userGroupID`, 
					`specialPrice`
					)
				VALUES
					" . implode(",", $groupPrice) . "
			";
            $this->ObjDatabase->setQuery($sql);
        }
        if (!empty($row['tier_price'])) {
            $groupPrice = array();
            foreach ($row['tier_price'] as $tier_price) {
                if ($tier_price['quantity'] > 0 && $tier_price['tierPrice'] > 0) {
                    $allGroups = 0;
                    if ($tier_price['userGroupID'] == '') {
                        $allGroups = 1;
                    }
                    array_push($groupPrice, "(
						'" . $option_id . "',
						'" . $tier_price['userGroupID'] . "',
						'" . $allGroups . "',
						'" . $tier_price['quantity'] . "',
						'" . $tier_price['tierPrice'] . "'
						)");
                }
            }
            $sql = "
				DELETE FROM 
					`" . DB_PREFIX . "variant_request_tier_price` 
				WHERE
					productOptionID = '" . $option_id . "'
			";
            $this->ObjDatabase->setQuery($sql);
            $sql = "
				INSERT INTO `" . DB_PREFIX . "variant_request_tier_price`
					(
					`productOptionID`, 
					`userGroupID`, 
					`allGroups`,
					`quantity`, 
					`tierPrice`
					)
				VALUES
					" . implode(",", $groupPrice) . "
			";
            $this->ObjDatabase->setQuery($sql);
        }
    }
    public function getOptionRequestUserGroupPrice($productOptionID) {
        $sql = "
				SELECT
					userGroupID,
					specialPrice
				FROM
					" . DB_PREFIX . "variant_request_group_price
				WHERE 
					productOptionID = '" . $productOptionID . "'
			";
        return $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
    }
    public function getOptionRequestTierPrice($productOptionID) {
        $sql = "
				SELECT
					userGroupID,
					quantity,
					allGroups,
					tierPrice
				FROM
					" . DB_PREFIX . "variant_request_tier_price 
				WHERE 
					productOptionID = '" . $productOptionID . "'
			";
        return $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
    }
    //END OF FUNCTION	
    public function SaveProductRequestOptionImages($option_count, $POST, $productID, $productOptionID, $sortOrder) {
        $ObjImage          = new ImageModel();
        $productImageCount = $POST["productOptionImageCount" . $option_count];
        if (!empty($sortOrder)) {
            $sortOrder = explode(",", $sortOrder);
        }
        for ($i = 1; $i <= $productImageCount; $i++) {
            if (is_array($sortOrder)) {
                $order = array_search($i, $sortOrder) + 1;
            } else {
                $order = $i;
            }
            $mediaID  = (isset($POST['hidmediaID_' . $option_count . '_' . $i])) ? $POST['hidmediaID_' . $option_count . '_' . $i] : '';
            $isDelete = (isset($POST['isdelete_' . $option_count . '_' . $i])) ? $POST['isdelete_' . $option_count . '_' . $i] : '';
            if ($mediaID) {
                if ($isDelete == 1) {
                    $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_request_media` WHERE `productMediaID`='" . $mediaID . "'  And  productMediaType='I' AND productObjectType='DO'");
                } else {
                    if (($POST["productOptionImage_" . $option_count . '_' . $i . "_temp"] == "") && ($POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"] == "")) {
                        $mediaFlag = 1;
                        $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_request_media` SET `productMediaPriority`='" . $order . "' WHERE  productMediaID='" . $mediaID . "'");
                    } else {
                        $mediaFlag = 0;
                    }
                }
            } else {
                $mediaFlag = 0;
            }
            if ($mediaFlag != 1 && $isDelete != 1) {
                $productImageType = $POST['productOptionImage_' . $option_count . '_' . $i];
                $productImage     = "";
                if ($productImageType) {
                    /*@ main image exist */
                    if ($POST["productOptionImage_" . $option_count . '_' . $i . "_temp"] == '' && $POST['productOptionImage_' . $option_count . '_' . $i] != '')
                        $productImage = $this->getImageName($productImageType);
                    else /*@ main image upload */ 
                        $productImage = $productImageType;
                    /*@ thumb exist,main uploads*/
                    if (($_POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"] == '') && ($_POST["productOptionImageThumb_" . $option_count . '_' . $i] != '')) {
                        $paramMedia['thumbFlag'] = 1;
                        $paramMedia['resImage']  = $_POST["productOptionImageThumb_" . $option_count . '_' . $i];
                    }
                }
                if ($productImageType == "productOptionImage_" . $option_count . '_' . $i || $productImage == "") {
                    continue;
                }
                if ($productImage) {
                    $paramMedia['mainImage_temp']  = $POST["productOptionImage_" . $option_count . '_' . $i . "_temp"];
                    $paramMedia['thumbImage_temp'] = $POST["productOptionImageThumb_" . $option_count . '_' . $i . "_temp"];
                    $paramMedia['mediaParam']      = $POST['dataResize'];
                    $paramMedia['mainImage']       = $productImage;
                    $paramMedia['destFolder']      = 'product';
                    $productImage                  = $this->generateRequestMedia($paramMedia);
                }
                if (!$mediaID) {
                    $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_request_media`
			(`productObjectID`,`productRequestID`,
			`productMedia` ,`productMediaType`,
			`productMediaPriority`,`productObjectType`)
			VALUES
			('" . $productOptionID . "','" . $productID . "',
			'" . $productImage . "','I','" . $order . "','DO')");
                } else {
                    $this->ObjDatabase->setQuery("UPDATE `" . DB_PREFIX . "product_request_media` SET `productMedia`='" . $productImage . "',`productMediaPriority`='" . $order . "' WHERE  productMediaID='" . $mediaID . "'");
                }
            }
        }
    }
    //FUNCTION TO SAVE DEAL REQUEST TO CATEGORY
    public function saveProductRequestToCategory($productID, $POST) {
        for ($z = 0; $z < count($POST['productCategoryID']); $z++) {
            $this->ObjDatabase->setQuery("INSERT INTO `" . DB_PREFIX . "product_request_to_category` 
		(`productID`, `productCategoryID`) VALUES ('" . $productID . "', '" . $POST['productCategoryID'][$z] . "')");
        }
    }
    public function destroyProductrequestToCategory($productID) {
        $sql    = "DELETE FROM  " . DB_PREFIX . "product_request_to_category WHERE `productID` =" . $productID;
        $result = $this->ObjDatabase->setQuery($sql);
        return $result;
    }
    public function listProductRequestTocategoryDetails($languageIDs, $productID = '') {
        $sql    = "SELECT 
			productReqToCat.*,
			productCatDet.productCategoryName 
		FROM 
			" . DB_PREFIX . "product_request_to_category AS productReqToCat  
		LEFT JOIN 
			" . DB_PREFIX . "product_categories AS productCat ON 
			productCat.productCategoryID=productReqToCat.productCategoryID AND				   													
			productCat.productCategoryStatus='Active'  
		LEFT JOIN " . DB_PREFIX . "product_category_details AS productCatDet ON 
			productReqToCat.productCategoryID=productCatDet.productCategoryID WHERE productID='" . $productID . "'
			AND productCatDet.languageID='" . $languageIDs['Current'] . "'";
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    // Get product req count for admin notification
    public function getProductRequestCount($status = '') {
        $sql    = "
						SELECT 
							COUNT(DISTINCT productReq.productID) AS productReqCount 
						FROM 
							" . DB_PREFIX . "products productReq
						WHERE
							productStatus='" . $status . "'";
        $result = $this->ObjDatabase->readValue($sql);
        return $result['productReqCount'];
    }
    //GET PRODUCT IMAGES
    public function listRequestOptionMedia($productOptionID) {
        $querySelectProductImages = "SELECT productMedia,productMediaID FROM `" . DB_PREFIX . "product_request_media` WHERE  productObjectID = '" . (int) $productOptionID . "' AND `productMediaType` = 'I' AND productObjectType='DO' ORDER BY productMediaPriority ASC";
        $resSelectProductImages   = $this->ObjDatabase->readValues($querySelectProductImages);
        return $resSelectProductImages;
    }
    //END OF FUNCTION
    /*---- Custom Option Section---->*/
    //list Custom Product Option
    public function listRequestCustomProductOption($languageIDs, $paramArray = array()) {
        $ObjCustom          = new CustomOptionModel();
        $currentLanguageID  = $languageIDs['Current'];
        $excludeVariant     = (isset($paramArray['excludeVariant'])) ? $this->escape($paramArray['excludeVariant']) : '';
        $variantInputs      = $ObjCustom->getMultiVariants();
        //Get params from paramArray
        $customOptionID     = (isset($paramArray['customOptionID'])) ? $this->escape($paramArray['customOptionID']) : '';
        $customOptionName   = (isset($paramArray['customOptionName'])) ? $this->escape($paramArray['customOptionName']) : '';
        $status             = (isset($paramArray['status'])) ? $this->escape($paramArray['status']) : '';
        $productRequestID   = (isset($paramArray['productRequestID'])) ? $this->escape($paramArray['productRequestID']) : '';
        $sqlSelectAttribute = "SELECT CO.customOptionID,COD.customOptionName,COD.validationMessage,CO.inputType,CO.status,COL.customOptionLinkID";
        $sqlSelectAttribute .= ",CO.*,
					COD.*";
        $sqlSelectAttribute .= " FROM " . DB_PREFIX . "product_request_custom_option_link  COL 
		LEFT JOIN " . DB_PREFIX . "product_request_custom_option CO ON (COL.customOptionID = CO.customOptionID)
		LEFT JOIN " . DB_PREFIX . "product_request_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 ($productRequestID != '') {
            $sqlSelectAttribute .= "  AND COL.productRequestID='" . $productRequestID . "'";
        }
        $sqlSelectAttribute .= " ORDER BY COL.sortOrder ASC";
        $resAtributeDetails = $this->ObjDatabase->readValues($sqlSelectAttribute);
        return $resAtributeDetails;
    }
    //Save Request Custom Option
    //Save Custom Attribute
    public function saveReqCustomOptions($languageIDs, $paramArray, $fileArray = array()) {
        $currentLanguageID    = $languageIDs['Current'];
        $ObjImage             = new ImageModel();
        $ObjCustom            = new CustomOptionModel();
        $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   = $this->escape($paramArray['attrOptionAddCount']);
        $status               = $this->escape($paramArray['status']);
        if ($inputType == 'select') {
            $includeInCombination = ((isset($paramArray['includeInCombination'])) && trim($paramArray['includeInCombination']) == 'Yes') ? 'Yes' : 'No';
        } else
            $includeInCombination = "No";
        $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 ($productRequestID > 0) {
            //Save Attribute 
            if ($customOptionID > 0) //Update
                {
                //Options table
                $this->ObjDatabase->setQuery("UPDATE
			" . DB_PREFIX . "product_request_custom_option
			SET 	
				 inputType='" . $inputType . "',
				 validateRule='" . $validateRule . "',
				 include_in_combination='" . $includeInCombination . "',
				 priceDiff='" . $priceDiff . "',
				 priceDiffType='" . $priceDiffType . "',
				 status = '" . $status . "' 
			WHERE customOptionID = '" . $customOptionID . "'");
                //Options Detail									  
                $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_request_custom_option_details
			SET 	customOptionName='" . $customOptionName . "',
				 validationMessage='" . $validationMessage . "',
				 helpText = '" . $helpText . "' 
			WHERE customOptionID = '" . $customOptionID . "' AND languageID ='" . $currentLanguageID . "'");
            } else //Insert
                {
                //Options table
                $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_request_custom_option 
			(
			inputType,
			validateRule,
			include_in_combination,
			priceDiff,
			priceDiffType,
			status
			) 
			VALUES 
			( 
			'" . $inputType . "',
			'" . $validateRule . "',
			'" . $includeInCombination . "',
			'" . $priceDiff . "',
			'" . $priceDiffType . "',
			'" . $status . "')");
                $customOptionID      = $this->ObjDatabase->getInsertId();
                //Options Detail
                $insertAttrDetailSql = "INSERT INTO " . DB_PREFIX . "product_request_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_request_custom_option_link 
			(									   
			customOptionID,
			productRequestID
			)
			VALUES
			( 
			" . $customOptionID . ",		
			" . $productRequestID . "
			)";
                $insertCustomAttrDet = $this->ObjDatabase->setQuery($sqlImportAsLink);
            }
            //Save 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_request_custom_option_variant WHERE customOptionVariantID='" . $customOptionVariantID . "'");
                            $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "product_request_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']);
                        $isDefault         = (isset($row['isDefault'])) ? $this->escape($row['isDefault']) : '';
                        $hidThumb          = (isset($row['hidThumb'])) ? "public/" . $this->escape($row['hidThumb']) : '';
                        $variantThumbImage = '';
                        //option image section
                        if ($inputType == 'select') {
                            if ($includeInCombination == 'Yes') {
                                $priceDiff      = 0;
                                $priceDiffType  = 'N';
                                $weightDiff     = 0;
                                $weightDiffType = 'N';
                            }
                            $variantThumbImageType = $paramArray['OptionVariantThumb_' . $rowKey];
                            if ($paramArray["OptionVariantThumb_" . $rowKey . "_temp"] != '') {
                                $variantThumbImage = "";
                                if ($variantThumbImageType)
                                    $variantThumbImage = $variantThumbImageType;
                                if ($variantThumbImage) {
                                    $ObjImage->copy_file($paramArray["OptionVariantThumb_" . $rowKey . "_temp"], "/" . __UPLOADS_FOLDER . "catalog-request/custom-option-variant/" . $variantThumbImage);
                                }
                                if ($customOptionVariantID > -1) {
                                    $this->deleteVariantImage($customOptionVariantID);
                                }
                            } else {
                                if ($variantThumbImageType != '')
                                    $variantThumbImage = $variantThumbImageType;
                                else
                                    $variantThumbImage = '';
                            }
                        }
                        //option image section
                        if ($customOptionVariantID > -1) // Option already present in db. Update it
                            {
                            //Attribute options
                            $this->ObjDatabase->setQuery("UPDATE " . DB_PREFIX . "product_request_custom_option_variant
					SET 	priceDiff='" . $priceDiff . "',
					      variantThumbImage='" . $variantThumbImage . "',
						      priceDiffType='" . $priceDiffType . "',
						      weightDiff='" . $weightDiff . "',
						      weightDiffType = '" . $weightDiffType . "',
						      sortOrder = '" . $sortOrder . "',
						      isDefault = '" . $isDefault . "' 
					WHERE customOptionVariantID = '" . $customOptionVariantID . "'");
                            //Options option Detail
                            $attrOptionDetailSql = "UPDATE " . DB_PREFIX . "product_request_custom_option_variant_details
					SET 	value='" . $valueTitle . "'";
                            $attrOptionDetailSql .= " WHERE customOptionVariantID = '" . $customOptionVariantID . "' AND languageID ='" . $currentLanguageID . "'";
                            $this->ObjDatabase->setQuery($attrOptionDetailSql);
                        } else // New option. Insert it
                            {
                            //options
                            $this->ObjDatabase->setQuery("INSERT INTO " . DB_PREFIX . "product_request_custom_option_variant 
			(customOptionID,
			variantThumbImage,
			 priceDiff, 
			 priceDiffType, 
			 weightDiff,
			 weightDiffType,
			 sortOrder,
			 isDefault
			) 
			VALUES 
			('" . $customOptionID . "',
			'" . $variantThumbImage . "', 
			 '" . $priceDiff . "', 
			 '" . $priceDiffType . "', 
			 '" . $weightDiff . "',
			 '" . $weightDiffType . "',															   
			 '" . $sortOrder . "',
			 '" . $isDefault . "')");
                            $customOptionVariantID          = $this->ObjDatabase->getInsertId();
                            //custom option Detail
                            $insertAttrOptionDetailSql      = "INSERT INTO " . DB_PREFIX . "product_request_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 ($inputType == 'file') {
                $validateRule = '';
                if ($validateRuleRequired == 'Yes') {
                    $validateRule = 'required~*';
                }
                if ($maxFileSize != '') {
                    $validateRule .= "checkFileSize->" . $maxFileSize . "~*";
                }
                $validateRule .= "isValidFileExtension";
                if ($allowedExtensions != '')
                    $validateRule .= "->" . $allowedExtensions;
            }
            $ObjCustom->updateOptionRule($customOptionID, $validateRule);
        }
    }
    //List Request Option Variants
    public function listRequestOptionVariant($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']) : '';
        $resAtributeOptionDetails = array();
        if ($customOptionID > 0) {
            $sqlSelectAttributeOptions = "SELECT OV.*,CO.inputType as inputType,DM.productMedia,OVD.value as varValue,
		OVD.*	 
		FROM
			" . DB_PREFIX . "product_request_custom_option_variant OV
		LEFT JOIN
			" . DB_PREFIX . "product_request_custom_option_variant_details OVD ON 
		(OV.customOptionVariantID=OVD.customOptionVariantID
		AND 
		IF(EXISTS (SELECT customOptionVariantDetailsID FROM " . DB_PREFIX . "product_request_custom_option_variant_details WHERE customOptionVariantID = OV.customOptionVariantID 
		AND languageID='" . $currentLanguageID . "'), 
		OVD.languageID = '" . $currentLanguageID . "',
		IF(EXISTS (SELECT customOptionVariantDetailsID FROM " . DB_PREFIX . "product_request_custom_option_variant_details WHERE customOptionVariantID = OV.customOptionVariantID 
		AND languageID='" . $defultLanguageID . "'),OVD.languageID = '" . $defultLanguageID . "', 
		OVD.languageID ='1')))
		LEFT JOIN " . DB_PREFIX . "product_request_custom_option CO ON 
		(OV.customOptionID=CO.customOptionID)
		LEFT JOIN " . DB_PREFIX . "product_request_media DM ON 
		(OV.customOptionVariantID=DM.productObjectID AND DM.productObjectType='COV')	
		WHERE OV.customOptionID='" . $customOptionID . "'
		";
            if ($customOptionVariantID != '') {
                $sqlSelectAttributeOptions .= " AND OV.customOptionVariantID='" . $customOptionVariantID . "'";
            }
            $sqlSelectAttributeOptions .= " GROUP BY OV.customOptionVariantID
						ORDER BY OV.sortOrder ASC";
            $resAtributeOptionDetails = $this->ObjDatabase->readValues($sqlSelectAttributeOptions);
        }
        return $resAtributeOptionDetails;
    }
    public function importGlobalOptionsForRequest($languageIDs, $paramArray) {
        $defultLanguageID      = $languageIDs['Default'];
        $currentLanguageID     = $languageIDs['Current'];
        $AsLinkcustomOptionIDs = array();
        $ObjImage              = new ImageModel();
        //Get params from paramArray
        $customOptionIDs       = $this->escape($paramArray['customOptionIDs']);
        $productRequestID      = $this->escape($paramArray['productRequestID']) <= 0 ? 0 : $this->escape($paramArray['productRequestID']);
        if ($customOptionIDs && ($productRequestID > 0)) {
            $customOptionIDs = explode(",", $customOptionIDs);
            foreach ($customOptionIDs as $customOptionID) {
                //option Table Import
                $sqlImportAttribute  = "INSERT INTO " . DB_PREFIX . "product_request_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 . "'";
                $insertCustomAttr    = $this->ObjDatabase->setQuery($sqlImportAttribute);
                $custominsertID      = $this->ObjDatabase->getInsertId();
                $sqlImportlinking    = "INSERT INTO " . DB_PREFIX . "product_request_custom_option_link 
									  (									   
									   customOptionID,
									   productRequestID									   
									  )
								 	 VALUES( 
									  " . $custominsertID . ",		
									  " . $productRequestID . "
										)";
                $insertImportlinking = $this->ObjDatabase->setQuery($sqlImportlinking);
                //Option Details Table Import
                $sqlImportoptionDet  = "INSERT INTO " . DB_PREFIX . "product_request_custom_option_details
									  (
									   customOptionID,
									   languageID,
									   customOptionName,
									   validationMessage,
									   helpText
									  )
								 	  SELECT 
										" . $custominsertID . ",		
										languageID,
										customOptionName,
										validationMessage,
										helpText								  
								  	  FROM " . DB_PREFIX . "product_custom_option_details WHERE customOptionID = '" . $customOptionID . "'";
                $insertCustomAttrDet = $this->ObjDatabase->setQuery($sqlImportoptionDet);
                $inputTypesql        = "SELECT 									  
						    inputType									
																			  
						FROM
						    " . DB_PREFIX . "product_custom_option
						WHERE
						    customOptionID = '" . $customOptionID . "'";
                $inputType_arry      = $this->ObjDatabase->readValue($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->readValues($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->readValue($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-request/custom-option-variant/" . $thumbImage);
                            } else
                                $thumbImage = '';
                            //Option Variant Table Import
                            $sqlImportAttributeOptions = "INSERT INTO " . DB_PREFIX . "product_request_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 . "'";
                            $insertCustomAttrOptions   = $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->readValue($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_request_custom_option_variant_details
											(
											 customOptionVariantID,
											 languageID,
											 value
											)
											SELECT 
											 " . $customOptionVariantID . ",		
											 languageID,
											 value	
											FROM " . DB_PREFIX . "product_custom_option_variant_details WHERE customOptionVariantID IN (" . $currentValueID . ")";
                                    $insertCustomAttrOptDet   = $this->ObjDatabase->setQuery($sqlImportAttributeOptDet);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    public function getRequestCustomOptionVariants($languageIDs, $customOptionID) {
        $currentLanguageID = $languageIDs['Current'];
        if ($customOptionID > 0) {
            $sql    = "SELECT 
						proCusOptVar.customOptionVariantID,
						proCusOptVarDet.value,
						proCusOptVar.customOptionID, 
						proCusOptVar.variantThumbImage, 
						proCusOptVar.priceDiff, 
						proCusOptVar.priceDiffType, 
						proCusOptVar.weightDiff, 
						proCusOptVar.weightDiffType, 
						proCusOptVar.sortOrder,
						proCusOptVar.isDefault,
						proCusOptVar.status						 
					FROM 
						" . DB_PREFIX . "product_request_custom_option_variant as proCusOptVar 
					LEFT JOIN 
						" . DB_PREFIX . "product_request_custom_option_variant_details as proCusOptVarDet 
						ON proCusOptVar.customOptionVariantID = proCusOptVarDet.customOptionVariantID 
						AND proCusOptVarDet.languageID = " . (int) $currentLanguageID . " 
					WHERE 
						proCusOptVar.customOptionID =" . (int) $customOptionID . "   
					ORDER BY 
						proCusOptVar.sortOrder, 
						proCusOptVar.customOptionVariantID";
            $result = $this->ObjDatabase->readValues($sql);
            return $result;
        }
    }
    public function getProductRequestCombination($productID, $view = "No", $status = 'A', $languageIDs = '') {
        $currentLanguageID = $languageIDs['Current'];
        $sql               = "SELECT 	proCom.combination,
		proCom.combinationHash,
		proCom.combinationHeight,
		proCom.combinationID,
		proCom.combinationLength,
		proCom.combinationPrice,
		proCom.combinationPriceDiffType,
		proCom.combinationSKU,
		proCom.combinationWeight,
		proCom.combinationWeightDiffType,
		proCom.combinationWidth,		
		proCom.status,
		IF(proCom.combinationQty = '',1,0) as combinationQtyUnlimited,
		CAST(IFNULL(proCom.combinationQty,0) AS UNSIGNED) as combinationQty
		FROM 		
		" . DB_PREFIX . "product_request_combination as proCom 							
		WHERE 
		proCom.productID =" . (int) $productID;
        if ($status == 'A') {
            $sql .= " AND proCom.status='A'";
        } else {
            $sql .= " AND proCom.status!='D'";
        }
        if ($view == 'Yes') {
            $sql .= " ORDER BY proCom.combinationID DESC";
        }
        $result = $this->ObjDatabase->readValues($sql);
        if (count($result) > 0) {
            return $result;
        } else {
            return array();
        }
    }
    //To get oombination details	
    public function getRequestCombinationVariants($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_request_custom_option_variant as proCusOptVar 
			LEFT JOIN 
				" . DB_PREFIX . "product_request_custom_option_variant_details as proCusOptVarDet 
				ON proCusOptVar.customOptionVariantID = proCusOptVarDet.customOptionVariantID 
				AND proCusOptVarDet.languageID = " . (int) $currentLanguageID . "
			LEFT JOIN 
				" . DB_PREFIX . "product_request_custom_option_details as proCusOptDet 
				ON proCusOptVar.customOptionID = proCusOptDet.customOptionID 
				AND proCusOptDet.languageID = " . (int) $currentLanguageID . "	
			WHERE 
				proCusOptVar.customOptionVariantID IN (" . $variants . ")";
            $result   = $this->ObjDatabase->readValues($sql);
            $i        = 0;
            foreach ($result as $resvariants) {
                $varArray[$i]['customOptionName'] = $resvariants['customOptionName'];
                $varArray[$i]['variantName']      = $resvariants['value'];
                $varArray[$i]['variantID']        = $resvariants['customOptionVariantID'];
                $i++;
            }
            return $varArray;
        }
    }
    public function getProductRequestCombinationByID($comboID) {
        $sql    = "SELECT 
				 proCom.* ,productMedia,proCom.status as Combstatus
			FROM 
				
				" . DB_PREFIX . "product_request_combination as proCom 			
			LEFT JOIN 
				" . DB_PREFIX . "product_request_media as productMed 
				ON (proCom.combinationID = productMed.productObjectID
				AND productMed.productObjectType='C')
			WHERE 
				proCom.combinationID =" . (int) $comboID . ";";
        $result = $this->ObjDatabase->readValue($sql);
        return $result;
    }
    public function getProductRequestOptionsDetails($languageIDs, $productID) {
        $defaultLanguageID = $languageIDs['Default'];
        $currentLanguageID = $languageIDs['Current'];
        $sql               = "
		SELECT
			productOpt.productRequestOptionID as productOptionID,productOptDet.productOptionName,productOpt.*,productOptDet.*
		FROM
			" . DB_PREFIX . "product_request_options productOpt,
			" . DB_PREFIX . "product_request_option_details productOptDet
		WHERE
			productOpt.productRequestOptionID=productOptDet.productRequestOptionID
		AND
			languageID=
			(
			SELECT CASE
			WHEN
			(
			SELECT EXISTS
			(
			SELECT
			*
			FROM
			" . DB_PREFIX . "product_request_options
			WHERE
			productRequestOptionID=productOpt.productRequestOptionID
			AND
			languageID='" . $currentLanguageID . "'
			)
			)
			THEN
			'" . $currentLanguageID . "'
			ELSE
			'" . $currentLanguageID . "'
			END
			)
			AND
			productRequestID='" . $productID . "'
			AND
			productOptionStatus='Active' ";
        return $this->ObjDatabase->readValues($sql);
    }
    function getRequestComboImage($combinationID) {
        $sql    = "SELECT
		productMedia
		FROM
		" . DB_PREFIX . "product_request_media
		WHERE
		productObjectID = '" . $combinationID . "' AND  productObjectType='C'";
        $result = $this->ObjDatabase->readValue($sql);
        return $result;
    }
    function generateRequestMedia($MediaArry) {
        $ObjImage        = new ImageModel();
        $destination     = $MediaArry['destFolder'];
        $Image           = $MediaArry['mainImage'];
        $info            = pathinfo($Image);
        $dirs            = basename($Image, '.' . $info['extension']);
        $mainDir         = strtolower($dirs['0']);
        $subDir          = (!empty($dirs['1'])) ? strtolower($dirs['1']) : "";
        $mainImage_temp  = $MediaArry['mainImage_temp'];
        $thumbImage_temp = $MediaArry['thumbImage_temp'];
        $resImage        = isset($MediaArry['resImage']) ? $MediaArry['resImage'] : '';
        $thumbFlag       = isset($MediaArry['thumbFlag']) ? $MediaArry['thumbFlag'] : 0;
        $Image           = preg_replace('/\s+/', '-', $Image);
        $dest_image      = (!empty($subDir) && $subDir != "_") ? $mainDir . "/" . $subDir . "/" . $Image : $mainDir . "/" . $Image;
        $upload_images   = $this->getSettingValue('site_settings', 'upload_images_to');
        if ($upload_images == 'filesystem') {
            $dirLevel1              = __CORE_PUBLIC_UPLOADS_PATH . "catalog-request/" . $destination . "/large/" . $mainDir;
            $dirLevel2              = __CORE_PUBLIC_UPLOADS_PATH . "catalog-request/" . $destination . "/large/" . $mainDir . "/" . $subDir;
            $dirLevel2_preview_main = __CORE_PUBLIC_UPLOADS_PATH . "catalog-request/" . $destination . "/preview-main/" . $mainDir . "/" . $subDir;
            if (file_exists($dirLevel2) && is_dir($dirLevel2)) {
            } elseif (file_exists($dirLevel1) && is_dir($dirLevel1)) {
                mkdir($dirLevel2, 0777);
                mkdir($dirLevel2_preview_main, 0777);
            } else {
                mkdir($dirLevel2, 0777, TRUE);
                mkdir($dirLevel2_preview_main, 0777, TRUE);
            }
        }
        if ($thumbImage_temp != '') {
            $ObjImage->copy_file($thumbImage_temp, '/' . __UPLOADS_FOLDER . 'catalog-request/' . $destination . '/preview-main/' . $dest_image);
            @unlink($thumbImage_temp);
        } elseif ($mainImage_temp != '') {
            // @main changes:preview same 
            if ($mainImage_temp != '' && $thumbFlag == 1) {
                if ($upload_images == 'filesystem') {
                    $ObjImage->copy_file(__CORE_PUBLIC_PATH . '/' . __UPLOADS_FOLDER . 'catalog-request/' . $destination . '/preview-main/' . $resImage, '/' . __UPLOADS_FOLDER . 'catalog-request/' . $destination . '/preview-main/' . $dest_image);
                    $this->unlinkImages($resImage, $destination);
                } else {
                    $tempImg = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog-request/' . $destination . '/preview-main/' . $resImage);
                    $ObjImage->copy_file(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg, '/' . __UPLOADS_FOLDER . 'catalog-request/' . $destination . '/preview-main/' . $dest_image);
                    @unlink(__DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'temp/' . $tempImg);
                }
                // give unlink
            }
        }
        if ($mainImage_temp != '') {
            $ObjImage->copy_file($mainImage_temp, '/' . __UPLOADS_FOLDER . 'catalog-request/' . $destination . '/large/' . $dest_image);
            @unlink($mainImage_temp);
        }
        return $dest_image;
    }
    public function deleteVariantImage($customOptionVariantID) {
        $ObjImage            = new ImageModel();
        $variantmainImagesql = "SELECT 									  
			variantThumbImage									
			
			FROM
			" . DB_PREFIX . "product_request_custom_option_variant
			WHERE
			customOptionVariantID = '" . $customOptionVariantID . "'";
        $variantthumb_arry   = $this->ObjDatabase->readValue($variantmainImagesql);
        if ($variantthumb_arry['variantThumbImage']) {
            $ObjImage->unlinkImage(__UPLOADS_FOLDER . "catalog-request/custom-option-variant/" . $variantthumb_arry['variantThumbImage']);
        }
    }
    function get_default_optionprice($productID) {
        $sql   = "SELECT productOptionRegularPrice as Price,productOptionProductPrice as listPrice FROM " . DB_PREFIX . "product_request_options WHERE productOptionDefault='Yes' AND productRequestID ='" . $productID . "'";
        $price = $this->ObjDatabase->readValue($sql);
        return $price['listPrice'];
    }
    function get_default_option_details($productID) {
        $sql = "SELECT optionSKU as sku FROM " . DB_PREFIX . "product_request_options WHERE productOptionDefault='Yes' AND productRequestID ='" . $productID . "'";
        $sku = $this->ObjDatabase->readValue($sql);
        return $sku['sku'];
    }
    function get_request_langIDs($productRequestID) {
        $sql     = "SELECT languageID FROM " . DB_PREFIX . "product_request_details WHERE  productRequestID ='" . $productRequestID . "'";
        $langIDs = $this->ObjDatabase->readValues($sql);
        foreach ($langIDs as $lan) {
            $lang[] = $lan['languageID'];
        }
        return $lang;
    }
    function get_request_Custom_langIDs($customOptionID) {
        $sql     = "SELECT languageID FROM " . DB_PREFIX . "product_request_custom_option_details WHERE  customOptionID ='" . $customOptionID . "'";
        $langIDs = $this->ObjDatabase->readValues($sql);
        foreach ($langIDs as $lan) {
            $lang[] = $lan['languageID'];
        }
        return $lang;
    }
    function get_request_attr_langIDs($attrValueID) {
        $sql     = "SELECT languageID FROM " . DB_PREFIX . "product_request_attribute_value_details WHERE  attrValueID ='" . $attrValueID . "'";
        $langIDs = $this->ObjDatabase->readValues($sql);
        foreach ($langIDs as $lan) {
            $lang[] = $lan['languageID'];
        }
        return $lang;
    }
    public function deleteExistCombo($productID) {
        $this->ObjDatabase->setQuery("Update " . DB_PREFIX . "product_request_combination SET `status`='D' WHERE productID='" . $productID . "'");
        $this->ObjDatabase->setQuery("DELETE FROM `" . DB_PREFIX . "product_request_media` WHERE productRequestID='" . $productID . "' AND  productObjectType='C'");
    }
    public function getImageName($img_file) {
        $info      = pathinfo($img_file);
        $file_name = basename($img_file, '.' . $info['extension']);
        return $file = $file_name . "." . $info['extension'];
    }
    public function saveProductLinkBuybox($languageIDs,$POST,$pid){ 
           
            $buyboxproductID           = $POST['buyboxproductID'];
            $productMinBuyLimit        = $POST['productMinBuyLimit'];
            $productOptionMRP          = $POST['productOptionMRP'];
            $productMaxBuyLimit        = (!empty($POST['productMaxBuyLimit']))? $POST['productMaxBuyLimit'] : 'NULL';
            $productQuantityNotifyAt   = (!empty($POST['productQuantityNotifyAt']))? $POST['productQuantityNotifyAt'] : 1 ;
            $showQuantityAvailable     = $this->escape($POST['showQuantityAvailable']);
            $sqlUpdateProducts         = " UPDATE 
                                                    `".DB_PREFIX."product_requests` 
                                         SET 
                                                    `productMinBuyLimit`='".$productMinBuyLimit."',
                                                    `productMaxBuyLimit`=".$productMaxBuyLimit.",
                                                    `productQuantityNotifyAt`='".$productQuantityNotifyAt."',
                                                    `showQuantityAvailable`='".$showQuantityAvailable."' ";
            $sqlUpdateProducts	.=	" WHERE `productRequestID` = '".$pid."'";	
            $this->ObjDatabase->setQuery($sqlUpdateProducts);
            //
            $data = $this->ObjDatabase->readValues("SELECT productTitle,languageID FROM `".DB_PREFIX."product_details` WHERE productID =".$buyboxproductID,MYSQLI_ASSOC);
            foreach ($data as $v) {
                //if ($v['languageID'] == 'CART_LANGUAGE') {
                        $orig_name = $this->escape($v['productTitle']);
                        $this->ObjDatabase->setQuery("
                                                    UPDATE 
                                                                    `".DB_PREFIX."product_request_details` 
                                                    SET 
                                                                    `productTitle`='".$orig_name."' 
                                                    WHERE 
                                                                    `productRequestID` = '".$pid."' AND `languageID`='".$v['languageID']."'");
                //}
            }
            //
            $options    = isset($POST['productOptionsGroup'])?$POST['productOptionsGroup']:'';
            $data1 = $this->ObjDatabase->readValues("SELECT productRequestOptionID FROM `".DB_PREFIX."product_request_options` WHERE productlRequestID=".$pid,MYSQLI_ASSOC);
            $i = 1;
            foreach ($data1 as $v) {
                if($options[$i]['productOptionQuantity']=="")
                $productQuantityUnlimited 	= "1";
                else
                $productQuantityUnlimited 	= "0";
                // Product option update 
                $productOptionID = $v['productRequestOptionID'];
                $this->ObjDatabase->setQuery("
                                    UPDATE 
                                                    `".DB_PREFIX."product_request_options` 
                                    SET 
                                                `productOptionRegularPrice`='".$options[$i]['productOptionRegularPrice']."',
                                                `optionSKU`='".$options[$i]['optionSKU']."',
                                                `optionBarCode`='".$options[$i]['optionBarCode']."',
                                                `productOptionProductPrice`='".$options[$i]['productOptionProductPrice']."',
                                                `productOptionQuantity`='".$options[$i]['productOptionQuantity']."',
                                                `productQuantityUnlimited` = '".$productQuantityUnlimited."' 
                                    WHERE 
                                                `productRequestOptionID` = '".$productOptionID."' ");
                // Product option details update 
                $this->ObjDatabase->setQuery("UPDATE `".DB_PREFIX."product_request_option_details` 
                                            SET 
                                                `productOptionName`='".$orig_name."'
                                            WHERE 
                                                `productRequestOptionID`='".$productOptionID."'");
                $i++;
            }
        }
}

