<?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: ProductController.php, v 1.0 2011/06/14 20:52:11
//
class ProductController extends Controller {
    //LIST DEAL WITH SEARCH
    public function indexAction() {
        $ObjProduct             = new ProductModel();
        $ObjProductList         = new ProductListModel(); 
        $ObjProductCategory     = new ProductCategoryModel();
        $ObjCustomOption        = new CustomOptionModel();
        $ObjBrand               = new BrandModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $settingsDateFormat     = $date_format = $this->getSettingValue('site_settings', 'date_format');
        $time_format            = $this->getSettingValue('site_settings', 'time_format');
        $link                   = '';
        
        $resCategories = $ObjProductCategory->listProductCategoryItems($languageIDs, 0);
        if (is_array($resCategories))
            array_shift($resCategories);
        $searchProductID           = $this->getRequestValue("key");
        $searchProductName         = $this->decodeUrlString($this->getRequestValue("name"));
        $searchProductBusinessType = $this->getRequestValue("btype");
        $searchProductBusinessName = $this->decodeUrlString($this->getRequestValue("bname"));
        $searchProductCategory     = $this->getRequestValue("category");
        $brandID                   = $this->getRequestValue("brandID");
        $searchProductCategories   = explode(":", $searchProductCategory);
        $searchProductFromDate     = $this->urlDate($this->getRequestValue("from"), 'get', $settingsDateFormat);
        $searchProductToDate       = $this->urlDate($this->getRequestValue("to"), 'get', $settingsDateFormat);
        $sortByOption              = $this->getRequestValue("sortby");
        $sortByOrder               = $this->getRequestValue("orderby");
        $productStatus             = $this->getRequestValue("dstatus");
        $searchPriceFrom           = $this->decodeUrlString($this->getRequestValue("pricefrom"));
        $searchPriceUpto           = $this->decodeUrlString($this->getRequestValue("priceupto"));
        $searchDiscountFrom        = $this->decodeUrlString($this->getRequestValue("discountfrom"));
        $searchDiscountTo          = $this->decodeUrlString($this->getRequestValue("discountto"));
        $searchGlobalKeyword       = $this->getRequestValue("gkeyword");
        $searchQuantityBelow       = $this->getRequestValue("searchQuantityBelow");
        $searchInventory           = $this->getRequestValue("inventory");
        $searchType                = $this->getRequestValue("sType");
        if (isset($searchStatus) && $searchStatus != '') {
            $link .= "status/" . $searchStatus . "/";
        }
        if ($searchProductID > 0) {
            $link .= "key/" . $searchProductID . "/";
        }
        if ($searchProductName != '') {
            $link .= "name/" . $this->encodeUrlString($searchProductName) . "/";
        }
        if ($searchProductBusinessType > 0) {
            $link .= "btype/" . $searchProductBusinessType . "/";
        }
        if ($brandID > 0) {
            $link .= "brandID/" . $brandID . "/";
        }
        if ($searchProductBusinessName != '') {
            $link .= "bname/" . $this->encodeUrlString($searchProductBusinessName) . "/";
        }
        if (isset($searchProductCities) && $searchProductCities != '') {
            $link .= "city/" . $searchProductCities . "/";
        }
        if ($searchProductCategory) {
            $link .= "category/" . $searchProductCategory . "/";
        }
        if ($searchProductFromDate) {
            $link .= "from/" . $this->urlDate($searchProductFromDate, 'set', $settingsDateFormat) . "/";
        }
        if ($searchProductToDate) {
            $link .= "to/" . $this->urlDate($searchProductToDate, 'set', $settingsDateFormat) . "/";
        }
        if ($productStatus) {
            $link .= "dstatus/" . $productStatus . "/";
        }
        if (isset($productCurrency) && $productCurrency != '') {
            $link .= "currency/" . $productCurrency . "/";
        }
        if ($searchPriceFrom) {
            $link .= "pricefrom/" . $this->encodeUrlString($searchPriceFrom) . "/";
        }
        if ($searchPriceUpto) {
            $link .= "priceupto/" . $this->encodeUrlString($searchPriceUpto) . "/";
        }
        if ($searchDiscountFrom) {
            $link .= "discountfrom/" . $this->encodeUrlString($searchDiscountFrom) . "/";
        }
        if ($searchDiscountTo) {
            $link .= "discountto/" . $this->encodeUrlString($searchDiscountTo) . "/";
        }
        if ($searchGlobalKeyword) {
            $link .= "gkeyword/" . $searchGlobalKeyword . "/";
        }
        if ($searchType) {
            $link .= "stype/" . $searchType . "/";
        }
        if ($searchQuantityBelow != '') {
            $link .= "searchQuantityBelow/" . $this->encodeUrlString($searchQuantityBelow) . "/";
        }
        if ($searchInventory != '') {
            $link .= "inventory/" . $searchInventory . "/";
        }
        //$link .= "list";
        
        
        
        /***********************************all post options**********************************/
        
        //status
        if (isset($_REQUEST['submitProductInline'])) {
            if ($this->ObjForm->isValid('formProduct', 'submitProductInline')) {
                if ($_POST['optionIDsString'] != '') {
                    $productOptionIDS = explode("_", $_POST['optionIDsString']);
                    foreach ($productOptionIDS as $key => $optionID) {
                        if (isset($_POST['itemPrice_' . $optionID])) {                            
                            $optionParams                              = array();
                            $optionParams['productOptionQuantity']     = '';
                            $optionParams['optionSKU']                 = '';
                            if(isset($_POST['optionSKU_' . $optionID])) {
                                 $optionParams['optionSKU']            = $_POST['optionSKU_' . $optionID];
                            }                           
                            $optionParams['productOptionRegularPrice'] = $_POST['itemPrice_' . $optionID];
                            $optionParams['productOptionProductPrice'] = ($_POST['salePrice_' . $optionID] != '') ? $_POST['salePrice_' . $optionID] : $_POST['itemPrice_' . $optionID];
                            if(isset($_POST['optionQuantity_' . $optionID])) {
                                $optionParams['productOptionQuantity']     = isset($_POST['optionQuantity_' . $optionID]) ? $_POST['optionQuantity_' . $optionID] : "0";
                            }
                            $optionParams['businessID']                = $this->ObjSession->getSession("BUSINESS_USER_ID");
                            $resUpdate                                 = $ObjProduct->updateProductsOptionsDetails($optionID, $optionParams);   
                        }
                    }
                }
                if ($_POST['combinationIDsString'] != '') {
                    $combinationIDS = explode("_", $_POST['combinationIDsString']);
                    foreach ($combinationIDS as $key => $combination) {
                         if (isset($_POST['combinationPrice_' . $combination])) {
                            $combinationParams                             = array();
                            $combinationParams['combinationSKU']           = '';
                            $combinationParams['combinationQty']           = '';
                            if(isset($_POST['combinationSKU_' . $combination])) {
                                 $combinationParams['combinationSKU']      = $_POST['combinationSKU_' . $combination];
                            }                                
                            $combinationParams['combinationPrice']         = $_POST['combinationPrice_' . $combination];
                            $combinationParams['combinationPriceDiffType'] = $_POST['combinationPriceDiffType_' . $combination];
                            if(isset($_POST['combinationQuantity_' . $combination])) {
                                $combinationParams['combinationQty']           = isset($_POST['combinationQuantity_' . $combination]) ? $_POST['combinationQuantity_' . $combination] : "0";
                            }
                            $combinationParams['businessID']               = $this->ObjSession->getSession("BUSINESS_USER_ID");
                            $resUpdate                                     = $ObjProduct->updateProductsCombinationsDetails($combination, $combinationParams);
                        }
                    }
                }
                if ($_POST['combinationIDsString'] != '' || $_POST['optionIDsString'] != '') {
                    $this->setMessage("language.lblRecordsUpdated", 3);
                    $this->setRedirect();
                }
            } else {
                $this->ObjView->assign('validated', 'No');
            }
        } else if (isset($_REQUEST['changeStatus'])) {
            $checkProductIDsCount = count($_REQUEST['checkProductIDs']);
            for ($i = 0; $i < $checkProductIDsCount; $i++) {
                $productID    = $_REQUEST['checkProductIDs'][$i];
                $changestatus = $ObjProduct->changeProductStatus($productID,$this->ObjSession->getSession("BUSINESS_USER_ID"));
            }
            if ($changestatus && $_POST['changeStatus'] == "Deleted") {
                $this->setMessage("language.msgproductDelete", 3);
            } else {
                if ($changestatus) {
                    $this->setMessage("language.msgProductUpdateStatus", 3);
                }
            }
            $this->setRedirect("product/index/" . $link);
        } else if (isset($_POST['submitProductSearch'])) {
            $link = '';
            $searchProductID   = isset($_POST['searchProductID']) ? $_POST['searchProductID'] : '';
            $searchOption      = $_POST['searchOption'];
            $brandID           = (int) $_POST['brandID'];
            $searchProductName = strtolower(trim($_POST['searchProductName']));
            $pos               = strpos($searchProductName, "/");
            if ($pos != false) {
                $searchProductName = substr($searchProductName, 0, strrpos($searchProductName, "/"));
            }
            $searchProductName         = $this->encodeUrlString($searchProductName);
            $searchProductType         = isset($_POST['searchProductType']) ? $_POST['searchProductType'] : '';
            $searchProductBusinessType = isset($_POST['searchProductBusinessType']) ? $_POST['searchProductBusinessType'] : '';
            $searchProductBusinessName = isset($_POST['searchProductBusinessName']) ? strtolower(trim($_POST['searchProductBusinessName'])) : '';
            $searchProductBusinessName = $this->encodeUrlString($searchProductBusinessName);
            $searchProductCategories   = isset($_POST['searchProductCategory']) ? $_POST['searchProductCategory'] : '';
            if (!empty($searchProductCategories))
                $searchProductCategory = implode(":", $searchProductCategories);
            if ($_POST['searchProductDate'] != '') {
                if (strpos($_POST['searchProductDate'], " - ")) {
                    $searchDates = explode(' - ', $_POST['searchProductDate']);
                    $fromDate    = $searchDates[0];
                    if (isset($searchDates[1]))
                        $toDate = $searchDates[1];
                } else {
                    $fromDate = $toDate = $_POST['searchProductDate'];
                }
                $searchProductFromDate = trim($fromDate);
                $searchProductToDate   = trim($toDate);
            }
            $sortByOption  = isset($_POST['sortByOption']) ? $_POST['sortByOption'] : '';
            $sortByOrder   = isset($_POST['sortByOrder']) ? $_POST['sortByOrder'] : '';
            $productStatus = $_POST['productStatus'];
            //***********SALES REP*************//
            $searchRep     = isset($_POST['salesRep']) ? $_POST['salesRep'] : '';
            if (!empty($searchRep))
                $searchSalesRep = implode(":", $searchRep);
            //***********END SALES REP*************//
            $productCurrency = isset($_POST['productDefaultCurrency']) ? $_POST['productDefaultCurrency'] : '';
            if ($productStatus == 'Select Status') {
                $productStatus = '';
            }
            if ($searchProductID > 0) {
                $link .= "key/" . $searchProductID . "/";
            }
            if ($brandID > 0) {
                $link .= "brandID/" . $brandID . "/";
            }
            if ($searchProductName != '') {
                $link .= "name/" . $searchProductName . "/";
            }
            if ($searchProductBusinessType > 0) {
                $link .= "btype/" . $searchProductBusinessType . "/";
            }
            if ($searchProductBusinessName != '') {
                $link .= "bname/" . $searchProductBusinessName . "/";
            }
            if (is_array($searchProductCategories) && count(array_filter($searchProductCategories)) > 0) {
                $link .= "category/" . $searchProductCategory . "/";
            }
            if (isset($searchProductFromDate) && $searchProductFromDate != '') {
                $link .= "from/" . $this->urlDate($searchProductFromDate, 'set', $settingsDateFormat) . "/";
            }
            if (isset($searchProductToDate) && $searchProductToDate != '') {
                $link .= "to/" . $this->urlDate($searchProductToDate, 'set', $settingsDateFormat) . "/";
            }
            if ($sortByOption) {
                $link .= "sortby/" . $sortByOption . "/";
            }
            if ($sortByOrder) {
                $link .= "orderby/" . $sortByOrder . "/";
            }
            if ($productStatus) {
                $link .= "dstatus/" . $productStatus . "/";
            }
            if ($productCurrency) {
                $link .= "currency/" . $productCurrency . "/";
            }
            if ($_POST['searchPriceFrom']) {
                $link .= "pricefrom/" . $this->encodeUrlString($_POST['searchPriceFrom']) . "/";
            }
            if ($_POST['searchPriceUpto']) {
                $link .= "priceupto/" . $this->encodeUrlString($_POST['searchPriceUpto']) . "/";
            }
            if ($_POST['searchDiscountFrom']) {
                $link .= "discountfrom/" . $this->encodeUrlString($_POST['searchDiscountFrom']) . "/";
            }
            if ($_POST['searchDiscountTo']) {
                $link .= "discountto/" . $this->encodeUrlString($_POST['searchDiscountTo']) . "/";
            }
            if (isset($_POST['searchGlobalKeyword']) && $_POST['searchGlobalKeyword'] != '') {
                $link .= "gkeyword/" . $_POST['searchGlobalKeyword'] . "/";
            }
            if ($searchOption) {
                $link .= "sType/" . $searchOption . "/";
            }
            if ($_POST['searchQuantityBelow'] != '') {
                $link .= "searchQuantityBelow/" . $this->encodeUrlString($_POST['searchQuantityBelow']) . "/";
            }
            $this->setRedirect("product/index/" . $link);
        }
        /***************************************************************************************/
        if ($sortByOption == 'skey' && $sortByOrder == "asc") {
            $sortByOrderProductKey = "desc";
        } else {
            $sortByOrderProductKey = "asc";
        }
        if ($sortByOption == "stitle" && $sortByOrder == "asc") {
            $sortByOrderProductTitle = "desc";
        } else {
            $sortByOrderProductTitle = "asc";
        }
        if ($sortByOption == 'sbusiness' && $sortByOrder == "asc") {
            $sortByOrderBusiness = "desc";
        } else {
            $sortByOrderBusiness = "asc";
        }
        if ($sortByOption == 'screated' && $sortByOrder == "asc") {
            $sortByOrderDate = "desc";
        } else {
            $sortByOrderDate = "asc";
        }
        $sortByFeatured = ($sortByOption == 'sfeatured' && $sortByOrder == "asc") ? "desc" : "asc";
        $sortByPrice    = ($sortByOption == 'sprice' && $sortByOrder == "asc") ? "desc" : "asc";
        $sortByDiscount = ($sortByOption == 'sdiscount' && $sortByOrder == "asc") ? "desc" : "asc";
        $sortByPopular  = ($sortByOption == 'spopular' && $sortByOrder == "asc") ? "desc" : "asc";
        $sortByEnding   = ($sortByOption == 'sendsoon' && $sortByOrder == "asc") ? "desc" : "asc";
        if(isset($sortByOrder)){
          if(strtolower($sortByOrder)=='asc' || strtolower($sortByOrder)=='desc')  {
              
          }
          else{
              $sortByOrder='asc';
          }
        }
        
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'requestedBy' => 'admin',
            'languageIDs' => $languageIDs,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'sortBy' => $sortByOption,
            'orderBy' => $sortByOrder,
            'searchProductKeyword' => $searchProductName,
            'brandID' => $brandID,
            'searchProductFromDate' => $this->convertDateForSQL($searchProductFromDate, $settingsDateFormat),
            'searchProductToDate' => $this->convertDateForSQL($searchProductToDate, $settingsDateFormat),
            'searchProductStatus' => $productStatus,
            'searchBusinessName' => $searchProductBusinessName,
            'businessID' => $this->ObjSession->getSession("BUSINESS_USER_ID"),
            'searchProductCategories' => $searchProductCategories,
            'searchPriceFrom' => $searchPriceFrom,
            'searchPriceUpto' => $searchPriceUpto,
            'searchDiscountFrom' => $searchDiscountFrom,
            'searchDiscountTo' => $searchDiscountTo,
            'searchGlobalKeyword' => $searchGlobalKeyword,
            'productAddedBy' => '1',
            'searchQuantityBelow' => $searchQuantityBelow,
            'searchInventory' => $searchInventory,
            'page' => 'business',
            'searchFrom' => 'business'
        );
        $resProducts   = $ObjProductList->listProducts($params); 
        $resPagesCount = $this->setPagesCount($key = 'page');
        if($productStatus=="Buybox"){
            foreach($resProducts as $key=>$product){
                $OtherSellerInfo  =  $ObjProductList->getOtherSellersInfo($languageIDs,$product['productID']);
                $resProducts[$key]['otherSeller']  =  $OtherSellerInfo;
            }
        }
        //echo "<pre>"; print_r($resProducts); exit;
        if (count($resProducts) > 0) {
            foreach ($resProducts as $key => $products) {
                  if ($products['enableBuybox'] == 'Yes') {
                    $resPdtID      =$ObjProduct->getBuyboxBusinessProductIDs($products['productID'],$this->ObjSession->getSession("BUSINESS_USER_ID"));
                    $resProducts[$key]['price']=$resPdtID['price'];
               }
                if ($products['InventoryTrackLevel'] == 'No') {
                    $outOfStock = 'No';
                } else {
                    $outOfStock = $ObjProductList->checkProductOutOfStock($products['productID'], isset($products['productQuantityNotifyAt']) ? $products['productQuantityNotifyAt'] : 0, $products['InventoryTrackLevel']);
                }
                $resProducts[$key]['outOfStock'] = $outOfStock;
                $resProducts[$key]['options']    = $ObjProduct->listProductOptions($languageIDs, $products['productID'], Null, Null, 'list', "", "", "basic","Yes",$this->ObjSession->getSession("BUSINESS_USER_ID"));
                $params                          = array(
                    'productID' => $products['productID'],
                    'view' => 'No',
                    'status' => 'A',
                    'languageIDs' => $languageIDs,
                    'purpose' => "basic",
                    'businessID' => $this->ObjSession->getSession("BUSINESS_USER_ID")
                );
                if ($products['multiOptionsAvailable'] != "Yes") {
                    $resProducts[$key]['combination'] = $ObjCustomOption->getProductCombination($params);
                    if (count($resProducts[$key]['combination']) > 0) {
                        $count          = 0;
                        $combinationQty = '';
                        foreach ($resProducts[$key]['combination'] as $combo) {
                            $comboID     = $combo['combinationID'];
                            $Combination = '';
                            if ($combinationQty != '')
                                $combinationQty .= "-";
                            $combinationQty .= $combo['combinationQty'];
                            $comboArray = $ObjCustomOption->getCombinationVariants($languageIDs, $combo['combination']);
                            foreach ($comboArray as $combostr) {
                                if ($Combination)
                                    $Combination .= ",";
                                $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                            }
                            $resProducts[$key]['combination'][$count]['ProductCombo'] = $Combination;
                            $count++;
                        }
                    }
                }
                if ($products['InventoryTrackLevel'] == 'Product') {
                    $optionQty = '';
                    foreach ($resProducts[$key]['options'] as $options) {
                        foreach ($options['businessOptions'] as $busOptions) {
                            if ($optionQty != '')
                                $optionQty .= "-";
                            $optionQty .= $busOptions['productOptionQuantity'];
                        }
                    }
                    $resProducts[$key]['quantityString'] = $optionQty;
                } else if ($products['InventoryTrackLevel'] == 'Options') {
                    $resProducts[$key]['quantityString'] = isset($combinationQty) ? $combinationQty : '';
                }
            }
        }
        //echo "<pre>"; print_r($resProducts); exit;
        $siteUrl   = $this->getSettingValue('site_settings', 'global_http_url');
        $params    = array(
            'languageIDs' => $languageIDs
        );
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign('brandID', $brandID);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('sortByOption', $sortByOption);
        $this->ObjView->assign('sortByOrderProductKey', $sortByOrderProductKey);
        $this->ObjView->assign('sortByOrderProductTitle', $sortByOrderProductTitle);
        $this->ObjView->assign('sortByOrderBusiness', $sortByOrderBusiness);
        $this->ObjView->assign('sortByOrderDate', $sortByOrderDate);
        $this->ObjView->assign('sortByOrderByFeatured', $sortByFeatured);
        $this->ObjView->assign('sortByOrderByPrice', $sortByPrice);
        $this->ObjView->assign('sortByOrderByDiscount', $sortByDiscount);
        $this->ObjView->assign('sortByOrderByPopular', $sortByPopular);
        $this->ObjView->assign('sortByOrderByEnding', $sortByEnding);
        $this->ObjView->assign('productStatus', $productStatus);
        $this->ObjView->assign('searchProductID', $searchProductID);
        $this->ObjView->assign('searchProductName', $searchProductName);
        $this->ObjView->assign('searchQuantityBelow', $searchQuantityBelow);
       
        /*if ($searchProductToDate == $searchProductFromDate) {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate);
        } else {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate . " - " . $searchProductToDate);
        }*/
        if($searchProductFromDate!='' && $searchProductToDate!='') {
            $searchProductDate = $searchProductFromDate . " - " . $searchProductToDate;
        } else {
            $searchProductDate = '';
        }        
        $this->ObjView->assign('searchProductDate',$searchProductDate );
        $this->ObjView->assign('searchProductBusinessType', $searchProductBusinessType);
        $this->ObjView->assign('searchProductBusinessName', $searchProductBusinessName);
        $this->ObjView->assign('searchPriceFrom', $searchPriceFrom);
        $this->ObjView->assign('searchPriceUpto', $searchPriceUpto);
        $this->ObjView->assign('searchDiscountFrom', $searchDiscountFrom);
        $this->ObjView->assign('searchDiscountTo', $searchDiscountTo);
        $this->ObjView->assign('date_format', $date_format);
        $this->ObjView->assign('time_format', $time_format);
        $this->ObjView->assign("resCategories", $resCategories);
        $this->ObjView->assign('searchProductCategorySel', $searchProductCategory);
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->assign("fromDate", $searchProductFromDate);
        $this->ObjView->assign("toDate", isset($searchProductToDate) ? $searchProductToDate : '');
        $this->ObjView->assign("productDefaultCurrency", isset($productCurrency) ? $productCurrency : '');
        if ($searchType) {
            $this->ObjView->assign('searchOption', $searchType);
        } else {
            $this->ObjView->assign('searchOption', 'basic');
        }
        //*********** END SALES REP*************//
        $this->ObjView->assign('sortByOrder', $sortByOrder);
        $settingEditProduct = $this->getSettingValue('multi_vendor_settings', 'allow_edit_approved_products');
        $this->ObjView->assign('settingEditProduct', $settingEditProduct);
        $this->ObjView->display('ProductList.tpl');
    }
    //END OF FUNCTION
    //END OF FUNCTION
    //FUNCTION TO SHOW DEAL DETAILS
    public function showAction() {
        $ObjTimezoneModel = new TimezoneModel();
        $ObjProductList   = new ProductListModel();
        $ObjBusiness      = new BusinessModel();
        $ObjProductReview = new ProductreviewModel();
        $ObjProduct       = new ProductModel();
        $ObjAttr          = new AttributeModel();
        $ObjCustom        = new CustomOptionModel();
        $businessID       = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $rand             = rand(10, 300);
        $secondsToCache   = 60;
        $expiryTime       = gmdate("D, d M Y H:i:s", time() + $secondsToCache) . " GMT";
        header("Expires: $expiryTime");
        header("Pragma: no-cache");
        header("Cache-Control: public,max-age=$secondsToCache");
        // To cache response for 1minute
        $productID = (int)$this->getRequestValue("id");
        $tab       = $this->getRequestValue("tab");
        $this->ObjView->assign('tab', $tab);
        if (isset($_POST['submitBulkStatus'])) {
            $status = $_POST['productOptionStatusUpdate'];
            if ($status) {
                $rsBulkStatus = $ObjProduct->changeProductOptionBulkStatus($_POST, $status);
                $this->setMessage("language.msgStatus", "success");
                $this->ObjView->assign('statusChanged', "1");
                $this->setRedirect("/product/show/id/" . $productID . "/tab/3/");
            }
        }
        $languageIDs       = $this->ObjView->languageIDs;
        $currentLanguageID = $languageIDs['Current'];
        $defaultLanguageID = $languageIDs['Default'];
        $productTab        = $this->getRequestValue("tab");
        //***********SALES REP***************//
        if (__ANALYTICS_MODULE) {
            $detailViewCount = $ObjProduct->getProductPopularityCount($productID);
        }
        $resDetailViewCount    = $detailViewCount['viewed'];
        $uniqueDetailViewCount = $detailViewCount['uniqueViewed'];
        $this->ObjView->assign('detailViewCount', $resDetailViewCount);
        $this->ObjView->assign('uniqueDetailViewCount', $uniqueDetailViewCount);
        $globalUrl             = $this->getSettingValue('site_settings', 'global_http_url');
        $dateFormat            = $this->getSettingValue('site_settings', 'date_format');
        $timeFormat            = $this->getSettingValue('site_settings', 'time_format');
        $defaultTimeZone       = $this->getSettingValue('site_settings', 'default_timezone');
        $settingsTaxApplicable = $this->getSettingValue('product_cart_settings', 'tax_applicable');
        $resProductTimeZones   = $ObjTimezoneModel->listTimezones($defaultTimeZone);
        if ($productID) {
            $paramArray['selectedProductID'] = $productID;
            $paramArray['languageIDs']       = $languageIDs;
            $paramArray['view']              = 'Yes';
            $resSelectproduct                = $ObjProduct->getProductDetails($paramArray);
            $resSelectproduct                = $resSelectproduct[0];
            if ($businessID != $resSelectproduct['businessID'])
                $this->setRedirect('product/');
            $paramArray                      = array();
            $paramArray['productID']         = $productID;
            $paramArray['currentLanguageID'] = $currentLanguageID;
            $productIDs                      = $ObjProductList->getRelatedProducts($productID);
            if (!empty($productIDs)) {
                $paramArray['relIDs'] = $productIDs;
                $resRelatedproducts   = $ObjProductList->getProductsForRelated($paramArray);
                $this->ObjView->assign('resRelatedproducts', $resRelatedproducts);
            }
            $upSellProducts = $ObjProductList->getUpSellProducts($productID);
            if (!empty($upSellProducts)) {
                $paramArray['relIDs'] = $upSellProducts;
                $resUpsellproducts    = $ObjProductList->getProductsForRelated($paramArray);
                $this->ObjView->assign('resUpsellproducts', $resUpsellproducts);
            }
            $crossSellProducts = $ObjProductList->getCrossSellProducts($productID);
            if (!empty($crossSellProducts)) {
                $paramArray['relIDs'] = $crossSellProducts;
                $resCrossSellProducts = $ObjProductList->getProductsForRelated($paramArray);
                $this->ObjView->assign('resCrossSellProducts', $resCrossSellProducts);
            }
            //*********** END SALES REP*************//
            $resProductcategory = $ObjProduct->listProductTocategoryDetails($languageIDs, $productID);
            $this->ObjView->assign('resProductcategory', $resProductcategory);
            $resBusiness       = $ObjBusiness->getBusinessBasic($resSelectproduct['businessID'], $languageIDs);
            $resProductOptions = $ObjProduct->listProductOptions($languageIDs, $productID, "", '', 'list');
            //optionmedia		
            $opCount           = 0;
            foreach ($resProductOptions as $reslistOptions) {
                $productOptionMedia                   = $ObjProduct->listProductOptionMedia($reslistOptions['productOptionID']);
                $resProductOptions[$opCount]['media'] = $productOptionMedia;
                $opCount++;
            }
            //optionmedia           
            if ($resSelectproduct['productImage']) {
                $fileName = __CORE_PUBLIC_PATH . "/uploads/product/thumb/" . $resSelectproduct['productImage'];
                if (file_exists($fileName)) {
                    $this->ObjView->assign('image_directory', 'Yes');
                }
            }
            $citySpecificMultiCurrency = $this->getSettingValue('product_cart_settings', 'city_specific_multi_currency');
            $this->ObjView->assign('citySpecificMultiCurrency', $citySpecificMultiCurrency);
            //$this->ObjView->assign('resSoldCount', $resSoldCount);
            $this->ObjView->assign('resProductOptions', $resProductOptions);
            $this->ObjView->assign('resSelectproduct', $resSelectproduct);
        }
        if ($resSelectproduct['productID']) {
            $productReturn['enableReturn'] = $this->getSettingValue('product_cart_settings', 'enable_product_return');
            $productReturn['returnPeriod'] = $this->getSettingValue('product_cart_settings', 'return_period');
            $this->ObjView->assign('productReturn', $productReturn);
            $this->ObjView->assign('date_format', $dateFormat);
            $this->ObjView->assign('time_format', $timeFormat);
            $this->ObjView->assign('productID', $productID);
            $this->ObjView->assign('resProductTimeZones', $resProductTimeZones);
            $this->ObjView->assign('resBusiness', $resBusiness);
            $this->ObjView->assign('settingsTaxApplicable', $settingsTaxApplicable);
            list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
            $resProductReviewDetails = $ObjProductReview->getProductReviewDetails($languageIDs, $productID, '', 'all', $limitFrom, $limitTo);
            $resPagesCount           = $this->setPagesCount($key = 'page');
            $this->ObjView->assign('resProductReviewDetails', $resProductReviewDetails);
            $this->ObjView->assign('submittedStatus', 0);
            $this->ObjView->assign('productTab', $productTab);
            $previousURL = $this->getPreviousURL();
            if ($previousURL == '') {
                $previousURL = 'product/index/';
            }
            $this->ObjView->assign('previousURL', $previousURL);
            $this->ObjView->assign('global_url', $globalUrl);
            $this->ObjView->assign('rand', $rand);
            $WeightDim = $ObjProduct->getMeasurementById($resSelectproduct['measurementWeight']);
            $LengthDim = $ObjProduct->getMeasurementById($resSelectproduct['measurementLength']);
            $this->ObjView->assign('WeightDim', $WeightDim);
            $this->ObjView->assign('LengthDim', $LengthDim);
            //ATTRIBUTE SECTION//			
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = isset($productRequestID) ? $productRequestID : '';
            $customAttributeArray['attributeSetID']   = $ObjProduct->getAttrSetID($productID);
            $resAttributes                            = $ObjAttr->listProductAttributes($languageIDs, $customAttributeArray);
            if (isset($resAttributes)) {
                $attributeArray = array();
                foreach ($resAttributes as $attributes) {
                    $attributeArray[$attributes['attributeGroupID']]['attributeGroupName']                                                                  = $attributes['name'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrInputType']                             = $attributes['attrInputType'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrName']                                  = $attributes['attrName'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrOptionID'][$attributes['attrOptionID']] = $attributes['attrOptName'];
                    if ($attributes['productID'] == $productID) {
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrDetValue']       = $attributes['attrDetValue'];
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrValueID']        = $attributes['attrValueID'];
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['assignedOptionID'][] = $attributes['attrOptionID'];
                    }
                }
            }
            $this->ObjView->assign('resAttributes', $attributeArray);
            //ATTRIBUTE SECTION//
            //INVENTORY	
            $params       = array(
                'productID' => $productID,
                'view' => 'Yes',
                'status' => 'All',
                'languageIDs' => $languageIDs,
                'businessID' => $this->ObjSession->getSession("BUSINESS_USER_ID")
            );
            $productCombo = $ObjCustom->getProductCombination($params);
            $count        = 0;
            foreach ($productCombo as $combo) {
                $comboID     = $combo['combinationID'];
                $Combination = '';
                $comboArray  = $ObjCustom->getCombinationVariants($languageIDs, $combo['combination']);
                foreach ($comboArray as $combostr) {
                    if ($Combination)
                        $Combination .= ",";
                    $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                }
                $productCombo[$count]['ProductCombo'] = $Combination;
                $productCombo[$count]['ComboImage']   = $ObjCustom->getComboImageByID($comboID);
                $productCombo[$count]['soldQunatity'] = $ObjProduct->getSoldQuantity($combo['combinationHash']);
                $count++;
            }
            $this->ObjView->assign('resproductCombo', $productCombo);
            //INVENTORY	
            //shipping//
            $productShip = $ObjProduct->getProductShippings($productID, $languageIDs);
            $this->ObjView->assign('resproductShip', $productShip);
            //shipping//
            //Custom Option
            $customAttributeArray['productID'] = $productID;
            $resUserLevelAttributes            = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
            $optcount                          = 0;
            foreach ($resUserLevelAttributes as $customOption) {
                if ($customOption['inputType'] == 'select' || $customOption['inputType'] == 'multiselect') {
                    $customParamArray['customOptionID']           = $customOption['customOptionID'];
                    $resUserLevelAttributes[$optcount]['variant'] = $ObjCustom->listOptionVariant($languageIDs, $customParamArray);
                }
                $optcount++;
            }
            $resAtrributeInputTypes = $ObjCustom->listAtrributeInputTypes($this->ObjView->_languageXML, 'Yes');
            $this->ObjView->assign('resAtrributeInputTypes', $resAtrributeInputTypes);
            $this->ObjView->assign('resUserLevelAttributes', $resUserLevelAttributes);
            
            
             if(isset($categoryIDList))
		$categoryList = implode(",", $categoryIDList);
		else
		$categoryList ="";		
		$resProductSizeChart    = $ObjProduct->listSizeChartSatisfy($resSelectproduct['businessID'],$resSelectproduct['brandID'],$categoryList);
		if($resSelectproduct['sizeChart']!='') {
			$this->ObjView->assign('productSizeChart', $resSelectproduct['sizeChart']);
                }
		else {
                        if(empty($resSelectproduct['size_chart_description'])) {
                           $resSelectproduct['size_chart_description'] = '' ;
                        }
			$this->ObjView->assign('productSizeChart', $resSelectproduct['size_chart_description']);
                }
                
            //custom option
            $settingEditProduct = $this->getSettingValue('multi_vendor_settings', 'allow_edit_approved_products');
            $this->ObjView->assign('settingEditProduct', $settingEditProduct);
            $this->ObjView->display('ProductDetails.tpl');
        } else {
            $this->setRedirect('product/');
        }
    }
    //END OF FUNCTION	
    public function samplecsvAction() {
        $ObjProduct       = new ProductModel();
        $ObjCsv           = new Csv();
        $codeLength       = $this->getSettingValue('product_cart_settings', 'product_certificate_length');
        $codeGenerateType = $this->getSettingValue('product_cart_settings', 'code_spporting_letters');
        $i                = 0;
        $count            = 5;
        while ($i < $count) {
            $arrCertCodes[]['CertificateCode'] = $ObjProduct->getRandomCode($codeLength, $codeGenerateType);
            $i++;
        }
        if (is_array($arrCertCodes)) {
            $header = array(
                "CertificateCode"
            );
            $data   = $ObjCsv->output('example.csv', $arrCertCodes, $header);
        }
    }
    //END OF FUNCTION	
    public function ajaxlistProductOptionImagesAction() {
        $productImageCount  = $_POST["productImageCount"];
        $productOptionCount = $_POST["optionCount"];
        $ajax_root_path     = $_POST["ajax_root_path"];
        $this->ObjView->assign('ajax_root_path', $ajax_root_path);
        $this->ObjView->assign('productOptionCount', $productOptionCount);
        $this->ObjView->assign('productImageCount', $productImageCount + 1);
        $this->ObjView->display('ProductOptionImageAjax.tpl');
    }
    //END OF FUNCTION
    //FUNCTION TO LIST DEAL OPTIONS
    public function ajaxLoadProductOptionsTplAction() {
        $productOptionCount = $_POST["productOptionCount"];
        $productTypeKey     = $_POST["productTypeKey"];
        $this->ObjView->assign('productOptionCount', $productOptionCount + 1);
        $this->ObjView->assign('productTypeKey', $productTypeKey);
        $productSelectedType = $_POST["productSelectedType"];
        $this->ObjView->assign('productSelectedType', $productSelectedType);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
        $this->ObjView->display('ProductAdd_OptionsAjax.tpl');
    }
    //END OF FUNCTION 
    // FUNCTION TO FIND DATE LEFT
    public function findDateLeft($fromDate, $toDate) {
        if ($fromDate >= $toDate) {
            return 0;
        }
        $diff        = strtotime($toDate) - strtotime($fromDate);
        $daysLeft    = floor(($diff / 60) / 60 / 24);
        $hoursLeft   = floor((($diff / 60) / 60) % 24);
        $minutesLeft = floor(($diff / 60) % 60);
        return array(
            'days' => $daysLeft,
            'hours' => $hoursLeft,
            'minutes' => $minutesLeft
        );
    }
    //END OF FUNCTION
    //FUNCTION TO FORMAT DATE
    public function formatDate($date, $dateFormat = '', $timeFormat = '') {
        $_dateMap      = array(
            '%B %e, %Y' => 'F d, Y',
            '%A, %B %e, %Y' => 'l  F d, Y',
            '%m/%d/%Y' => 'm/d/Y',
            /**/
            '%d/%m/%Y' => 'd/m/Y',
            '%d-%m-%Y' => 'd-m-Y',
            '%Y-%m-%d' => 'Y-m-d'
        );
        $_timeMap      = array(
            '%I:%M %p' => 'h:i A',
            '%l:%I %p' => 'g:i A',
            '%H:%M' => 'H:i'
        );
        $phpDateFormat = (isset($_dateMap[$dateFormat])) ? $_dateMap[$dateFormat] : '';
        $phpTimeFormat = (isset($_timeMap[$timeFormat])) ? $_timeMap[$timeFormat] : '';
        $format        = $phpDateFormat . ' ' . $phpTimeFormat;
        if ($format) {
            $date = new DateTime($date);
            return $date->format($format);
        } else {
            return $date;
        }
    }
    //END OF FUNCTION
    // Delete temp dir contents
    private function deleteTemp($temp_file_name) {
        $file_name = 'public/uploads/temp/' . $temp_file_name;
        $del       = unlink($file_name);
        return $del;
    }
    //END OF FUNCTION	
    public function newAction() {
        $ObjUsergroup                   = new UsergroupModel();
        $productID                      = $this->getRequestValue("id");
        $productRequestID               = $this->getRequestValue("id");
        $languageIDs                    = $this->ObjView->languageIDs;
        $businessID                     = $this->ObjSession->getSession("BUSINESS_USER_ID");
        
        //Media Settings
        $dataResize['previewHeight']    = $this->getSettingValue('product_cart_settings', 'preview_height');
        $dataResize['previewWidth']     = $this->getSettingValue('product_cart_settings', 'preview_width');
        $dataResize['thumbHeight']      = $this->getSettingValue('product_cart_settings', 'thumb_height');
        $dataResize['thumbWidth']       = $this->getSettingValue('product_cart_settings', 'thumb_width');
        $dataResize['smallthumbWidth']  = $this->getSettingValue('product_cart_settings', 'small_thumb_width');
        $dataResize['smallthumbHeight'] = $this->getSettingValue('product_cart_settings', 'small_thumb_height');
        $productReturn['enableReturn']  = $this->getSettingValue('product_cart_settings', 'enable_product_return');
        $productReturn['returnPeriod']  = $this->getSettingValue('product_cart_settings', 'return_period');
        $this->ObjView->assign('dataResize', $dataResize);
        $this->ObjView->assign('productReturn', $productReturn);
        $requestReview             = $this->getSettingValue('multi_vendor_settings', 'review_before_publish');
        //Media Settings
        if ($this->ObjForm->isValid('Product', 'submitProductDetails')) {
            if (!empty($_POST['buyboxproductID']) && ($_POST['hiddenbuyboxStatus'] == "Yes")) {
                $ObjClone       = new CloneModel();
                $ObjProduct     = new ProductModel();
                $clonedata      = $ObjClone->fn_clone_product($languageIDs, $_POST['buyboxproductID'], 0,'No','Yes');
                $msgCu	= '';
		if (!empty($clonedata['product_id'])) {
                    $pid            = $clonedata['product_id'];
                    $LinkBuybox     = $ObjProduct->saveProductLinkBuybox($languageIDs, $_POST, $pid,'Yes');
                    $this->setMessage($this->getLanguageValue("msgAddProductRequest").$msgCu, "success");	
		}		
		$this->setRedirect("product/edit/id/$pid/");
            }else{
                $_POST['dataResize'] = $dataResize;
                $this->ProductAddform($productID, $productRequestID);
            }
            
        } elseif (isset($_POST['productOptionAddCount']) && $_POST['productOptionAddCount'] != '') {
            $this->ObjView->assign("productTypeKey", $_POST['productTypeKey']);
            $resProductOptions = isset($_POST['productOptionsGroup']) ? $_POST['productOptionsGroup'] : '';
            $opCount           = 0;
            $resProductOptions = $this->optionPostback($resProductOptions);
            $this->ObjView->assign('resProductOptions_postback', $resProductOptions);
            $this->ObjView->assign('postCallback', '1');
        }
        if ($this->ObjSession->getSession("BUSINESS_USER_ID"))
            $this->ObjView->assign("businessID", $this->ObjSession->getSession("BUSINESS_USER_ID"));
        $this->productAddAssign($productID, $productRequestID);
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
        $this->ObjView->assign('sysKeys', SYSTEM_DIR_KEYS);
        $this->ObjView->display('ProductAdd.tpl');
    }
    public function editAction() {
        $ObjUsergroup       = new UsergroupModel();
        $ObjBrand           = new BrandModel();
        $productRequestID   = $this->getRequestValue("reqID");
        $productID          = $this->getRequestValue("id");
        $languageIDs        = $this->ObjView->languageIDs;
        $ctab               = $this->getRequestValue("tab");
        $settingEditProduct = $this->getSettingValue('multi_vendor_settings', 'allow_edit_approved_products');
        if (($settingEditProduct != 'Yes') && ($productID > 0)) {
            $this->setRedirect("product/show/id/" . $productID . "/");
        }
		$requestReview             = $this->getSettingValue('multi_vendor_settings', 'review_before_publish');
		if (!empty($requestReview))
            $review_before_publish    = 'Yes';
        else {
            $review_before_publish    = 'No';
        }
        if ($productRequestID > 0 || $productID > 0) {
            $ObjProduct = new ProductModel();
            $businessID = $this->ObjSession->getSession("BUSINESS_USER_ID");
            if ($productRequestID)
                $proBusinessID = $ObjProduct->getProductRequestBusinessID($productRequestID);
            else
                $proBusinessID = $ObjProduct->getProductBusinessID($productID);
            if ($businessID != $proBusinessID) {
                if ($productRequestID)
                    $this->setRedirect("product/request/");
                else
                    $this->setRedirect("product/index/");
            }
        }
        //Media Settings
        $dataResize['previewHeight']    = $this->getSettingValue('product_cart_settings', 'preview_height');
        $dataResize['previewWidth']     = $this->getSettingValue('product_cart_settings', 'preview_width');
        $dataResize['thumbHeight']      = $this->getSettingValue('product_cart_settings', 'thumb_height');
        $dataResize['thumbWidth']       = $this->getSettingValue('product_cart_settings', 'thumb_width');
        $dataResize['smallthumbWidth']  = $this->getSettingValue('product_cart_settings', 'small_thumb_width');
        $dataResize['smallthumbHeight'] = $this->getSettingValue('product_cart_settings', 'small_thumb_height');
        $productReturn['enableReturn']  = $this->getSettingValue('product_cart_settings', 'enable_product_return');
        $productReturn['returnPeriod']  = $this->getSettingValue('product_cart_settings', 'return_period');
        $this->ObjView->assign('dataResize', $dataResize);
        $this->ObjView->assign('productReturn', $productReturn);
        //Media Settings
        if (isset($_POST['submitProductDetails'])) {
            if ($this->ObjForm->isValid('Product', 'submitProductDetails')) {                
                   if (!empty($_POST['buyboxproductID']) && ($_POST['hiddenbuyboxStatus'] == "Yes")) {
                        if (!empty($productID)) {                           
                            $pid            = $productID;
                            $ObjProduct     =   new ProductModel();
                            if($_POST['hiddenParProduct']!=$_POST['buyboxproductID']){
                                $ObjClone       = new CloneModel();                                
                                $clonedata      = $ObjClone->fn_clone_product($languageIDs, $_POST['buyboxproductID'],$productID,'No','Yes','');
                            }
                        }
                         //$ObjProduct->addSizeChartToproduct($productID);
                        $LinkBuybox     = $ObjProduct->saveProductLinkBuybox($languageIDs, $_POST, $pid,''); 
                        $this->setMessage("language.msgProductDetailsSave", "success");
                        if($type =='look'){
                           $this->setRedirect("product/edit/type/look/id/$pid/"); 
                        }
                        else{
                            $this->setRedirect("product/edit/id/$pid/");
                        }
                    
                    }else{                        
                         $_POST['dataResize'] = $dataResize;
                         $this->ProductEditform($productID);
                    }
                  
                  
            } elseif ($_POST['productOptionAddCount']) {
                $this->ObjView->assign("productTypeKey", $_POST['productTypeKey']);
                $resProductOptions = $_POST['productOptionsGroup'];
                $opCount           = 0;
                $resProductOptions = $this->optionPostback($resProductOptions, $_POST);
                $this->ObjView->assign('resProductOptions_postback', $resProductOptions);
                $this->ObjView->assign('postCallback', '1');
            }
        }
        if (!($productID || $productRequestID)) {
            $this->setRedirect("product/new/");
        }
        $this->saveCustomAttribute();
        $this->saveCustomOption();
        $this->productEditassign($productID, $productRequestID);
        $paramsArray['productRequestID'] = $productRequestID;
        $paramsArray['productID']        = $productID;
        $paramsArray['BusinessID']       = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $this->bindAttributeForm($paramsArray);
        $this->bindOptionForm($paramsArray);
        $this->bindInventoryForm($paramsArray);
        $this->bindShippingForm($paramsArray);
        $this->ObjView->assign('hiddenProductType', 'product_product');
        if ($ctab)
            $this->ObjView->assign('ctab', $ctab);
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
        $this->ObjView->assign('review_before_publish', $review_before_publish);
        $this->ObjView->display('ProductAdd.tpl');
    }
    
    public function buyboxeditAction() {
        $ObjProduct                 =           new ProductModel();
        $ObjUsergroup               =           new UsergroupModel();
        $ObjBusiness                =           new BusinessModel();
        $businessID                 =           $this->ObjSession->getSession("BUSINESS_USER_ID");
        $productID                  =           $this->getRequestValue("id");
        $addBuyBox                  =           $this->getRequestValue("add");
        $addBuyBox                  =           isset($addBuyBox) ? $addBuyBox : "no";
        $languageIDs                =           $this->ObjView->languageIDs;
        $productDetails             =           $ObjProduct->getBasicProductDetails($languageIDs,$productID);
        $optionDetails              =           $ObjProduct->getProductBusinessOptionsDetails($languageIDs,$productID,$businessID,$addBuyBox);
        $resPeriod                  =           $ObjProduct->getDispatchTime();
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups             =           $ObjUsergroup->listUsergroups($params);
        $businessLocations          =           $ObjBusiness->listBusinessLocations(0,"",'Active',$businessID,$languageIDs);
        
        if(count($optionDetails)>0){
            foreach($optionDetails as $key=>$busOptions){
                $busProductOptionID    =  $busOptions['productOptionID'];
                $busOptBusinessID      =  $busOptions['businessID'];
                $groupPriceValues      =  $ObjProduct->getbusinessGroupPrice($busProductOptionID,$busOptBusinessID);
                $optionDetails[$key]['group_price'] = $groupPriceValues;
            }
        }
        
        //if (isset($_POST['submitProductDetails']) && $_POST['submitProductDetails']=="Save") {
        if ($this->ObjForm->isValid('productBusOptForm', 'submitProductDetails')) { 
            if(count($_POST['businessOptionsGroup'])>0){
                foreach($_POST['businessOptionsGroup'] as $busGroupVal){
                    $busGroupVal['assignBusinessID']  =  $businessID;
                    $busGroupVal['hiddenBusinessID']  =  $businessID;
                    $prodOptionBusID    =   $busGroupVal['hiddenOptionBusinessID'];
                    $sellThisOption     =   isset($busGroupVal['sellThisOption']) ? $busGroupVal['sellThisOption'] : "No";
                    if($sellThisOption=="Yes"){
                        $updateMerchant     =   $ObjProduct->addBusinessOptions($busGroupVal['hiddenProductOptionID'],$busGroupVal,$busGroupVal['hiddenProductID'],$prodOptionBusID);
                    }else{
                        if($prodOptionBusID>0){
                            $deleteMerchant =   $ObjProduct->deleteBusinessOptions($prodOptionBusID);
                        }
                    }
                }
                $this->setMessage("language.msgProductDetailsSave", "success");
                $this->setRedirect("product/buyboxedit/id/" . $productID . "/");
            }
        }else if(count($_POST['businessOptionsGroup'])>0){
            $postOptionArr              =     array();
            $busGroupIncr               =     0;
            foreach($_POST['businessOptionsGroup'] as $key=>$busGroupValues){
                $postOptionArr[$busGroupIncr]['productOptionBusinessID']    =       $busGroupValues['hiddenOptionBusinessID'];
                $postOptionArr[$busGroupIncr]['productOptionID']            =       $busGroupValues['hiddenProductOptionID'];
                $postOptionArr[$busGroupIncr]['productID']                  =       $busGroupValues['hiddenProductID'];
                $postOptionArr[$busGroupIncr]['productOptionName']          =       $busGroupValues['productOptionName'];
                $postOptionArr[$busGroupIncr]['optionSKU']                  =       $busGroupValues['optionSKU'];
                $postOptionArr[$busGroupIncr]['businessOptionDefault']      =       $busGroupValues['businessOptionDefault'];
                $postOptionArr[$busGroupIncr]['businessOptionSKU']          =       $busGroupValues['businessOptionSKU'];
                $postOptionArr[$busGroupIncr]['productOptionRegularPrice']  =       $busGroupValues['businessOptionReqPrice'];
                $postOptionArr[$busGroupIncr]['productOptionProductPrice']  =       $busGroupValues['businessOptionSalePrice'];
                $postOptionArr[$busGroupIncr]['productOptionQuantity']      =       $busGroupValues['businessQuantity'];
                $postOptionArr[$busGroupIncr]['busWareHouse']               =       $busGroupValues['businessWareHouse'];
                $postOptionArr[$busGroupIncr]['businessDispatchTime']       =       $busGroupValues['businessDispatchTime'];
                $postOptionArr[$busGroupIncr]['group_price']                =       $busGroupValues['group_price'];
                $postOptionArr[$busGroupIncr]['busProductStatus']           =       $busGroupValues['busProductStatus'];
                $postOptionArr[$busGroupIncr]['sellThisOptionCheck']        =       $busGroupValues['sellThisOptionCheck'];
                $busGroupIncr                                               =       $busGroupIncr+1;
            }
            $this->ObjView->assign('businessOptionsGroup_postback', $postOptionArr);
        }
            
        $this->ObjView->assign('productID', $productID);
        $this->ObjView->assign('productDetails', $productDetails);
        $this->ObjView->assign('optionDetails', $optionDetails);
        $this->ObjView->assign('resPeriod', $resPeriod);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $this->ObjView->assign("businessLocations", $businessLocations);
        $this->ObjView->display('ProductBuyboxAdd.tpl');
    }
    
    
    public function buyboxreqeditAction() {
        $ObjProduct                 =           new ProductModel();
        $ObjUsergroup               =           new UsergroupModel();
        $ObjBusiness                =           new BusinessModel();
        $businessID                 =           $this->ObjSession->getSession("BUSINESS_USER_ID");
        $productID                  =           $this->getRequestValue("id");
        $addBuyBox                  =           $this->getRequestValue("add");
        $addBuyBox                  =           isset($addBuyBox) ? $addBuyBox : "no";
        $languageIDs                =           $this->ObjView->languageIDs;
        $productDetails             =           $ObjProduct->getBasicProductDetails($languageIDs,$productID);
        $optionDetails              =           $ObjProduct->getProductReqBusinessOptionsDetails($languageIDs,$productID,$businessID,$addBuyBox);
        $resPeriod                  =           $ObjProduct->getDispatchTime();
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups             =           $ObjUsergroup->listUsergroups($params);
        $businessLocations          =           $ObjBusiness->listBusinessLocations(0,"",'Active',$businessID,$languageIDs);
        
        if(count($optionDetails)>0){
            foreach($optionDetails as $key=>$busOptions){
                $busProductOptionID    =  $busOptions['productOptionID'];
                $busOptBusinessID      =  $busOptions['businessID'];
                $groupPriceValues      =  $ObjProduct->getbusinessReqGroupPrice($busProductOptionID,$busOptBusinessID);
                $optionDetails[$key]['group_price'] = $groupPriceValues;
            }
        }
        
        //if (isset($_POST['submitProductDetails']) && $_POST['submitProductDetails']=="Save") {
        if ($this->ObjForm->isValid('productBusOptForm', 'submitProductDetails')) { 
            $sellThisOptionIncr         =       0;
            if(count($_POST['businessOptionsGroup'])>0){
                foreach($_POST['businessOptionsGroup'] as $busGroupVal){
                    $sellThisOption     =   isset($busGroupVal['sellThisOption']) ? $busGroupVal['sellThisOption'] : "No";
                    if($sellThisOption=="Yes"){
                        $sellThisOptionIncr =   $sellThisOptionIncr+1;
                    }
                }
            }
            if($sellThisOptionIncr<=0){
                $this->setMessage("language.errNoDetailsForMerchants", "error");
                $this->setRedirect("product/buyboxreqedit/id/" . $productID . "/");
            }
            
            if(count($_POST['businessOptionsGroup'])>0){
                foreach($_POST['businessOptionsGroup'] as $busGroupVal){
                    $busGroupVal['assignBusinessID']  =  $businessID;
                    $busGroupVal['hiddenBusinessID']  =  $businessID;
                    $prodOptionBusID    =   $busGroupVal['hiddenOptionBusinessID'];
                    $sellThisOption     =   isset($busGroupVal['sellThisOption']) ? $busGroupVal['sellThisOption'] : "No";
                    if($sellThisOption=="Yes"){
                        $updateMerchant     =   $ObjProduct->addBusinessReqOptions($busGroupVal['hiddenProductOptionID'],$busGroupVal,$busGroupVal['hiddenProductID'],$prodOptionBusID);
                    }else{
                        if($prodOptionBusID>0){
                            $deleteMerchant =   $ObjProduct->deleteBusinessReqOptions($prodOptionBusID);
                        }
                    }
                }
                $this->setMessage("language.msgProductDetailsSave", "success");
                $this->setRedirect("product/buyboxreqedit/id/" . $productID . "/");
            }
        }else if(count($_POST['businessOptionsGroup'])>0){
            $postOptionArr              =     array();
            $busGroupIncr               =     0;
            foreach($_POST['businessOptionsGroup'] as $key=>$busGroupValues){
                $postOptionArr[$busGroupIncr]['productReqOptionBusinessID'] =       $busGroupValues['hiddenOptionBusinessID'];
                $postOptionArr[$busGroupIncr]['productOptionID']            =       $busGroupValues['hiddenProductOptionID'];
                $postOptionArr[$busGroupIncr]['productID']                  =       $busGroupValues['hiddenProductID'];
                $postOptionArr[$busGroupIncr]['productOptionName']          =       $busGroupValues['productOptionName'];
                $postOptionArr[$busGroupIncr]['optionSKU']                  =       $busGroupValues['optionSKU'];
                $postOptionArr[$busGroupIncr]['businessOptionDefault']      =       $busGroupValues['businessOptionDefault'];
                $postOptionArr[$busGroupIncr]['businessOptionSKU']          =       $busGroupValues['businessOptionSKU'];
                $postOptionArr[$busGroupIncr]['productOptionRegularPrice']  =       $busGroupValues['businessOptionReqPrice'];
                $postOptionArr[$busGroupIncr]['productOptionProductPrice']  =       $busGroupValues['businessOptionSalePrice'];
                $postOptionArr[$busGroupIncr]['productOptionQuantity']      =       $busGroupValues['businessQuantity'];
                $postOptionArr[$busGroupIncr]['busWareHouse']               =       $busGroupValues['businessWareHouse'];
                $postOptionArr[$busGroupIncr]['businessDispatchTime']       =       $busGroupValues['businessDispatchTime'];
                $postOptionArr[$busGroupIncr]['group_price']                =       $busGroupValues['group_price'];
                $postOptionArr[$busGroupIncr]['busProductStatus']           =       $busGroupValues['busProductStatus'];
                $postOptionArr[$busGroupIncr]['sellThisOptionCheck']        =       $busGroupValues['sellThisOptionCheck'];
                $busGroupIncr                                               =       $busGroupIncr+1;
            }
            $this->ObjView->assign('businessOptionsGroup_postback', $postOptionArr);
        }
            
        $this->ObjView->assign('productID', $productID);
        $this->ObjView->assign('productDetails', $productDetails);
        $this->ObjView->assign('optionDetails', $optionDetails);
        $this->ObjView->assign('resPeriod', $resPeriod);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $this->ObjView->assign("businessLocations", $businessLocations);
        $this->ObjView->display('ProductBuyboxRequestAdd.tpl');
    }
    
    //Add section for all products
    function productAddAssign($productID, $productRequestID) {
        $ObjProduct                = new ProductModel();
        $ObjBusiness               = new BusinessModel();
        $ObjTaxclassModel          = new TaxclassModel();
        $ObjProductCategory        = new ProductCategoryModel();
        $ObjAttr                   = new AttributeModel();
        $ObjBrand                  = new BrandModel();
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
        $languageIDs               = $this->ObjView->languageIDs;
        $defaultTimeZone           = $this->getSettingValue('site_settings', 'default_timezone');
        $globalCommision           = $this->getSettingValue('multi_vendor_settings', 'global_product_commission');
        $globalCommisionPercentage = $this->getSettingValue('multi_vendor_settings', 'commission_percentage');
        $resBusiness               = $ObjBusiness->listBusinessInOptions($languageIDs);
        $resAttrSet                = $ObjAttr->listAttributeSet();
        $resTaxClass               = $ObjTaxclassModel->listTaxClasses("", "", "", "Active", "product");
        $resProducts               = $ObjProduct->getProductTitleBuybox($languageIDs);
        //For MIC				
        $this->ObjView->assign('defaultCurrency', $this->ObjView->_defaultCurrency);
        //End MIC
        $resCategoryTree = $ObjProductCategory->listProductCategoryItems($languageIDs, 0, 0);
        $resCategoryTree = array_slice($resCategoryTree, 1);
        $this->ObjView->assign('resCategoryTree', $resCategoryTree);
		
		$resProductCategories      = $ObjProductCategory->listProductCategories($languageIDs, -1);
        $productCategoryCount   = count($resProductCategories);
        foreach ($resProductCategories as $key => $value) {
            $categoryTree[$resProductCategories[$key]['productCategoryParent']][] = $resProductCategories[$key];
        }
        $resProductCategories = $this->createCategoryTree($categoryTree, $categoryTree[0]); //echo '<pre>'; 
        $this->ObjView->assign("resProductCategories", $resProductCategories);
		
		
        if (isset($_POST['submitProductDetails'])) {
            if (!empty($_POST['productCategoryID'])) {
                foreach ($_POST['productCategoryID'] as $values) {
                    $resProductcategory[] = isset($values['productCategoryID']) ? $values['productCategoryID'] : '';
                }
                $this->ObjView->assign('resProductcategory', $resProductcategory);
            }
        }
        $taxApplicable = $this->getSettingValue('product_cart_settings', 'tax_applicable');
        $this->ObjView->assign('taxApplicable', $taxApplicable);
        $this->ObjView->assign('globalCommision', $globalCommision);
        $this->ObjView->assign('globalCommisionPercentage', $globalCommisionPercentage);
        $this->ObjView->assign('DeafaultTimeZone', $defaultTimeZone);
        $this->ObjView->assign('resBusiness', $resBusiness);
        $this->ObjView->assign('resProducts', $resProducts);
        $currDate = $ObjProduct->getCurrentDate();
        $this->ObjView->assign('currDate', $currDate);
        $this->ObjView->assign('resTaxClass', $resTaxClass);
        $this->ObjView->assign('productFinePrint', isset($resSelectproduct['productFinePrint']) ? $resSelectproduct['productFinePrint'] : '');
        $this->ObjView->assign('productHighlights', isset($resSelectproduct['productHighlights']) ? $resSelectproduct['productHighlights'] : '');
        $this->ObjView->assign('productReviews', isset($resSelectproduct['productReviews']) ? $resSelectproduct['productReviews'] : '');
        $this->ObjView->assign('productDescription', isset($resSelectproduct['productDescription']) ? $resSelectproduct['productDescription'] : '');
        //measurement//
        $resLength = $ObjProduct->listMeasuremntClass("Length");
        $this->ObjView->assign('resLength', $resLength);
        $resWeight = $ObjProduct->listMeasuremntClass("Weight");
        $this->ObjView->assign('resWeight', $resWeight);
        //measurement//
        //$this->ObjView->assign('defaultCurrency', $this->getSettingValue('site_settings', 'default_currency'));
        $this->ObjView->assign('defaultCurrency', $this->ObjView->_defaultCurrency);
        $this->ObjView->assign('resAttrSet', $resAttrSet);
        $params    = array(
            'languageIDs' => $languageIDs
        );
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign('baseProductID', '');
        $this->ObjView->assign('buyboxStatus', '');        
        $this->ObjView->assign('parentProductID', '');
        $this->ObjView->assign('businessID', $this->ObjSession->getSession("BUSINESS_USER_ID"));
        $this->ObjView->assign('resSelectproduct', '');
    }
    //End
    //Edit section  for all product types		
    function productEditassign($productID, $productRequestID) {
        $ObjProduct             = new ProductModel();
        $ObjProductReq          = new ProductRequestModel();
        $ObjProductList         = new ProductListModel();
        $ObjBusiness            = new BusinessModel();
        $ObjImage               = new ImageModel();
        $ObjTaxclassModel       = new TaxclassModel();
        $ObjProductCategory     = new ProductCategoryModel();
        $ObjAttr                = new AttributeModel();
        $settingsDateFormat     = $this->getSettingValue('site_settings', 'date_format');
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $defaultTimeZone        = $this->getSettingValue('site_settings', 'default_timezone');
        $enable_cdn             = $this->getSettingValue('site_settings', 'enable_cdn_images');
        $resBusiness            = $ObjBusiness->listBusinessInOptions($languageIDs);
        $resProducts            = $ObjProduct->getProductTitleBuybox($languageIDs);
        $resAttrSet             = $ObjAttr->listAttributeSet();
        $resTaxClass            = $ObjTaxclassModel->listTaxClasses("", "", "", "Active", "product");
        $resPeriod              = $ObjProduct->getDispatchTime();
        $this->ObjView->assign('resPeriod', $resPeriod);
        if (isset($productID) || isset($productRequestID)) {
            $paramArray['languageIDs'] = $languageIDs;
            $paramArray['view']        = 'Yes';
            if (isset($productRequestID) && $productRequestID > 0) {
                $paramArray['selectedProductID'] = $productRequestID;
                $resProductOptions               = $ObjProductReq->listProductReqOptions($languageIDs, $productRequestID, "", "", 'list');
                foreach ($resProductOptions as $key => $reslistOptions) {
                    $productOptionID                        = $reslistOptions['option_id'];
                    $resProductOptions[$key]['group_price'] = $ObjProductReq->getOptionRequestUserGroupPrice($productOptionID);
                    $resProductOptions[$key]['tier_price']  = $ObjProductReq->getOptionRequestTierPrice($productOptionID);
                }
                $resSelectproduct   = $ObjProductReq->getProductRequestDetails($paramArray);
                $resProductcategory = $ObjProductReq->listProductRequestTocategoryDetails($languageIDs, $productRequestID);
                $this->ObjView->assign('productReqID', $productRequestID);
                $resSelectproduct = $resSelectproduct['0'];
            } else {
                $paramArray['selectedProductID'] = $productID;
                $resProductOptions               = $ObjProduct->listProductOptions($languageIDs, $productID, "", "", 'list');
                foreach ($resProductOptions as $key => $reslistOptions) {
                    $productOptionID                        = $reslistOptions['option_id'];
                    $resProductOptions[$key]['group_price'] = $ObjProduct->getOptionUserGroupPrice($productOptionID);
                    $resProductOptions[$key]['tier_price']  = $ObjProduct->getOptionTierPrice($productOptionID);
                }
                $resSelectproduct   = $ObjProduct->getProductDetails($paramArray);
                $resProductcategory = $ObjProduct->listProductTocategoryDetails($languageIDs, $productID);
                $resSelectproduct   = $resSelectproduct['0'];
            }
            $timezonval = $resSelectproduct['productTimeZone'];
            $this->ObjView->assign('productTimeZoneSelect', $timezonval);
            //MIC	
            $this->ObjView->assign('showCountTimer', $resSelectproduct['showCountTimer']);
            //MIC	
            if (empty($resSelectproduct)) {
                $this->setRedirect("product/new/");
            }
            //measurement//
            $resLength = $ObjProduct->listMeasuremntClass("Length");
            $this->ObjView->assign('resLength', $resLength);
            $resWeight = $ObjProduct->listMeasuremntClass("Weight");
            $this->ObjView->assign('resWeight', $resWeight);
            //measurement//	
            $resCategoryTree = $ObjProductCategory->listProductCategoryItems($languageIDs, 0, 0);
            $resCategoryTree = array_slice($resCategoryTree, 1);
            $this->ObjView->assign('resCategoryTree', $resCategoryTree);
			
			
			$resProductCategories      = $ObjProductCategory->listProductCategories($languageIDs, -1);
			$productCategoryCount   = count($resProductCategories);
			foreach ($resProductCategories as $key => $value) {
				$categoryTree[$resProductCategories[$key]['productCategoryParent']][] = $resProductCategories[$key];
			}
			$resProductCategories = $this->createCategoryTree($categoryTree, $categoryTree[0]); //echo '<pre>'; 
			$this->ObjView->assign("resProductCategories", $resProductCategories);
			
			
            //optionmedia		
            $opCount = 0;
            foreach ($resProductOptions as $reslistOptions) {
                if (!empty($productRequestID)) {
                    if (!empty($reslistOptions['productRequestOptionID']))
                        $productOptionMedia = $ObjProductReq->listRequestOptionMedia($reslistOptions['productRequestOptionID']);
                } else {
                    if (!empty($reslistOptions['productOptionID']))
                        $productOptionMedia = $ObjProduct->listProductOptionMedia($reslistOptions['productOptionID']);
                }
                if (!empty($productOptionMedia)) {
                    foreach ($productOptionMedia as $key => $productmedia) {
                        if (!empty($productRequestID)) {
                            $fileName = "uploads/catalog-request/product/preview-main/" . $productmedia['productMedia'];
                        } else {
                            $fileName = "uploads/catalog/product/preview-main/" . $productmedia['productMedia'];
                        }
                        $result = $ObjImage->file_exist($fileName);
                        if ($result) {
                            $productOptionMedia[$key]['productthumb'] = $productmedia['productMedia'];
                        }
                    }
                    $resProductOptions[$opCount]['media'] = $productOptionMedia;
                }
                $opCount++;
            }
            //echo '<pre>'; print_r($resProductOptions); exit;
            //optionmedia
            foreach ($resProductcategory as $values) {
                $resProductcategory[] = $values['productCategoryID'];
				$categoryIDList[]=$values['productCategoryID'];
            }
			if(isset($categoryIDList)) {
			$resProductcat = implode(",", $categoryIDList);
			$resProductcategory[]= "0,".$resProductcat;
            $this->ObjView->assign('resProductcategory', $resProductcategory);
			}
            if ($resSelectproduct['productStartTime']) {
                $productStartTime                     = explode(" ", $resSelectproduct['productStartTime']);
                $resSelectproduct['productStartTime'] = $productStartTime[0];
            }
            if ($resSelectproduct['productEndTime']) {
                $productEndTime                     = explode(" ", $resSelectproduct['productEndTime']);
                $resSelectproduct['productEndTime'] = $productEndTime[0];
            }
            $this->ObjView->assignValues($resSelectproduct);
            //For MIC			
            $this->ObjView->assign('productDefaultCurrency', $this->ObjView->_defaultCurrency);
            $this->ObjView->assign('resProductOptions', $resProductOptions);
            if (isset($_POST['submitProductDetails'])) {
                if (!empty($_POST['productCategoryID'])) {
                    foreach ($_POST['productCategoryID'] as $values) {
                        if (!empty($values['productCategoryID']))
                            $resProductcategory[] = $values['productCategoryID'];
                    }
                    $this->ObjView->assign('resProductcategory', $resProductcategory);
                }
            }
        }
        $taxApplicable                   = $this->getSettingValue('product_cart_settings', 'tax_applicable');
        $productIDs                      = $ObjProductList->getRelatedProducts($productID);
        $paramArray                      = array();
        $paramArray['currentLanguageID'] = $languageIDs['Current'];
        $paramArray['productID']         = $productID;
        $paramArray['productStatus']     = 'Active';
        if (!empty($productIDs)) {
            $paramArray['relIDs']         = $productIDs;
            $resRightListUpcomingProducts = $ObjProductList->getProductsForRelated($paramArray);
            $this->ObjView->assign('resRightListUpcomingProducts', $resRightListUpcomingProducts);
            $productProducts = implode("~*", $productIDs);
            $this->ObjView->assign('Productproducts', $productProducts);
        }
        $upSellProducts = $ObjProductList->getUpSellProducts($productID);
        if (!empty($upSellProducts)) {
            $paramArray['relIDs']   = $upSellProducts;
            $resRightUpsellProducts = $ObjProductList->getProductsForRelated($paramArray);
            $this->ObjView->assign('resRightUpsellProducts', $resRightUpsellProducts);
            $productUpProducts = implode("~*", $upSellProducts);
            $this->ObjView->assign('ProductUpproducts', $productUpProducts);
        }
        $crossSellProducts = $ObjProductList->getCrossSellProducts($productID);
        if (!empty($crossSellProducts)) {
            $paramArray['relIDs']      = $crossSellProducts;
            $resRightCrossSellProducts = $ObjProductList->getProductsForRelated($paramArray);
            $this->ObjView->assign('resRightCrossSellProducts', $resRightCrossSellProducts);
            $productCrossProducts = implode("~*", $crossSellProducts);
            $this->ObjView->assign('ProductCrossproducts', $productCrossProducts);
        }
        
        if(isset($categoryIDList))
		$categoryList = implode(",", $categoryIDList);
		else
		$categoryList ="";		
		$resProductSizeChart    = $ObjProduct->listSizeChartSatisfy($resSelectproduct['businessID'],$resSelectproduct['brandID'],$categoryList);
		if($resSelectproduct['sizeChart']!='')
			$this->ObjView->assign('productSizeChart', $resSelectproduct['sizeChart']);
		else
			$this->ObjView->assign('productSizeChart', $resProductSizeChart['size_chart_description']);		 
        
        
        $this->ObjView->assign('taxApplicable', $taxApplicable);
        $this->ObjView->assign('productID', $productID);
		$this->ObjView->assign('categoryIDList', isset($categoryIDList)?$categoryIDList:'');
        $this->ObjView->assign('DeafaultTimeZone', $defaultTimeZone);
        $this->ObjView->assign('resBusiness', $resBusiness);
        $this->ObjView->assign('resProducts', $resProducts);
        $this->ObjView->assign('resTaxClass', $resTaxClass);
        $this->ObjView->assign('productTitle', $resSelectproduct['productTitle']);
        $this->ObjView->assign('productFinePrint', $resSelectproduct['productFinePrint']);
        $this->ObjView->assign('productHighlights', $resSelectproduct['productHighlights']);
        $this->ObjView->assign('productReviews', isset($resSelectproduct['productReviews']) ? $resSelectproduct['productReviews'] : '');
        $this->ObjView->assign('productDescription', $resSelectproduct['productDescription']);
        $this->ObjView->assign('productMetaTitle', $resSelectproduct['productMetaTitle']);
        $this->ObjView->assign('productMetaDescription', $resSelectproduct['productMetaDescription']);
        $this->ObjView->assign('productMetaKeywords', $resSelectproduct['productMetaKeywords']);
        $this->ObjView->assign('businessID', $resSelectproduct['businessID']);
        //$this->ObjView->assign('defaultCurrency', $this->getSettingValue('site_settings', 'default_currency'));
        $this->ObjView->assign('defaultCurrency', $this->ObjView->_defaultCurrency);
        $this->ObjView->assign('resAttrSet', $resAttrSet);
        $this->ObjView->assign('resSelectproduct', $resSelectproduct);
        if ($resSelectproduct['productImage']) {
            if ($productRequestID)
                $fileName = "uploads/catalog-request/product/preview-main/" . $resSelectproduct['productImage'];
            else
                $fileName = "uploads/catalog/product/preview-main/" . $resSelectproduct['productImage'];
            $result = $ObjImage->file_exist($fileName);
            if ($result) {
                $this->ObjView->assign('productImageThumb', $resSelectproduct['productImage']);
                $this->ObjView->assign('thumbPreview', 'Yes');
            }
        }
    }
    //End
    //Product Edit for All producttypes		
    public function ProductEditform($productID, $productRequestID='') {
        $ObjProduct                = new ProductModel();
        $ObjProductReq             = new ProductRequestModel();
        $languageIDs               = $this->ObjView->languageIDs;
        $languageIDs['Current']    = $languageIDs['Content'];
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
		$requestReview             = $this->getSettingValue('multi_vendor_settings', 'review_before_publish');
		$_POST['productAddedBy']   = '1';
        $_POST['businessID']       = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $_POST['productStartTime'] = $this->convertDateForSQL($_POST['productStartTime'], $settingsDateFormat);
        $_POST['productEndTime']   = $this->convertDateForSQL($_POST['productEndTime'], $settingsDateFormat);
		if (!empty($requestReview)){
                    if($_POST['productStatus'] =='Active' || $_POST['productStatus'] =='Inactive'){
                        $_POST['productStatus'] =$_POST['productStatus'] ;
                    }
                    else{
            $_POST['productStatus']    = 'Pending';
                    }
                }
        else {
            $_POST['productStatus']    = $_POST['productStatus'];
        }
        $imageFlag                 = 0;
        if (($_POST["productImageThumb_temp"] == "") && ($_POST["productImage_temp"] == ""))
            $imageFlag = 1;
        if ($imageFlag != 1) {
            if ($_POST["productImageThumb_temp"] != '' && $_POST["productImage_temp"] != '')
                $_POST['imageFlag'] = 1;
            $paramMedia['productImage'] = $_POST['productImage'];
            if ($_POST["productImage_temp"] != '')
                $paramMedia['mainImage'] = $_POST['productImage'];
            else
                $paramMedia['mainImage'] = $ObjProduct->getImageName($_POST['productImage']);
            if (($_POST["productImageThumb"] != '') && ($_POST["productImageThumb_temp"] == '')) {
                $paramMedia['thumbFlag'] = 1;
                $paramMedia['resImage']  = $_POST['hidMainImage'];
            }
            $paramMedia['mainImage_temp']  = $_POST["productImage_temp"];
            $paramMedia['thumbImage_temp'] = $_POST["productImageThumb_temp"];
            $paramMedia['mediaParam']      = $_POST['dataResize'];
            $_POST['mediaParam']           = $_POST['dataResize'];
            $paramMedia['destFolder']      = 'product';
                $paramMedia['productID'] = $productID;
                $_POST['productImage']   = $ObjProduct->generateMedia($paramMedia);
        } else{
            $_POST['productImage'] = $_POST['hidMainImage'];
        }
        $_POST['saveFrom'] = 'business';
        //echo "<pre>"; print_r($_POST); exit;
        $productID = $ObjProduct->saveProduct($languageIDs, $_POST, $productID);
        $this->setMessage("language.msgProductDetailsSave", "success");
        if($productRequestID=='') {
			 $algoliaEnableSettings= $this->getSettingValue('algolia_search_settings', 'algolia_enable');
			 if($algoliaEnableSettings=='Yes'){
				$this->updateAlgoliaRecord($productID) ;
			 }
        }
        $this->setRedirect("product/edit/id/" . $productID . "/");
    }
    //End
    //To save All Products
    public function ProductAddform($productID = '', $productRequestID = '') {
        $ObjProduct                = new ProductModel();
        $ObjProductReq             = new ProductRequestModel();
        $ObjEmailtemplate          = new EmailtemplateModel();
        $ObjBusiness               = new BusinessModel();
        $businessID                = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $languageIDs               = $this->ObjView->languageIDs;
        $languageIDsMail           = $languageIDs;
        $languageIDs['Current']    = $languageIDs['Content'];
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
        $requestReview             = $this->getSettingValue('multi_vendor_settings', 'review_before_publish');
        $_POST['productAddedBy']   = '1';
        $_POST['businessID']       = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $_POST['productStartTime'] = $this->convertDateForSQL($_POST['productStartTime'], $settingsDateFormat);
        $_POST['productEndTime']   = $this->convertDateForSQL($_POST['productEndTime'], $settingsDateFormat);
		if (!empty($requestReview))
            $_POST['productStatus']    = 'Pending';
        else {
            $_POST['productStatus']    = 'Active';
        }
        $productImage              = $_POST['productImage'];
        if (isset($productImage) && $productImage != '') {
            $paramMedia['mainImage']       = $productImage;
            $paramMedia['productImage']    = $_POST['productImage'];
            $paramMedia['destFolder']      = 'product';
            $paramMedia['mediaParam']      = $_POST['dataResize'];
            $_POST['mediaParam']           = $_POST['dataResize'];
            $paramMedia['mainImage_temp']  = $_POST["productImage_temp"];
            $paramMedia['thumbImage_temp'] = $_POST["productImageThumb_temp"];
            $paramMedia['productID'] 	   = $productID;
            $_POST['productImage']   	   = $ObjProduct->generateMedia($paramMedia);
        }
	$_POST['saveFrom'] = 'business';	
        $productID = $ObjProduct->saveProduct($languageIDs, $_POST, "");
        //URL Rewrite Settings		
        $settingsUrlSuffix         = $this->getSettingValue("seo_settings", "product_url_suffix");
        $product_sef_format        = $this->getSettingValue('seo_settings', 'product_sef_format');
        $product_sef_format=    isset($product_sef_format)  ? $product_sef_format   : false;
	//URL Rewrite 
        $args     = array(
            'productUrl' => $_POST['productUrl']
        );
        $SefModel = new SefModel();
        $SefModel->_refreshProductRewrites($languageIDs['AllList'], $productID, $settingsUrlSuffix, $args,'',$product_sef_format, 'insert');
        if($product_sef_format){
            foreach ($_POST['productCategoryID'] as $key => $category) {
                $args['category'] = $category;
                $SefModel->_refreshProductRewrites($languageIDs['AllList'], $productID, $settingsUrlSuffix, $args,'',$product_sef_format, 'insert');
            }
        }
        //URL Rewrite END	
        //SEND MAIL TO ADMIN
        //currency code & value
        $resDefaultCurrency           = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency];
        $languageIDsCustom            = $languageIDs;
        $languageIDsCustom['Current'] = $languageIDs['Default'];
        $emailbody                    = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustom, '', 'product-request-received');
        $from                         = array(
            $emailbody['emailFromEmail'],
            $emailbody['emailFromName']
        );
        $subject                      = $emailbody['emailSubject'];
        $siteName                     = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl                      = $this->getSettingValue('site_settings', 'global_http_url');
        $companyLogo                  = $this->getSettingValue('company_information', 'company_logo');
        $this->ObjView->assign('companyLogo', $companyLogo);
        //email body
//        if (!empty($requestReview))
//            $bodytag = str_replace('{$productKey}', $ObjProductReq->get_default_option_details($productID), $emailbody['emailHtml']);
//        else
//            $bodytag = str_replace('{$productKey}', $ObjProduct->get_default_option_details($productID), $emailbody['emailHtml']);
        $bodytag = str_replace('{$productKey}', $ObjProduct->get_default_option_details($productID), $emailbody['emailHtml']);
        $bodytag = str_replace('{$productTitle}', $_POST['productTitle'], $bodytag);
        $bodytag = str_replace('{$typeofbusiness}', $this->ObjSession->getSession("BUSINESS_NAME"), $bodytag);
        $bodytag = str_replace('{$startDate}', $_POST['productStartTime'], $bodytag);
        $bodytag = str_replace('{$endDate}', $_POST['productEndTime'], $bodytag);
        $bodytag = str_replace('{$siteName}', $siteName, $bodytag);
//        if (!empty($requestReview))
//            $bodytag = str_replace('{$productPrice}', $resDefaultCurrency['currencySymbolLeft'] . $ObjProductReq->get_default_optionprice($productID) . $resDefaultCurrency['currencySymbolRight'], $bodytag);
//        else
//            $bodytag = str_replace('{$productPrice}', $resDefaultCurrency['currencySymbolLeft'] . $ObjProduct->get_default_optionprice($productID) . $resDefaultCurrency['currencySymbolRight'], $bodytag);
        $bodytag = str_replace('{$productPrice}', $this->ObjView->getFormattedCurrency($ObjProduct->get_default_optionprice($productID)), $bodytag);
        $bodytag = str_replace('{$companyLogo}', $companyLogo, $bodytag);
        // print_r($languageIDsCustom);exit;
        $this->ObjView->assign('emailbody', $bodytag);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('siteName', $siteName);
        $this->ObjView->assign('companyLogo', $companyLogo);
        $emailID                       = $this->getSettingValue('site_settings', 'global_notification_email');
        $body                          = $this->ObjCommon->fetch($this->ObjView, "email_templates/Layout.tpl", $languageIDsCustom);
        $mailSettings                  = $this->getSettingValue('mail_settings');
        $mailSettings['smtp_password'] = $this->encryptDecrypt("decrypt", $mailSettings['smtp_password']);
        $ObjMail                       = new Mail($mailSettings);
        $ObjMail->IsHTML();
        $ObjMail->sendMail($from, $emailID, $subject, $body);
        if ($ObjMail->Send()) {
        }
        // SEND MAIL TO MAIN USER
        $resbusinessDetails = $ObjBusiness->getBusinessBasic($this->ObjSession->getSession("BUSINESS_USER_ID"), $languageIDsMail);
        $emailbody          = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsMail, '', 'product-request-thank');
        $from               = array(
            $emailbody['emailFromEmail'],
            $emailbody['emailFromName']
        );
        $subject            = $emailbody['emailSubject'];
        $siteName           = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl            = $this->getSettingValue('site_settings', 'global_http_url');
        $companyLogo        = $this->getSettingValue('company_information', 'company_logo');
        $userName           = $resbusinessDetails['businessCFirstName'] . ' ' . $resbusinessDetails['businessCLastName'];
        $this->ObjView->assign('companyLogo', $companyLogo);
        //email body					
        $bodytag = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
        $bodytag = str_replace('{$userName}', $userName, $bodytag);
        $bodytag = str_replace('{$companyLogo}', $companyLogo, $bodytag);
        $this->ObjView->assign('emailbody', $bodytag);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('siteName', $siteName);
        $this->ObjView->assign('userName', $userName);
        $this->ObjView->assign('companyLogo', $companyLogo);
        $emailID                       = $resbusinessDetails['businessEmail'];
        $body                          = $this->ObjCommon->fetch($this->ObjView, "email_templates/Layout.tpl", $languageIDsMail);
        $mailSettings                  = $this->getSettingValue('mail_settings');
        $mailSettings['smtp_password'] = $this->encryptDecrypt("decrypt", $mailSettings['smtp_password']);
        $ObjMail                       = new Mail($mailSettings);
        $ObjMail->IsHTML();
        $ObjMail->sendMail($from, $emailID, $subject, $body);
        if ($ObjMail->Send()) {
        }
        if (!empty($requestReview)) {
            $this->setMessage($this->getLanguageValue("msgAddProductRequest"), "success");
            $this->setRedirect("product/edit/id/" . $productID . "/");
        } else {
			$algoliaEnableSettings= $this->getSettingValue('algolia_search_settings', 'algolia_enable');
			 if($algoliaEnableSettings=='Yes'){
				$this->updateAlgoliaRecord($productID) ;
			 }
            $this->setMessage($this->getLanguageValue("msgAddProduct"), "success");
            $this->setRedirect("product/edit/id/" . $productID . "/");
        }
    }
    //End
    public function ajaxsaveOrderAction() {
        $ObjProduct         = new ProductModel();
        $productIDWithIndex = json_decode($_POST['order']);
        $ObjProduct->orderoProductUpdate($productIDWithIndex);
        echo 'success';
    }
    //Bind Attribute Form
    public function bindAttributeForm($paramsArray = array(),$attrSetID='',$prevAttrSetID='') {
        $ObjAttribute           = new AttributeModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $ObjProduct             = new ProductModel();
        $productID              = $paramsArray['productID'];
        $productRequestID       = $paramsArray['productRequestID'];
        $bindAttributeForm      = 0;
        if ($productID > 0 || $productRequestID > 0) {
            $bindAttributeForm                        = 1;
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = $productRequestID;
            $customAttributeArray['attributeSetID']   = $ObjProduct->getAttrSetID($productID, $productRequestID);
            $resAttributes                            = $ObjAttribute->listProductAttributes($languageIDs, $customAttributeArray);
            $this->ObjView->assign('productID', $productID);
            $this->ObjView->assign('productRequestID', $productRequestID);
            if ($productRequestID)
                $productID = $productRequestID;
            if ($_POST && isset($paramsArray['excludePostCallback']) && $paramsArray['excludePostCallback'] != 'Yes') {
                $this->ObjView->assign('attributePostBackFlag', '1');
                $this->ObjView->assign('attributePostBackArray', $_POST);
            }
            if (!empty($resAttributes)) {
                $attributeArray = array();
                foreach ($resAttributes as $attributes) {
                    $attributeArray[$attributes['attributeGroupID']]['attributeGroupName']                                                                  = $attributes['name'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrInputType']                             = $attributes['attrInputType'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrName']                                  = $attributes['attrName'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrOptionID'][$attributes['attrOptionID']] = $attributes['attrOptName'];
                    if ($attributes['productID'] == $productID) {
                        if($attrSetID=='' || $attrSetID<=0 || ($attrSetID==$prevAttrSetID && $attrSetID>0 && $prevAttrSetID>0)) {
                            $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrDetValue']       = $attributes['attrDetValue'];
                        }
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrValueID']        = $attributes['attrValueID'];
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['assignedOptionID'][] = $attributes['attrOptionID'];
                    }
                }
                $this->ObjView->assign('resAttributes', $attributeArray);
            }
        }
        $this->ObjView->assign('bindAttributeForm', $bindAttributeForm);
    }
    //Import global attributes listing
    public function importGlobalAttributesAction() {
        $ObjAttribute     = new AttributeModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $scope            = $this->escape($this->decodeUrlString($this->getRequestValue("scope")));
        $productID        = $this->escape($this->getRequestValue("productID"));
        $productRequestID = $this->escape($this->getRequestValue("productRequestID"));
        if ($scope != '' && ($productID > 0 || $productRequestID > 0)) {
            if ($_POST["attributeIDs"] != '') {
                $saveParamArray['attributeIDs']     = $_POST["attributeIDs"];
                $saveParamArray['productID']        = $productID;
                $saveParamArray['productRequestID'] = $productRequestID;
                $ObjAttribute->importGlobalAttributes($languageIDs, $saveParamArray);
                echo '<script type="text/javascript">parent.$.colorbox.close();parent.reloadCustomAttributes(3);</script>';
                exit;
            }
            if (strtolower($scope) == 'user')
                $scope = 'User';
            elseif (strtolower($scope) == 'admin')
                $scope = 'Admin';
            $attributeParams['attributeLevel']            = $scope;
            $attributeParams['excludeImportedAttributes'] = 'Yes';
            $attributeParams['attributeStatus']           = 'Active';
            $attributeParams['productID']                 = $productID;
            $resListAttributes                            = $ObjAttribute->listAttributes($languageIDs, $attributeParams);
            $this->ObjView->assign('resListAttributes', $resListAttributes);
        }
        $this->ObjView->display("ImportGlobalAttributes.tpl");
    }
    //Ajax Reload Custom attributes
    public function ajaxReloadCustomAttributesAction() {
        $productID                         = $this->escape($_POST["productID"]);
        $productRequestID                  = $this->escape($_POST["productRequestID"]);
        $paramArray['productID']           = $productID;
        $paramArray['productRequestID']    = $productRequestID;
        if($_POST["attrSetID"]>0) {
            $paramArray['attributeSetID']      = $this->escape($_POST["attrSetID"]);
            $paramArray['excludePostCallback'] = '';
        } else {
            $paramArray['excludePostCallback'] = 'Yes';
        }        
        $this->bindAttributeForm($paramArray,$paramArray['attributeSetID'],$_POST["prevAttrSetID"]);
        $this->ObjView->assign('productID', $productID);
        $this->ObjView->assign('productRequestID', $productRequestID);
        $this->ObjView->assign('selAttrSetID', $_POST["attrSetID"]);
        $this->ObjView->assign('productReqID', $productRequestID);
        $this->ObjView->display('CustomAttributeAjax.tpl');
    }
    //Custom Attribute save
    public function saveCustomAttribute() {
        $ObjAttribute           = new AttributeModel();
        $productID              = $this->getRequestValue("id");
        $productRequestID       = $this->getRequestValue("reqID");
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($this->ObjForm->isValid('formCustomAttributeAdd', 'submitAttributeDetails')) {
            $ObjAttribute->assignCustomAttributeToProduct($languageIDs, $productID, $_POST, $_FILES, $productRequestID);
            $this->setMessage("language.msgAttributeUpdate", "success");
            if ($productRequestID)
                $this->setRedirect("product/edit/reqID/" . $productRequestID . "/tab/cattr/");
            else
                $this->setRedirect("product/edit/id/" . $productID . "/tab/cattr/");
        }
    }
    //Download Attribute Files
    public function downloadAction() {
        $ObjAttribute           = new AttributeModel();
        $attrValueID            = $this->getRequestValue("id");
        $attrReqValueID         = $this->getRequestValue("reqid");
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($attrValueID || $attrReqValueID) {
            if ($attrReqValueID) {
                $image_loc = "catalog-request";
                $fileName  = $ObjAttribute->getAttributeFile($languageIDs, $attrReqValueID, "Yes");
            } else {
                $fileName  = $ObjAttribute->getAttributeFile($languageIDs, $attrValueID);
                $image_loc = "catalog";
            }
            if (!empty($fileName)) {
                $filePath = __CORE_PUBLIC_PATH . "/uploads/" . $image_loc . "/attributes/";
                header("Pragma: public"); // required 
                header("Expires: 0");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: private", false); // required for certain browsers 
                header("Content-Disposition: attachment; filename=\"" . $fileName . "\";");
                header("Content-Transfer-Encoding: binary");
                ob_clean();
                flush();
                echo file_get_contents($filePath . $fileName);
            }
        }
    }
    //Custom Attribute File Delete
    public function AjaxDestroyCustAttrFileAction() {
        $ObjAttribute           = new AttributeModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $_POST['id']            = $_POST['attrValueID'];
        $_POST['languageIDs']   = $languageIDs;
        $statusUpdate           = $ObjAttribute->deleteCustomAttributeFile($_POST);
    }
    //View Attribute Files
    public function viewFileAction() {
        $ObjAttribute           = new AttributeModel();
        $attrID                 = $this->getRequestValue("aid");
        $valueID                = $this->getRequestValue("vid");
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($attrID > 0 && $valueID > 0) {
            $paramArray['customAttributeID'] = $attrID;
            $paramArray['valueID']           = $valueID;
            $attrDetails                     = $ObjAttribute->listCustomAttributeOptions($languageIDs, $paramArray);
            $attrDetails                     = $attrDetails[0];
            if (!empty($attrDetails) && $attrDetails['file'] != "") {
                $filePath = __CORE_PUBLIC_PATH . "/uploads/attributes/custom/";
                $ext      = $attrDetails['fileType'];
                header("Pragma: public"); // required 
                header("Expires: 0");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: private", false); // required for certain browsers 
                header("Content-Type: $ext");
                header("Content-Transfer-Encoding: binary");
                ob_clean();
                flush();
                echo file_get_contents($filePath . $attrDetails['file']);
            }
        }
    }
    public function ajaxgetDefaultCurrencyAction() {
//        echo $this->getSettingValue('site_settings', 'default_currency');exit;
          echo $this->ObjView->_defaultCurrency;exit;
    }
    public function optionPostback($resProductOptions) {
        $ObjImage = new ImageModel();
        if (!empty($_POST["productRequestID"]))
            $loc = "catalog-request";
        else
            $loc = "catalog";
        if (isset($resProductOptions) && $resProductOptions != '') {
            foreach ($resProductOptions as $reslistOptions) {
                $option_count      = $reslistOptions['realOptionCount'];
                $productImageCount = $_POST["productOptionImageCount" . $option_count];
                $sortOrder         = $reslistOptions['productOptionImageSort'];
                if (!empty($sortOrder)) {
                    $sortOrder = explode(",", $sortOrder);
                }
                $productOptionMedia = array();
                for ($i = 1; $i <= $productImageCount; $i++) {
                    //$productImageType=$_POST["productOptionImage_" .$option_count.'_'. $i . "_temp"];
                    $productImg = $_POST["productOptionImage_" . $option_count . '_' . $i];
                    if ($productImg) {
                        if (!empty($sortOrder)) {
                            $order = array_search($i, $sortOrder) + 1;
                        } else {
                            $order = $i;
                        }
                        $productOptionMedia[$order]['productMedia'] = $productImg;
                        if ($ObjImage->file_exist("uploads/" . $loc . "/product/preview-main/" . $productImg))
                            $productOptionMedia[$order]['productthumb'] = $productImg;
                    }
                }
                if (is_array($productOptionMedia))
                    ksort($productOptionMedia);
                $resProductOptions[$option_count]['media'] = $productOptionMedia;
                $opCount                                   = isset($opCount) ? $opCount : '';
                $opCount++;
            }
        }
        return $resProductOptions;
    }
    //------------- Ecommerce Section Starts Here  ---------------------------------- //
    // CHANGE Product STATUS
    public function ajaxChangeStatusAction() {
        $ObjProduct            = new ProductModel();
        $_POST['changeStatus'] = 'Deleted';
        $did                   = $_POST['did'];
        $statusChange          = $ObjProduct->changeProductStatus($did,$this->ObjSession->getSession("BUSINESS_USER_ID"));
        $this->setMessage("language.msgproductDelete", 3);
        echo 1;
    }
    public function bindOptionForm($paramsArray = array()) {
        $ObjCustom              = new CustomOptionModel();
        $ObjProductReq          = new ProductRequestModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = $paramsArray['productID'];
        $productRequestID       = $paramsArray['productRequestID'];
        $bindOptionForm         = 0;
        if ($productID > 0 || $productRequestID > 0) {
            $bindOptionForm                           = 1;
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = $productRequestID;
            if ($productRequestID) {
                $resUserLevelAttributes = $ObjProductReq->listRequestCustomProductOption($languageIDs, $customAttributeArray);
            } else {
                $resUserLevelAttributes = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
            }
            $resAtrributeInputTypes = $ObjCustom->listAtrributeInputTypes($this->ObjView->_languageXML, 'Yes');
            $attributeRules         = $ObjCustom->attributeRules($this->ObjView->_languageXML);
            $this->ObjView->assign('attributeRules', $attributeRules);
            $this->ObjView->assign('resAtrributeInputTypes', $resAtrributeInputTypes);
            $this->ObjView->assign('productID', $productID);
            $this->ObjView->assign('productRequestID', $productRequestID);
            if ($_POST && isset($paramsArray['excludePostCallback']) && $paramsArray['excludePostCallback'] != 'Yes') {
                $this->ObjView->assign('attributePostBackFlag', '1');
                $this->ObjView->assign('attributePostBackArray', $_POST);
            }
        }
        $this->ObjView->assign('resUserLevelAttributes', $resUserLevelAttributes);
        $this->ObjView->assign('bindOptionForm', $bindOptionForm);
    }
    public function bindInventoryForm($paramsArray = array()) {
        $ObjCustom              = new CustomOptionModel();
        $ObjProduct             = new ProductModel();
        $ObjProductReq          = new ProductRequestModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = $paramsArray['productID'];
        $productRequestID       = $paramsArray['productRequestID'];
        $bindOptionForm         = 0;
        if ($productID > 0 || $productRequestID > 0) {
            $bindInventoryForm                        = 1;
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = $productRequestID;
            $customAttributeArray['excludeVariant']   = "Yes";
            $customAttributeArray['status']           = "A";
            if ($productRequestID)
                $resCombAttributes = $ObjProductReq->listRequestCustomProductOption($languageIDs, $customAttributeArray);
            else
                $resCombAttributes = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
            $i = 0;
            foreach ($resCombAttributes as $options) {
                if ($productRequestID)
                    $variantArray = $ObjProductReq->getRequestCustomOptionVariants($languageIDs, $options['customOptionID']);
                else
                    $variantArray = $ObjCustom->getCustomOptionVariants($languageIDs, $options['customOptionID']);
                $resCombAttributes[$i]['variant'] = $variantArray;
                $i++;
            }
            $this->ObjView->assign('resCombAttributes', $resCombAttributes);
            $this->ObjView->assign('productID', $productID);
            $this->ObjView->assign('productRequestID', $productRequestID);
        }
        if ($productRequestID)
            $productCombo = $ObjProductReq->getProductRequestCombination($productRequestID, "Yes", 'All', $languageIDs);
        else {
            $params       = array(
                'productID' => $productID,
                'view' => 'Yes',
                'status' => 'All',
                'languageIDs' => $languageIDs,
                'businessID' => $this->ObjSession->getSession("BUSINESS_USER_ID")
            );
            $productCombo = $ObjCustom->getProductCombination($params);
        }
        $count = 0;
        foreach ($productCombo as $combo) {
            $comboID     = $combo['combinationID'];
            $Combination = '';
            if ($productRequestID)
                $comboArray = $ObjProductReq->getRequestCombinationVariants($languageIDs, $combo['combination']);
            else
                $comboArray = $ObjCustom->getCombinationVariants($languageIDs, $combo['combination']);
            foreach ($comboArray as $combostr) {
                if ($Combination)
                    $Combination .= ",";
                $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
            }
            $productCombo[$count]['ProductCombo'] = $Combination;
            $productCombo[$count]['soldQunatity'] = $ObjProduct->getSoldQuantity($combo['combinationHash']);
            $count++;
        }
        $this->ObjView->assign('resproductCombo', $productCombo);
        $this->ObjView->assign('bindInventoryForm', $bindInventoryForm);
    }
    public function bindShippingForm($paramsArray = array()) {
        $ObjDelzone       = new DeliveryZoneModel();
        $ObjProduct       = new ProductModel();
        $ObjShipMethod    = new ShippingmethodModel();
        $ObjProductReq    = new ProductRequestModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $productID        = $paramsArray['productID'];
        $productRequestID = $paramsArray['productRequestID'];
        $BusinessID       = $paramsArray['BusinessID'];
        $bindShippingForm = 0;
        if ($productID > 0 || $productRequestID > 0) {
            $bindShippingForm = 1;
            $this->ShippingAssign($productID, $productRequestID);
            $shipping_origin_type = $this->getSettingValue('shipping_settings', 'shipping_origin_type');
            $resBasic             = $ObjProduct->getBasicByproductID($productID, $productRequestID);
            $shippingSetting      = $resBasic['shippingSetting'];
            $resBusLoc            = $ObjProduct->getDeliveryBusinessLocations($BusinessID, $languageIDs);
            $this->ObjView->assign('shippingSetting', $shippingSetting);
            if ($shippingSetting)
                $ShipSettingManage = $shippingSetting;
            else {
                if ($shipping_origin_type == 'biz') {
                    $ShipSettingManage = "biz";
                } else {
                    $ShipSettingManage = "admin";
                }
            }
            if ($ShipSettingManage == 'admin') {
                $adminShippingOrigin = "Global : " . $this->getSettingValue('shipping_settings', 'global_shipping_city') . "," . $this->getSettingValue('shipping_settings', 'global_shipping_country') . ",";
                if ($this->getSettingValue('shipping_settings', 'global_shipping_state'))
                    $adminShippingOrigin .= $this->getSettingValue('shipping_settings', 'global_shipping_state') . ",";
                $adminShippingOrigin .= $this->getSettingValue('shipping_settings', 'global_shipping_zipcode');
                $this->ObjView->assign('adminShippingOrigin', $adminShippingOrigin);
                $global = array(
                    '0' => '0',
                    'businessLocID' => '0',
                    '1' => $adminShippingOrigin,
                    'location' => $adminShippingOrigin
                );
                array_unshift($resBusLoc, $global);
            }
            $businessLocID = $resBasic['shippingOrigin'];
            $this->ObjView->assign('businessLocID', $businessLocID);
            $this->ObjView->assign('resBusLoc', $resBusLoc);
            $this->ObjView->assign('shipping_origin_type', $shipping_origin_type);
            $this->ObjView->assign('ShipSettingManage', $ShipSettingManage);
        }
        $this->ObjView->assign('bindShippingForm', $bindShippingForm);
    }
    public function importGlobalOptionAction() {
        $ObjCustom              = new CustomOptionModel();
        $ObjProductReq          = new ProductRequestModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = $this->escape($this->getRequestValue("productID"));
        $productRequestID       = $this->escape($this->getRequestValue("productRequestID"));
        if (($productID > 0 || $productRequestID > 0)) {
            if (isset($_POST["customOptionIDs"]) && $_POST["customOptionIDs"] != '') {
                $saveParamArray['customOptionIDs']  = $_POST["customOptionIDs"];
                $saveParamArray['productID']        = $productID;
                $saveParamArray['productRequestID'] = $productRequestID;
                if ($productRequestID)
                    $ObjProductReq->importGlobalOptionsForRequest($languageIDs, $saveParamArray);
                else
                    $ObjCustom->importGlobalOptions($languageIDs, $saveParamArray);
                echo '<script type="text/javascript">parent.$.colorbox.close();parent.reloadCustomOptions(3);</script>';
                exit;
            }
            $attributeParams['excludeImportedAttributes'] = 'Yes';
            $attributeParams['status']                    = 'A';
            $attributeParams['isGlobal']                  = '1';
            $attributeParams['productID']                 = $productID;
            $attributeParams['productRequestID']          = $productRequestID;
            $resListAttributes                            = $ObjCustom->listCustomOptions($languageIDs, $attributeParams);
            $this->ObjView->assign('resListAttributes', $resListAttributes);
        }
        $this->ObjView->display("ImportGlobalOptions.tpl");
    }
    //Reload global option section	
    public function ajaxReloadCustomOptionAction() {
        $productID                         = $this->escape($_POST["productID"]);
        $productRequestID                  = $this->escape($_POST["productRequestID"]);
        $paramArray['productID']           = $productID;
        $paramArray['productRequestID']    = $productRequestID;
        $paramArray['excludePostCallback'] = 'Yes';
        $this->bindOptionForm($paramArray);
        $this->ObjView->assign('productID', $productID);
        $this->ObjView->assign('optionBlockChange', '1');
        $this->ObjView->assign('productReqID', $productRequestID);
        $this->ObjView->display('ProductCustomOptionAjax.tpl');
    }
    //Custom Attribute save
    public function saveCustomOption() {
        $ObjCustom              = new CustomOptionModel();
        $productID              = $this->getRequestValue("id");
        $productRequestID       = $this->getRequestValue("reqID");
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($this->ObjForm->isValid('formCustomOptionAdd', 'submitOptionDetails')) {              
            $ObjCustom->assignCustomOptionToProduct($languageIDs, $productID, $_POST, $productRequestID);
            $this->setMessage("language.msgOptionUpdate", "success");
            if ($productRequestID)
                $this->setRedirect("product/edit/reqID/" . $productRequestID . "/tab/coption/");
            else
                $this->setRedirect("product/edit/id/" . $productID . "/tab/coption/");
        }
    }
    public function ajaxAddCombinationAction() {
        $ObjCustom                     = new CustomOptionModel();
        $ObjUsergroup                  = new UsergroupModel();
        $ObjProductReq                 = new ProductRequestModel();
        $ObjProduct                    = new ProductModel();
        $ObjImage                      = new ImageModel();
        $languageIDs                   = $this->ObjView->languageIDs;
        $businessID                    = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $languageIDs['Current']        = $languageIDs['Content'];
        $actionForm                    = "formComboAdd";
        $actionButton                  = 'submitCombo';
        $_POST[$actionButton]          = '1';
        $returnData['validationError'] = 'No';
        $params                        = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups                = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'OP') {
            if ($this->ObjForm->isValid($actionForm, $actionButton, false,false)) {
                $resProBasic                    = $ObjProduct->getBasicByproductID($_POST['productID'], $_POST['productRequestID']);
                //$_POST['businessID']            = $resProBasic['businessID'];
                $_POST['businessID']            = $businessID;
                $dataResize['previewHeight']    = $this->getSettingValue('product_cart_settings', 'preview_height');
                $dataResize['previewWidth']     = $this->getSettingValue('product_cart_settings', 'preview_width');
                $dataResize['thumbHeight']      = $this->getSettingValue('product_cart_settings', 'thumb_height');
                $dataResize['thumbWidth']       = $this->getSettingValue('product_cart_settings', 'thumb_width');
                $dataResize['smallthumbWidth']  = $this->getSettingValue('product_cart_settings', 'small_thumb_width');
                $dataResize['smallthumbHeight'] = $this->getSettingValue('product_cart_settings', 'small_thumb_height');
                $_POST['mediaParam']            = $dataResize;
                $rescombo                       = $ObjCustom->addProductCombo($businessID);
                if ($rescombo != 3 && $rescombo != 4) {
                    //selct whole data
                    if ($_POST['productRequestID'])
                        $productCombo = $ObjProductReq->getProductRequestCombination($_POST['productRequestID'], "Yes", 'All', $languageIDs);
                    else {
                        $params       = array(
                            'productID' => $_POST['productID'],
                            'view' => 'Yes',
                            'status' => 'All',
                            'languageIDs' => $languageIDs,
                            'businessID' => $this->ObjSession->getSession("BUSINESS_USER_ID")
                        );
                        $productCombo = $ObjCustom->getProductCombination($params);
                    }
                    $count = 0;
                    foreach ($productCombo as $combo) {
                        $comboID     = $combo['combinationID'];
                        $Combination = '';
                        if ($_POST['productRequestID'])
                            $comboArray = $ObjProductReq->getRequestCombinationVariants($languageIDs, $combo['combination']);
                        else
                            $comboArray = $ObjCustom->getCombinationVariants($languageIDs, $combo['combination']);
                        foreach ($comboArray as $combostr) {
                            if ($Combination)
                                $Combination .= ",";
                            $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                        }
                        $productCombo[$count]['ProductCombo'] = $Combination;
                        $productCombo[$count]['soldQunatity'] = $ObjProduct->getSoldQuantity($combo['combinationHash']);
                        $count++;
                    }
                    $this->ObjView->assign('resproductCombo', $productCombo);
                    $html                  = $this->ObjView->fetch('AddedComboBlock.tpl');
                    $returnData['action']  = 'DB';
                    $returnData['html']    = $html;
                    $returnData['message'] = $rescombo;
                    echo json_encode($returnData);
                    return true;
                } else {
                    $returnData['validationError'] = 'No';
                    $returnData['message']         = $rescombo;
                    echo json_encode($returnData);
                    return true;
                }
            } else {
                $returnData['validationError'] = 'Yes';
                echo json_encode($returnData);
                return true;
            }
        } else {
            $productID                                = $_POST['productID'];
            $productRequestID                         = $_POST['productRequestID'];
            $combinationID                            = $_POST['combinationID'];
            $customAttributeArray['excludeVariant']   = "Yes";
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = $productRequestID;
            if ($productRequestID)
                $resCombAttributes = $ObjProductReq->listRequestCustomProductOption($languageIDs, $customAttributeArray);
            else
                $resCombAttributes = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
            $i = 0;
            foreach ($resCombAttributes as $options) {
                if ($productRequestID)
                    $variantArray = $ObjProductReq->getRequestCustomOptionVariants($languageIDs, $options['customOptionID']);
                else
                    $variantArray = $ObjCustom->getCustomOptionVariants($languageIDs, $options['customOptionID']);
                $resCombAttributes[$i]['variant'] = $variantArray;
                $i++;
            }
            $this->ObjView->assign('resCombAttributes', $resCombAttributes);
            if ($productRequestID) {
                $comboLoc     = "catalog-request";
                $comboDetails = $ObjProductReq->getProductRequestCombinationByID($combinationID);
            } else {
                $comboLoc     = "catalog";
                $comboDetails = $ObjCustom->getProductCombinationByID($combinationID,$this->ObjSession->getSession("BUSINESS_USER_ID"));
            }
            if ($comboDetails['productMedia']) {
                $fileName     = "uploads/" . $comboLoc . "/product-combination/preview-main/" . $comboDetails['productMedia'];
                $MainfileName = "uploads/" . $comboLoc . "/product-combination/large/" . $comboDetails['productMedia'];
                if ($ObjImage->file_exist($fileName)) {
                    $this->ObjView->assign('combothumbPreview', 'Yes');
                    $this->ObjView->assign('comboThumb', $comboDetails['productMedia']);
                }
                if ($ObjImage->file_exist($MainfileName)) {
                    $this->ObjView->assign('hidComboMain', $comboDetails['productMedia']);
                }
            }
            $this->ObjView->assign('productRequestID', $productRequestID);
            $combinationArray = explode('_', $comboDetails['combination']);
            unset($combinationArray[0]);
            $this->ObjView->assign('comboDetails', $comboDetails);
            $this->ObjView->assign('productReqID', $productRequestID);
            $this->ObjView->assign('ComboVar', $combinationArray);
            $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
            $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
            $html                 = $this->ObjView->fetch('AddProductComboBlock.tpl');
            $returnData['action'] = 'Show';
            $returnData['html']   = $html;
            echo json_encode($returnData);
            return true;
        }
    }
    public function ajaxAddShippingAction() {
        $ObjProduct                    = new ProductModel();
        $ObjDelzone                    = new DeliveryZoneModel();
        $ObjShipMethod                 = new ShippingmethodModel();
        $languageIDs                   = $this->ObjView->languageIDs;
        $languageIDs['Current']        = $languageIDs['Content'];
        $ObjTaxclassModel              = new TaxclassModel();
        $actionForm                    = "formShipAdd";
        $actionButton                  = 'submitShip';
        $_POST[$actionButton]          = '1';
        $returnData['validationError'] = 'No';
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'OP') {
            if ($this->ObjForm->isValid($actionForm, $actionButton, false)) {
                $resship = $ObjProduct->addProductShipping();
                if (isset($resship) && $resship != 3) {
                    //selct whole data			
                    $productShip = $ObjProduct->getProductShippings($_POST['productID'], $languageIDs, $_POST['productRequestID']);
                    $this->ObjView->assign('resproductShip', $productShip);
                    $settingsManageShipping = $this->getSettingValue('shipping_settings', 'shipping_origin_type');
                    $this->ObjView->assign('settingsManageShipping', $settingsManageShipping);
                    $adminShippingOrigin = $this->getSettingValue('shipping_settings', 'global_shipping_city') . "," . $this->getSettingValue('shipping_settings', 'global_shipping_country') . "," . $this->getSettingValue('shipping_settings', 'global_shipping_state') . "," . $this->getSettingValue('shipping_settings', 'global_shipping_zipcode');
                    $this->ObjView->assign('adminShippingOrigin', $adminShippingOrigin);
                    $html                  = $this->ObjView->fetch('AddedShippingBlock.tpl');
                    $returnData['action']  = 'DB';
                    $returnData['html']    = $html;
                    $returnData['message'] = $resship;
                    echo json_encode($returnData);
                    exit;
                } else {
                    $returnData['validationError'] = 'No';
                    $returnData['message']         = $resship;
                    echo json_encode($returnData);
                    exit;
                }
            } else {
                $returnData['validationError'] = 'Yes';
                echo json_encode($returnData);
                exit;
            }
        } else {
            $productID        = $_POST['productID'];
            $productRequestID = $_POST['productRequestID'];
            $shippingID       = $_POST['shippingID'];
            $this->ShippingAssign($productID, $productRequestID);
            $shipDetails = $ObjProduct->getProductShippingByID($shippingID, $productRequestID);
            $resTaxClass = $ObjTaxclassModel->listTaxClasses("", "", "", "Active", "product");
            $this->ObjView->assign('resTaxClass', $resTaxClass);
            $dZones = $ObjProduct->getZonesByShippingID($shippingID, $productRequestID);
            if (count($dZones) > 0)
                $dZonesString = implode("~*", $dZones);
            $this->ObjView->assign('shipDetails', $shipDetails);
            $this->ObjView->assign('dZonesString', $dZonesString);
            $html                 = $this->ObjView->fetch('AddProductShipBlock.tpl');
            $returnData['action'] = 'Show';
            $returnData['html']   = $html;
            echo json_encode($returnData);
            exit;
        }
    }
    public function AjaxDestroyComboAction() {
        $ObjCustom   = new CustomOptionModel();
        $_POST['id'] = $_POST['comboID'];
        if (!$_POST['status']) {
            $_POST['status'] = 'D';
        }
        $statusUpdate = $ObjCustom->updateComboStatus($_POST);
        echo "1";
    }
    public function AjaxDestroyShipAction() {
        $ObjProduct       = new ProductModel();
        $_POST['id']      = $_POST['shipID'];
        $productRequestID = $_POST['productRequestID'];
        if (!isset($_POST['status']) || $_POST['status'] == '') {
            $_POST['status'] = 'D';
        }
        $statusUpdate = $ObjProduct->updateProShipStatus($_POST, $productRequestID);
        echo "1";
    }
    public function ShippingAssign($productID, $productRequestID) {
        $ObjDelzone             = new DeliveryZoneModel();
        $ObjProduct             = new ProductModel();
        $ObjShipMethod          = new ShippingmethodModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $businessID             = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $resDelZones            = $ObjDelzone->listDeliveryZones($languageIDs, '', '', '', 'Active', 'options', '', $businessID);
        $resSmService           = $ObjShipMethod->groupSmServices();
        $productShip            = $ObjProduct->getProductShippings($productID, $languageIDs, $productRequestID);
        $this->ObjView->assign('resproductShip', $productShip);
        $this->ObjView->assign('resDelZones', $resDelZones);
        $this->ObjView->assign('resSmService', $resSmService);
        $this->ObjView->assign('productID', $productID);
        $this->ObjView->assign('productRequestID', $productRequestID);
        $adminShippingOrigin = $this->getSettingValue('shipping_settings', 'global_shipping_city') . "," . $this->getSettingValue('shipping_settings', 'global_shipping_country') . "," . $this->getSettingValue('shipping_settings', 'global_shipping_state') . "," . $this->getSettingValue('shipping_settings', 'global_shipping_zipcode');
        $this->ObjView->assign('adminShippingOrigin', $adminShippingOrigin);
        $globalSettingArry                   = array();
        $globalSettingArry['baseCharge']     = $this->getSettingValue('shipping_settings', 'global_shipping_baseCharge');
        $globalSettingArry['maxQty']         = $this->getSettingValue('shipping_settings', 'global_shipping_maxQty');
        $globalSettingArry['extraCharge']    = $this->getSettingValue('shipping_settings', 'global_shipping_extraCharge');
        $globalSettingArry['handlingCharge'] = $this->getSettingValue('shipping_settings', 'global_shipping_handlingCharge');
        $this->ObjView->assign('globalSettingArry', $globalSettingArry);
    }
    public function AjaxShippingTypeUpdateAction() {
        $ObjProduct                    = new ProductModel();
        $actionForm                    = "formShipSet";
        $actionButton                  = 'submitShipSet';
        $_POST[$actionButton]          = '1';
        $returnData['validationError'] = 'No';
        if ($this->ObjForm->isValid($actionForm, $actionButton, false)) {
            $statusUpdate                  = $ObjProduct->updateShippingSettings($_POST);
            $returnData['validationError'] = 'No';
            echo json_encode($returnData);
            exit;
        } else {
            $returnData['validationError'] = 'Yes';
            echo json_encode($returnData);
            exit;
        }
    }
    public function AjaxReloadAddComboAction() {
        $productID              = $_POST['productID'];
        $productRequestID       = $_POST['productRequestID'];
        $ObjCustom              = new CustomOptionModel();
        $ObjProduct             = new ProductModel();
        $ObjProductReq          = new ProductRequestModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($productRequestID)
            $resProductOptionMenu = $ObjProductReq->getProductRequestOptionsDetails($languageIDs, $productRequestID);
        else
            $resProductOptionMenu = $ObjProduct->getProductOptionsDetails($languageIDs, $productID);
        $this->ObjView->assign('resProductOptionMenu', $resProductOptionMenu);
        $customAttributeArray['excludeVariant']   = "Yes";
        $customAttributeArray['productID']        = $productID;
        $customAttributeArray['productRequestID'] = $productRequestID;
        if ($productRequestID)
            $resCombAttributes = $ObjProductReq->listRequestCustomProductOption($languageIDs, $customAttributeArray);
        else
            $resCombAttributes = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
        $i = 0;
        foreach ($resCombAttributes as $options) {
            if ($productRequestID)
                $variantArray = $ObjProductReq->getRequestCustomOptionVariants($languageIDs, $options['customOptionID']);
            else
                $variantArray = $ObjCustom->getCustomOptionVariants($languageIDs, $options['customOptionID']);
            $resCombAttributes[$i]['variant'] = $variantArray;
            $i++;
        }
        $combinationArray = array();
        $this->ObjView->assign('ComboVar', $combinationArray);
        $this->ObjView->assign('resCombAttributes', $resCombAttributes);
        $optionCount = count($resCombAttributes);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
        $html                = $this->ObjView->fetch('AddProductComboBlock.tpl');
        $returnData['html']  = $html;
        $returnData['count'] = $optionCount;
        echo json_encode($returnData);
        return true;
    }
    //List Requests
    public function requestAction() {
		
        $ObjProduct             = new ProductModel();
        $ObjProductList         = new ProductListModel();
        $ObjProductCategory     = new ProductCategoryModel();
        $ObjCustomOption        = new CustomOptionModel();
        $ObjBrand               = new BrandModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $settingsDateFormat     = $date_format = $this->getSettingValue('site_settings', 'date_format');
        $time_format            = $this->getSettingValue('site_settings', 'time_format');
        $link                   = '';
        //status
        if (isset($_REQUEST['submitProductInline'])) {
            if ($this->ObjForm->isValid('formProduct', 'submitProductInline')) {
                if ($_POST['optionIDsString'] != '') {
                    $productOptionIDS = explode("_", $_POST['optionIDsString']);
                    foreach ($productOptionIDS as $key => $optionID) {
                        if (isset($_POST['itemPrice_' . $optionID])) {
                            $optionParams                              = array();
                            $optionParams['productOptionQuantity']     = '';
                            $optionParams['optionSKU']                 = '';
                            if(isset($_POST['optionSKU_' . $optionID])) {
                                 $optionParams['optionSKU']            = $_POST['optionSKU_' . $optionID];
                            }                           
                            $optionParams['productOptionRegularPrice'] = $_POST['itemPrice_' . $optionID];
                            $optionParams['productOptionProductPrice'] = ($_POST['salePrice_' . $optionID] != '') ? $_POST['salePrice_' . $optionID] : $_POST['itemPrice_' . $optionID];
                            if(isset($_POST['optionQuantity_' . $optionID])) {
                                $optionParams['productOptionQuantity']     = isset($_POST['optionQuantity_' . $optionID]) ? $_POST['optionQuantity_' . $optionID] : "0";
                            }
                            $optionParams['businessID']                = $this->ObjSession->getSession("BUSINESS_USER_ID");
                            $resUpdate                                 = $ObjProduct->updateProductsOptionsDetails($optionID, $optionParams);
                        }
                    }
                }
                if ($_POST['combinationIDsString'] != '') {
                    $combinationIDS = explode("_", $_POST['combinationIDsString']);
                    foreach ($combinationIDS as $key => $combination) {
                        if (isset($_POST['combinationPrice_' . $combination])) {
                            $combinationParams                             = array();
                            $combinationParams['combinationSKU']           = '';
                            $combinationParams['combinationQty']           = '';
                            if(isset($_POST['combinationSKU_' . $combination])) {
                                 $combinationParams['combinationSKU']      = $_POST['combinationSKU_' . $combination];
                            }                                
                            $combinationParams['combinationPrice']         = $_POST['combinationPrice_' . $combination];
                            $combinationParams['combinationPriceDiffType'] = $_POST['combinationPriceDiffType_' . $combination];
                            if(isset($_POST['combinationQuantity_' . $combination])) {
                                $combinationParams['combinationQty']           = isset($_POST['combinationQuantity_' . $combination]) ? $_POST['combinationQuantity_' . $combination] : "0";
                            }
                            $combinationParams['businessID']               = $this->ObjSession->getSession("BUSINESS_USER_ID");
                            $resUpdate                                     = $ObjProduct->updateProductsCombinationsDetails($combination, $combinationParams);
                        }
                    }
                }
                if ($_POST['combinationIDsString'] != '' || $_POST['optionIDsString'] != '') {
                    $this->setMessage("language.lblRecordsUpdated", 3);
                    $this->setRedirect();
                }
            } else {
                $this->ObjView->assign('validated', 'No');
            }
        } else if (isset($_REQUEST['changeStatus'])) {
            $checkProductIDsCount = count($_REQUEST['checkProductIDs']);
            for ($i = 0; $i < $checkProductIDsCount; $i++) {
                $productID    = $_REQUEST['checkProductIDs'][$i];
                $changestatus = $ObjProduct->changeProductStatus($productID,$this->ObjSession->getSession("BUSINESS_USER_ID"));
            }
            if ($changestatus && $_POST['changeStatus'] == "Deleted") {
                $this->setMessage("language.msgproductDelete", 3);
            } else {
                if ($changestatus) {
                    $this->setMessage("language.msgProductUpdateStatus", 3);
                }
            }
            $this->setRedirect();
        } else if (isset($_POST['submitProductSearch'])) {
            $searchProductID   = isset($_POST['searchProductID']) ? $_POST['searchProductID'] : '';
            $searchOption      = $_POST['searchOption'];
            $brandID           = (int) $_POST['brandID'];
            $searchProductName = strtolower(trim($_POST['searchProductName']));
            $pos               = strpos($searchProductName, "/");
            if ($pos != false) {
                $searchProductName = substr($searchProductName, 0, strrpos($searchProductName, "/"));
            }
            $searchProductName         = $this->encodeUrlString($searchProductName);
            $searchProductType         = isset($_POST['searchProductType']) ? $_POST['searchProductType'] : '';
            if ($_POST['searchProductDate'] != '') {
                if (strpos($_POST['searchProductDate'], " - ")) {
                    $searchDates = explode(' - ', $_POST['searchProductDate']);
                    $fromDate    = $searchDates[0];
                    if (isset($searchDates[1]))
                        $toDate = $searchDates[1];
                } else {
                    $fromDate = $toDate = $_POST['searchProductDate'];
                }
                $searchProductFromDate = trim($fromDate);
                $searchProductToDate   = trim($toDate);
            }
            $sortByOption  = isset($_POST['sortByOption']) ? $_POST['sortByOption'] : '';
            $sortByOrder   = isset($_POST['sortByOrder']) ? $_POST['sortByOrder'] : '';
            $productStatus = $_POST['productStatus'];
            //***********SALES REP*************//
            $searchRep     = isset($_POST['salesRep']) ? $_POST['salesRep'] : '';
            if (!empty($searchRep))
                $searchSalesRep = implode(":", $searchRep);
            //***********END SALES REP*************//
            $productCurrency = isset($_POST['productDefaultCurrency']) ? $_POST['productDefaultCurrency'] : '';
            if ($productStatus == 'Select Status') {
                $productStatus = '';
            }
            if ($searchProductID > 0) {
                $link .= "key/" . $searchProductID . "/";
            }
            if ($searchProductName != '') {
                $link .= "name/" . $searchProductName . "/";
            }        
            if (isset($searchProductFromDate) && $searchProductFromDate != '') {
                $link .= "from/" . $this->urlDate($searchProductFromDate, 'set', $settingsDateFormat) . "/";
            }
            if (isset($searchProductToDate) && $searchProductToDate != '') {
                $link .= "to/" . $this->urlDate($searchProductToDate, 'set', $settingsDateFormat) . "/";
            }
            if ($sortByOption) {
                $link .= "sortby/" . $sortByOption . "/";
            }
            if ($sortByOrder) {
                $link .= "orderby/" . $sortByOrder . "/";
            }
            if ($productStatus) {
                $link .= "dstatus/" . $productStatus . "/";
            }
            if (isset($_POST['searchGlobalKeyword']) && $_POST['searchGlobalKeyword'] != '') {
                $link .= "gkeyword/" . $_POST['searchGlobalKeyword'] . "/";
            }
            if ($searchOption) {
                $link .= "sType/" . $searchOption . "/";
            }
            $this->setRedirect("product/request/" . $link);
        }
        $searchProductID           = $this->getRequestValue("key");
        $searchProductName         = $this->decodeUrlString($this->getRequestValue("name"));
        $searchProductFromDate     = $this->urlDate($this->getRequestValue("from"), 'get', $settingsDateFormat);
        $searchProductToDate       = $this->urlDate($this->getRequestValue("to"), 'get', $settingsDateFormat);
        $sortByOption              = $this->getRequestValue("sortby");
        $sortByOrder               = $this->getRequestValue("orderby");
        $productStatus             = $this->getRequestValue("dstatus");
        $searchGlobalKeyword       = $this->getRequestValue("gkeyword");
        $searchType                = $this->getRequestValue("sType");
        if (isset($searchStatus) && $searchStatus != '') {
            $link .= "status/" . $searchStatus . "/";
        }
        if ($searchProductID > 0) {
            $link .= "key/" . $searchProductID . "/";
        }
        if ($searchProductName != '') {
            $link .= "name/" . $this->encodeUrlString($searchProductName) . "/";
        }
        if ($searchProductFromDate) {
            $link .= "from/" . $this->urlDate($searchProductFromDate, 'set', $settingsDateFormat) . "/";
        }
        if ($searchProductToDate) {
            $link .= "to/" . $this->urlDate($searchProductToDate, 'set', $settingsDateFormat) . "/";
        }
        if ($productStatus) {
            $link .= "dstatus/" . $productStatus . "/";
        }
        if ($searchGlobalKeyword) {
            $link .= "gkeyword/" . $searchGlobalKeyword . "/";
        }
        if ($searchType) {
            $link .= "stype/" . $searchType . "/";
        }
        //$link .= "list";
        if ($sortByOption == 'skey' && $sortByOrder == "asc") {
            $sortByOrderProductKey = "desc";
        } else {
            $sortByOrderProductKey = "asc";
        }
        if ($sortByOption == "stitle" && $sortByOrder == "asc") {
            $sortByOrderProductTitle = "desc";
        } else {
            $sortByOrderProductTitle = "asc";
        }
        if ($sortByOption == 'screated' && $sortByOrder == "asc") {
            $sortByOrderDate = "desc";
        } else {
            $sortByOrderDate = "asc";
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'requestedBy' => 'admin',
            'languageIDs' => $languageIDs,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'sortBy' => $sortByOption,
            'orderBy' => $sortByOrder,
			'businessID' => $this->ObjSession->getSession("BUSINESS_USER_ID"),
            'searchProductKeyword' => $searchProductName,
            'searchProductFromDate' => $this->convertDateForSQL($searchProductFromDate, $settingsDateFormat),
            'searchProductToDate' => $this->convertDateForSQL($searchProductToDate, $settingsDateFormat),
            'searchProductStatus' => $productStatus,
            'searchGlobalKeyword' => $searchGlobalKeyword,
            'productAddedBy' => '1'
        );
        $resProducts   = $ObjProductList->listRequestedProducts($params);
        $resPagesCount = $this->setPagesCount($key = 'page');
        if (count($resProducts) > 0) {
            foreach ($resProducts as $key => $products) {
                if ($products['InventoryTrackLevel'] == 'No') {
                    $outOfStock = 'No';
                } else {
                    $outOfStock = $ObjProductList->checkProductOutOfStock($products['productID'], isset($products['productQuantityNotifyAt']) ? $products['productQuantityNotifyAt'] : 0, $products['InventoryTrackLevel']);
                }
                $resProducts[$key]['outOfStock'] = $outOfStock;
                $resProducts[$key]['options']    = $ObjProduct->listProductOptions($languageIDs, $products['productID'], Null, Null, 'list', "", "", "basic");
                $params                          = array(
                    'productID' => $products['productID'],
                    'view' => 'No',
                    'status' => 'A',
                    'languageIDs' => $languageIDs,
                    'purpose' => "basic",
                    'businessID' => $this->ObjSession->getSession("BUSINESS_USER_ID")
                );
                if ($products['multiOptionsAvailable'] != "Yes") {
                    $resProducts[$key]['combination'] = $ObjCustomOption->getProductCombination($params);
                    if (count($resProducts[$key]['combination']) > 0) {
                        $count          = 0;
                        $combinationQty = '';
                        foreach ($resProducts[$key]['combination'] as $combo) {
                            $comboID     = $combo['combinationID'];
                            $Combination = '';
                            if ($combinationQty != '')
                                $combinationQty .= "-";
                            $combinationQty .= $combo['combinationQty'];
                            $comboArray = $ObjCustomOption->getCombinationVariants($languageIDs, $combo['combination']);
                            foreach ($comboArray as $combostr) {
                                if ($Combination)
                                    $Combination .= ",";
                                $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                            }
                            $resProducts[$key]['combination'][$count]['ProductCombo'] = $Combination;
                            $count++;
                        }
                    }
                }
                if ($products['InventoryTrackLevel'] == 'Product') {
                    $optionQty = '';
                    foreach ($resProducts[$key]['options'] as $options) {
                        if ($optionQty != '')
                            $optionQty .= "-";
                        $optionQty .= $options['productOptionQuantity'];
                    }
                    $resProducts[$key]['quantityString'] = $optionQty;
                } else if ($products['InventoryTrackLevel'] == 'Options') {
                    $resProducts[$key]['quantityString'] = isset($combinationQty) ? $combinationQty : '';
                }
            }
        }
        $siteUrl   = $this->getSettingValue('site_settings', 'global_http_url');
        $params    = array(
            'languageIDs' => $languageIDs
        );

        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('sortByOption', $sortByOption);
        $this->ObjView->assign('sortByOrderProductKey', $sortByOrderProductKey);
        $this->ObjView->assign('sortByOrderProductTitle', $sortByOrderProductTitle);
        $this->ObjView->assign('sortByOrderDate', $sortByOrderDate);
        $this->ObjView->assign('productStatus', $productStatus);
        $this->ObjView->assign('searchProductID', $searchProductID);
        $this->ObjView->assign('searchProductName', $searchProductName);
        if ($searchProductToDate == $searchProductFromDate) {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate);
        } else {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate . " - " . $searchProductToDate);
        }

        $this->ObjView->assign('date_format', $date_format);
        $this->ObjView->assign('time_format', $time_format);
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->assign("fromDate", $searchProductFromDate);
        $this->ObjView->assign("toDate", isset($searchProductToDate) ? $searchProductToDate : '');
        $this->ObjView->assign("productDefaultCurrency", isset($productCurrency) ? $productCurrency : '');
        if ($searchType) {
            $this->ObjView->assign('searchOption', $searchType);
        } else {
            $this->ObjView->assign('searchOption', 'basic');
        }
        //*********** END SALES REP*************//
        $this->ObjView->assign('sortByOrder', $sortByOrder);
        $settingEditProduct = $this->getSettingValue('multi_vendor_settings', 'allow_edit_approved_products');
        $this->ObjView->assign('settingEditProduct', $settingEditProduct);
        $this->ObjView->display('ProductRequest.tpl');
    }
    public function productrequestdetailsAction() {
        $businessID = $this->ObjSession->getSession("BUSINESS_USER_ID");
        if (!$businessID) {
            $this->setRedirect('/login/');
        }
        $ObjproductReq    = new ProductRequestModel();
        $ObjCustom        = new CustomOptionModel();
        $ObjBusiness      = new BusinessModel();
        $ObjProduct       = new ProductModel();
        $ObjAttr          = new AttributeModel();
        $currRootPath     = $this->ObjView->_root_path;
        $languageIDs      = $this->ObjView->languageIDs;
        $productRequestID = $this->getRequestValue("id");
        $languageID       = $languageIDs['Default'];
        $dateFormat       = $this->getSettingValue('site_settings', 'date_format');
        $timeFormat       = $this->getSettingValue('site_settings', 'time_format');
        if ($productRequestID) {
            $param['languageIDs']       = $languageIDs;
            $param['selectedProductID'] = $productRequestID;
            $resSelectproduct           = $ObjproductReq->getProductRequestDetails($param);
            $resSelectproduct           = $resSelectproduct[0];
            if ($resSelectproduct['businessID'] != $businessID) {
                $this->setRedirect("product/request/");
            }
            $resProductcategory = $ObjproductReq->listProductRequestTocategoryDetails($languageIDs, $productRequestID);
            $this->ObjView->assign('resProductcategory', $resProductcategory);
            $resProductOptions = $ObjproductReq->listProductReqOptions($languageIDs, $productRequestID, "", "", 'list');
            //optionmedia		
            $opCount           = 0;
            foreach ($resProductOptions as $reslistOptions) {
                $productOptionMedia                   = $ObjproductReq->listRequestOptionMedia($reslistOptions['productRequestOptionID']);
                $resProductOptions[$opCount]['media'] = $productOptionMedia;
                $opCount++;
            }
            //optionmedia
            //ATTRIBUTE SECTION//
            $customAttributeArray['productRequestID'] = $productRequestID;
            $customAttributeArray['attributeSetID']   = $ObjProduct->getAttrSetID('', $productRequestID);
            $resAttributes                            = $ObjAttr->listProductAttributes($languageIDs, $customAttributeArray);
            //print_r($resAttributes);
            if (isset($resAttributes)) {
                $attributeArray = array();
                foreach ($resAttributes as $attributes) {
                    $attributeArray[$attributes['attributeGroupID']]['attributeGroupName']                                                                  = $attributes['name'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrInputType']                             = $attributes['attrInputType'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrName']                                  = $attributes['attrName'];
                    $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrOptionID'][$attributes['attrOptionID']] = $attributes['attrOptName'];
                    if ($attributes['productID'] == $productRequestID) {
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrDetValue']       = $attributes['attrDetValue'];
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['attrValueID']        = $attributes['attrValueID'];
                        $attributeArray[$attributes['attributeGroupID']]['attributes'][$attributes['attributeID']]['assignedOptionID'][] = $attributes['attrOptionID'];
                    }
                }
            }
            $this->ObjView->assign('resAttributes', $attributeArray);
            //ATTRIBUTE SECTION//
            //Custom Option
            $customAttributeArray['productID'] = $productRequestID;
            $resUserLevelAttributes            = $ObjproductReq->listRequestCustomProductOption($languageIDs, $customAttributeArray);
            $optcount                          = 0;
            foreach ($resUserLevelAttributes as $customOption) {
                if ($customOption['inputType'] == 'select' || $customOption['inputType'] == 'multiselect') {
                    $customParamArray['customOptionID']           = $customOption['customOptionID'];
                    $resUserLevelAttributes[$optcount]['variant'] = $ObjproductReq->getRequestCustomOptionVariants($languageIDs, $customOption['customOptionID']);
                }
                $optcount++;
            }
            $resAtrributeInputTypes = $ObjCustom->listAtrributeInputTypes($this->ObjView->_languageXML, 'Yes');
            $this->ObjView->assign('resAtrributeInputTypes', $resAtrributeInputTypes);
            $this->ObjView->assign('resUserLevelAttributes', $resUserLevelAttributes);
            //custom option
            //INVENTORY	
            $productCombo = $ObjproductReq->getProductRequestCombination($productRequestID, "Yes", 'All', $languageIDs);
            $count        = 0;
            foreach ($productCombo as $combo) {
                $comboID     = $combo['combinationID'];
                $Combination = '';
                $comboArray  = $ObjproductReq->getRequestCombinationVariants($languageIDs, $combo['combination']);
                foreach ($comboArray as $combostr) {
                    if ($Combination)
                        $Combination .= ",";
                    $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                }
                $productCombo[$count]['ProductCombo'] = $Combination;
                $productCombo[$count]['ComboImage']   = $ObjCustom->getComboImageByID($comboID, 'request');
                $count++;
            }
            $this->ObjView->assign('resproductCombo', $productCombo);
            //INVENTORY	
            //shipping//
            $productShip = $ObjProduct->getProductShippings('', $languageIDs, $productRequestID);
            $this->ObjView->assign('resproductShip', $productShip);
            //shipping//	
            $resBusiness               = $ObjBusiness->getBusinessBasic($resSelectproduct['businessID'], $languageIDs);
            $previousURl               = $this->getPreviousURL();
            $citySpecificMultiCurrency = $this->getSettingValue('product_cart_settings', 'city_specific_multi_currency');
            $this->ObjView->assign('citySpecificMultiCurrency', $citySpecificMultiCurrency);
            $this->ObjView->assign('backref', $previousURl);
            $this->ObjView->assign('resSelectproduct', $resSelectproduct);
            $this->ObjView->assign('resProductOptions', $resProductOptions);
            $this->ObjView->assign('date_format', $dateFormat);
            $this->ObjView->assign('time_format', $timeFormat);
            $this->ObjView->assign('productRequestID', $productRequestID);
            $this->ObjView->assign('resBusiness', $resBusiness);
            $this->ObjView->assign('curr_root_path', $currRootPath);
            $settingEditProduct = $this->getSettingValue('multi_vendor_settings', 'allow_edit_approved_products');
            $this->ObjView->assign('settingEditProduct', $settingEditProduct);
            $this->ObjView->display('ProductRequestDetails.tpl');
        } else {
            $this->setRedirect('/product/request/');
        }
    }
    //FUNCTION TO LIST ALL REVIEWS
    public function reviewAction() {
        $businessID = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $link       = '';
        if (!$businessID) {
            $this->setRedirect('/login/');
        }
        $ObjProductReview   = new ProductreviewModel();
        $ObjBusiness        = new BusinessModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $defaultLanguageID  = $languageIDs['Default'];
        $settingsDateFormat = $this->getSettingValue('site_settings', 'date_format');
        if (isset($_POST['submitProductReviewSearch'])) {
            $searchProductName = $this->encodeUrlString($_POST['searchProductName']);
            $searchUserName    = $this->encodeUrlString(trim($_POST['searchUserName']));
            if ($_POST['searchProductFromDate'] != '') {
                if (strpos($_POST['searchProductFromDate'], " - ")) {
                    $searchDates = explode(' - ', $_POST['searchProductFromDate']);
                    $fromDate    = $searchDates[0];
                    if (isset($searchDates[1]))
                        $toDate = $searchDates[1];
                } else {
                    $fromDate = $toDate = $_POST['searchProductFromDate'];
                }
                $searchProductFromDate = trim($fromDate);
                $searchProductToDate   = trim($toDate);
            }
            $status = $_POST['status'];
            if ($searchProductName) {
                $link .= "name/" . $searchProductName . "/";
            }
            if ($searchUserName) {
                $link .= "user/" . $searchUserName . "/";
            }
            if (isset($searchProductFromDate)) {
                $link .= "from/" . $this->urlDate($searchProductFromDate, 'set', $settingsDateFormat) . "/";
            }
            if (isset($searchProductToDate)) {
                $link .= "to/" . $this->urlDate($searchProductToDate, 'set', $settingsDateFormat) . "/";
            }
            if (isset($status) && $status != '') {
                $link .= "status/" . $status . "/";
            }
            if ($sortby = $this->getRequestValue("sortby")) {
                $link .= "sortby/" . $sortby . "/";
            }
            if ($orderby = $this->getRequestValue("orderby")) {
                $link .= "orderby/" . $orderby . "/";
            }
            $this->setRedirect("product/review/" . $link);
        } else {
            $searchProductName     = $this->decodeUrlString($this->getRequestValue("name"));
            $searchUserName        = $this->decodeUrlString($this->getRequestValue("user"));
            $searchProductFromDate = $this->urlDate($this->getRequestValue("from"), 'get', $settingsDateFormat);
            $searchProductToDate   = $this->urlDate($this->getRequestValue("to"), 'get', $settingsDateFormat);
            $status                = $this->getRequestValue("status");
            $sortby                = $this->getRequestValue("sortby");
            $orderby               = $this->getRequestValue("orderby");
            if(strtolower($orderby)!='asc' &&  strtolower($orderby)!='desc') {
                $orderby = 'asc';
            }
            if ($searchProductName) {
                $link .= "name/" . $this->encodeUrlString($searchProductName) . "/";
            }
            if ($searchUserName) {
                $link .= "user/" . $searchUserName . "/";
            }
            if ($searchProductFromDate) {
                $link .= "from/" . $this->urlDate($searchProductFromDate, 'set', $settingsDateFormat) . "/";
            }
            if ($searchProductToDate) {
                $link .= "to/" . $this->urlDate($searchProductToDate, 'set', $settingsDateFormat) . "/";
            }
            if ($status) {
                $link .= "status/" . $status . "/";
            }
            $link .= "list";
        }
        // pagination settings
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page'); //NO OF RECORDS PER PAGE
        $params['languageIDs']      = $languageIDs;
        $params['limitFrom']        = $limitFrom;
        $params['limitTo']          = $limitTo;
        $params['status']           = $status;
        $params['productName']      = $searchProductName;
        $params['user']             = $searchUserName;
        $params['fromDate']         = $this->convertDateForSQL($searchProductFromDate, $settingsDateFormat);
        $params['toDate']           = $this->convertDateForSQL($searchProductToDate, $settingsDateFormat);
        $params['search']           = array(
            "sortby" => $sortby,
            "orderby" => $orderby
        );
        $params['businessID']       = $businessID;
        $resAllProductReviewDetails = $ObjProductReview->getAllProductReviewDetails($params);
        $resPagesCount              = $this->setPagesCount($key = 'page');
        $resMerchantReviewCount     = $ObjBusiness->getMerchantReviewCount('', $businessID);
        $this->ObjView->assign('sortby', $sortby);
        $this->ObjView->assign('orderby', $orderby);
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('resAllProductReviewDetails', $resAllProductReviewDetails);
        $this->ObjView->assign('searchProductName', $searchProductName);
        $this->ObjView->assign('searchUserName', $searchUserName);
        if ($searchProductToDate == $searchProductFromDate) {
            $this->ObjView->assign('searchProductFromDate', $searchProductFromDate);
        } else {
            $this->ObjView->assign('searchProductFromDate', $searchProductFromDate . " - " . $searchProductToDate);
        }
        $this->ObjView->assign('status', $status);
        $this->ObjView->assign('selectOption', 'productreview');
        $this->ObjView->assign('resMerchantReviewCount', $resMerchantReviewCount);
        $this->ObjView->display('ProductReview.tpl');
    }
    //END OF FUNCTION
    //To check ProductUrl already exist	
    function checkUrlExist($test) {
        $ObjProduct = new ProductModel();
        if (!$ObjProduct->isProductUrlAlreadyExists($_POST['productUrl'], $_POST['productID'])) {
            return true;
        } else {
            return false;
        }
    }
    //To check ProductUrl already exist.  for Callback validdation in product list and edit.	
    function checkOptSKUexist($data) {
        $SKU              = $data['value'];
        $count            = 1;
        $productRequestID = isset($_POST['productRequestID']) ? $_POST['productRequestID'] : "";
        $businessID       = isset($_POST['businessID']) ? $_POST['businessID'] : 0;
        if (count($data['siblingPostArray']) > 0) {
            $option_id = $data['siblingPostArray']['option_id'];
        } else {
            $fieldName = $data['field'];
            $tempArray = explode("_", $fieldName);
            $option_id = $tempArray[1];
        }
        $productOptionID = ($option_id > 0) ? $option_id : 0;
        $ObjProduct      = new ProductModel();
        if ($productOptionID > 0 && $businessID < 1) {
            $businessID = $ObjProduct->getBusinessIDByProductOptionID($productOptionID);
        }
        if ($productOptionID == 0) {
            $sku_arry = $ObjProduct->array_column($_POST['productOptionsGroup'], 'optionSKU');
            $counts   = array_count_values($sku_arry);
            $count    = $counts[$SKU];
        }
        if ($count != 1)
            return false;
        if (!$ObjProduct->isProductSkuAlreadyExists($SKU, $productOptionID, $productRequestID, $businessID)) {
            return true;
        } else {
            return false;
        }
    }
    public function usergroupprice($params) {
        return true;
    }
    public function tierprice_quantity($params) {
        return true;
    }
    public function tierprice_price($params) {
        return true;
    }
    //To check ProductUrl already exist.  for Callback validdation in product list and edit.	
    function checkComSKUexist($data) {
        $SKU = $data['value'];
        //echo '<pre>';print_r($data);
        if (count($data['siblingPostArray']) > 0) {
            $option_id = $data['siblingPostArray']['option_id'];
        } else {
            $fieldName = $data['field'];
            $tempArray = explode("_", $fieldName);
            $option_id = $tempArray[1];
        }
        if ($option_id > 0)
            $combinationID = $option_id;
        else
            $combinationID = '';
        $ObjProduct = new ProductModel();
        if (!$ObjProduct->isCombinationSkuAlreadyExists($SKU, $combinationID)) {
            return true;
        } else {
            return false;
        }
    }
    public function ajaxListProductsAction() {
        //initialize object
        $ObjProduct                      = new ProductModel();
        $ObjPro                          = new ProductListModel();
        $ObjProductCategory              = new ProductCategoryModel();
        $languageIDs                     = $this->ObjView->languageIDs;
        $languageIDs['Current']          = $languageIDs['Content'];
        $productID                       = $_POST['productID'];
        $searchItems                     = explode('|', $_POST['searchItem']);
        $searchKeyword                   = $searchItems[0];
        $searchItems                     = implode(',', array_slice($searchItems, 1));
        $searchSetID                     = isset($_POST['searchSetID']) ? $_POST['searchSetID'] : '';
        $searchType                      = isset($_POST['type']) ? $_POST['type'] : '';
        $resListUpcomingProducts         = '';
        $paramArray                      = array();
        $paramArray['currentLanguageID'] = $languageIDs['Current'];
        $paramArray['productID']         = $productID;
        $paramArray['businessID']        = $this->ObjSession->getSession("BUSINESS_USER_ID");
        ;
        $paramArray['searchKeyword'] = $searchKeyword;
        $paramArray['searchItems']   = $searchItems;
        $paramArray['searchSetID']   = $searchSetID;
        $paramArray['selectOpt']     = "L";
        $paramArray['productStatus'] = 'Active';
        $resLeftList                 = $ObjPro->getProductsForRelated($paramArray);
        $resCategoryTree             = $ObjProductCategory->listProductCategoryItems($languageIDs, 0);
        $resCategoryTree             = array_slice($resCategoryTree, 1);
        $this->ObjView->assign('searchItems', $searchItems);
        if ($_POST['searchItem'] != '' || $searchSetID != '')
            $this->ObjView->assign('searchAnyItem', 1);
        $this->ObjView->assign('searchKeyword', $searchKeyword);
        $this->ObjView->assign('resCategoryTree', $resCategoryTree);
        $this->ObjView->assign('resListUpcomingProducts', $resLeftList);
        if ($searchType == '')
            $this->ObjView->display('RelatedProductsLeft.tpl');
        elseif ($searchType == 'Up')
            $this->ObjView->display('UpsellProductsLeft.tpl');
        elseif ($searchType == 'Cross')
            $this->ObjView->display('CrosssellProductsLeft.tpl');
    }
    public function ajaxsaveRelatedProductsAction() {
        //initialize object
        $ObjProduct             = new ProductModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = $_POST['productID'];
        $droppedProducts        = $_POST['droppedProducts'];
        $droppedProductIDs      = $this->decodeSplChar($_POST['droppedProducts']);
        if (substr($droppedProductIDs, -2) == '~*') {
            $droppedProductIDs = substr($droppedProductIDs, 0, -2);
        }
        $droppedProductIDs       = explode("~*", $droppedProductIDs);
        $resListUpcomingProducts = $ObjProduct->saveProductProductIDs($productID, $droppedProductIDs);
        if ($resListUpcomingProducts) {
            echo 1;
        }
    }
    public function ajaxsaveSellProductsAction() {
        //initialize object
        $ObjProduct             = new ProductModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = $_POST['productID'];
        $type                   = $_POST['type'];
        $droppedProducts        = $_POST['droppedProducts'];
        $droppedProductIDs      = $this->decodeSplChar($_POST['droppedProducts']);
        if (substr($droppedProductIDs, -2) == '~*') {
            $droppedProductIDs = substr($droppedProductIDs, 0, -2);
        }
        $droppedProductIDs       = explode("~*", $droppedProductIDs);
        $resListUpcomingProducts = $ObjProduct->saveSellProductProductIDs($productID, $droppedProductIDs, $type);
        if ($resListUpcomingProducts) {
            echo 1;
        }
    }
    public function ajaxShippingDefaultUpdateAction() {
        $ObjShippingMethod = new ShippingmethodModel();
        $smGroupID         = $_POST['serviceID'];
        $returnData        = array();
        $smGroupKey        = $ObjShippingMethod->getGroupKeyByID($smGroupID);
        if (strpos($smGroupKey, 'flat_') !== false) {
            $returnData['taxClassID'] = $ObjShippingMethod->getTaxcalassByID($smGroupID);
            $returnData['baseCharge'] = $ObjShippingMethod->getSmsBaseChargeByID($smGroupID);
            $returnData['sType']      = "flat_rate";
        }
        if (strpos($smGroupKey, 'free_') !== false) {
            $returnData['maxQtyPerShipping'] = $ObjShippingMethod->getSmsValueByID($smGroupID, "free_qty_upto");
            $returnData['sType']             = "free";
        }
        $returnData['dZones'] = $ObjShippingMethod->getSmsZoneByID($smGroupID);
        echo json_encode($returnData);
        exit;
    }
    //Bulk Export 
    public function ExportAction() {
        $patternID          = $this->getRequestValue("pattern");
        $ObjExim            = new EximModel();
        $ObjProduct         = new ProductModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $ObjAttr            = new AttributeModel();
        $ObjBrand           = new BrandModel();
        $ObjProductCategory = new ProductCategoryModel();
        /*$resProductCategories      = $ObjProductCategory->listProductCategories($languageIDs, -1);
		
        foreach ($resProductCategories as $key => $value) {
            $categoryTree[$resProductCategories[$key]['productCategoryParent']][] = $resProductCategories[$key];
        }*/
		//echo '<pre>'; 
		//print_r($categoryTree);exit;		
        //$resProductCategories = $this->createCategoryTree($categoryTree, $categoryTree[0]);
        
        //$resCategories      = $ObjProductCategory->listProductCategoryItems($languageIDs, 0);
        
        
        //$resProductCategories = $resCategories;
        $resProductCategories      = $ObjProductCategory->listProductCategories($languageIDs, -1);
		
        foreach ($resProductCategories as $key => $value) {
            $categoryTree[$resProductCategories[$key]['productCategoryParent']][] = $resProductCategories[$key];
        }
		//echo '<pre>'; 
		//print_r($categoryTree);exit;		
        $resProductCategories = $this->createCategoryTree($categoryTree, $categoryTree[0]);		
        $this->ObjView->assign('resCategories', $resProductCategories);
        $resAttrSet         = $ObjAttr->listAttributeSet();
        /*if (is_array($resCategories))
            array_shift($resCategories);
        $this->ObjView->assign('resCategories', $resCategories);*/
        $resAttrSet         = $ObjAttr->listAttributeSet();
        $params     = array(
            'languageIDs' => $languageIDs
        );
        $listBrand  = $ObjBrand->listBrand($params);
        $resAttrSet = $ObjAttr->listAttributeSet();
        $ListAll    = array(
            0 => 'all',
            'attributeSetID' => 'all',
            1 => $this->getLanguageValue("lblAll"),
            'attributeSetName' =>  $this->getLanguageValue("lblAll")
        );
        array_unshift($resAttrSet, $ListAll);
        $this->ObjView->assign('resAttrSet', $resAttrSet);
        $this->ObjView->assign('listBrand', $listBrand);
        $pdtexportArray   = array(
            $this->getLanguageValue("lblExBrand") => "Brand",
            $this->getLanguageValue("lblBoxsize") => "Box size",
            $this->getLanguageValue("lblBarCode") => "Bar Code",
            $this->getLanguageValue("lblMinOrderQty") => "Min Order Quantity",
            $this->getLanguageValue("lblMaxOrderQty") => "Max Order Quantity",
            $this->getLanguageValue("lblStartDate") => "Start Date",
            $this->getLanguageValue("lblEndDate") => "End Date",
            $this->getLanguageValue("lblShowCountDownCounter") => "Show days left",
            $this->getLanguageValue("lblIsFeaturedHot") => "Is Featured/Hot",
            $this->getLanguageValue("lblTrackInventory") => "Track Inventory",
            $this->getLanguageValue("lblProductReturn") => "Product Returnable",
            $this->getLanguageValue("lblReturnPeriod") => "Return Period",
            $this->getLanguageValue("lblAdminCommission") => "Admin Commission",
            $this->getLanguageValue("lblServiceFee") => "Service Fee",
            $this->getLanguageValue("lblStatus") => "Status",
            $this->getLanguageValue("lblPreviewImage") => "Preview Image",
            $this->getLanguageValue("lblDetailedImage") => "Detailed image",
            $this->getLanguageValue("lblTaxClass") => "Tax Class",
            $this->getLanguageValue("lblTaxClassID") => "Tax Class ID",
            $this->getLanguageValue("lblTaxToMer") => "Is tax payable to Merchant",
            $this->getLanguageValue("lblDescription") => "Description",
            $this->getLanguageValue("lblShortDescription") => "Short Description",
            $this->getLanguageValue("lblHighlights") => "Highlights",
            $this->getLanguageValue("lblSearchTags") => "Search Tags",
            $this->getLanguageValue("lblMetaTitle") => "Meta Title",
            $this->getLanguageValue("lblMetaDescription") => "Meta Description",
            $this->getLanguageValue("lblMetaKeywords") => "Meta keyword",
            $this->getLanguageValue("lblMOptions") => "Multiple Options Available",
            $this->getLanguageValue("lblVariants") => "Variants",
            $this->getLanguageValue("lblCustomOptions") => "Custom Options",
            $this->getLanguageValue("lblAttributes") => "Attributes",
            $this->getLanguageValue("lblShippingManage") => "Shipping Manage",
            $this->getLanguageValue("lblShippingOrigin") => "Shipping Origin",
            $this->getLanguageValue("lblDeliveryTime") => "Dispatch Time",
            $this->getLanguageValue("lblShippinginfo") => "Shipping Info",
            $this->getLanguageValue("lblProductID") => "Product ID",
            $this->getLanguageValue("lblEnableSizeChart") => "Enable Size Chart",
            $this->getLanguageValue("lblSizeChart") => "Size Chart",
            $this->getLanguageValue("lblSellAsBatch") => "Sell As Batch",
            $this->getLanguageValue("lblBatchType") => "Batch Type",
            $this->getLanguageValue("lblQuantityPerBatch") => "Quantity Per Batch",
        );
        $comboexportArray = array(
            $this->getLanguageValue("lblBarCode") => "Bar Code",
            $this->getLanguageValue("lblAmount") => "Amount",
            $this->getLanguageValue("lblPriceImpact") => "Price Impact",
            $this->getLanguageValue("lblQuantity") => "Quantity",
            $this->getLanguageValue("lblStatus") => "Status",
            $this->getLanguageValue("lblOptionName") => "Option Name"
        );
        $imagexportArray  = array(
            $this->getLanguageValue("lblProductName") => "Product Name"
        );
        $layout_data      = !empty($_POST['layout_data']) ? $_POST['layout_data'] : array();
        $ctab             = $this->getRequestValue("ctab");
        if ($ctab == 'combo')
            $this->ObjView->assign("ctab", 1);
        elseif ($ctab == 'image')
            $this->ObjView->assign("itab", 1);
        elseif ($ctab == 'pdt') {
            $this->ObjView->assign("ptab", 1);
        }
        //if (!empty($layout_data)) {
        if (!empty($_POST)) {
            $setID                   = $_POST['export_options']['attributeSetID'];
            $businessID              = $this->ObjSession->getSession("BUSINESS_USER_ID");
            $limitTo                 = $_POST['export_options']['limitTo']   = isset($_POST['limitTo'])?$_POST['limitTo']:'';
            $limitFrom               = $_POST['export_options']['limitFrom'] = isset($_POST['limitFrom'])?$_POST['limitFrom']:'';
            $brandID                 = $_POST['export_options']['brandID']   = isset($_POST['brandID'])?$_POST['brandID']:'';
            $searchProductCategories = isset($_POST['filterCategories']) ? $_POST['filterCategories'] : '';
            if ($setID == 'all')
                $setID = '';
            if ($_POST['pattern_id'] == 'products') {
                $resProd      = $ObjProduct->getProductsBysetID($setID, $businessID, $limitFrom, $limitTo, $brandID, $searchProductCategories);
                $count        = count($resProd);
                $preparedSubs = array();
                foreach ($resProd as $subArray) {
                    $preparedSubs[] = $subArray['productID'];
                }
                if ($searchProductCategories) {
                    if (is_array($preparedSubs) && count(array_filter($preparedSubs)) > 0) {
                        $searchProductCategory = implode(",", $preparedSubs);
                    } else {
                        $searchProductCategory = '';
                    }
                } else {
                    $searchProductCategory = '';
                }
                array_unshift($layout_data, "Product SKU", "Product Name", "URL Key", "Variant Title", "List Price", "Price", "Quantity", "Category", "Business name", "Attribute Set name", "Measurement Length", "Measurement Weight");
                $pattern = $ObjExim->getProductSchema($setID, '', $businessID, $brandID, $searchProductCategory,$_POST['export_options']['languageID']);
                $ctab    = "pdt";
            } elseif ($_POST['pattern_id'] == 'product_combinations') {
                $count = $ObjProduct->getComboBysetID($setID, $businessID);
                array_unshift($layout_data, "Product SKU", "Combination SKU", "Combination", "Product ID");
                $pattern = $ObjExim->getCombinationSchema($setID, $businessID);
                $ctab    = "combo";
            } elseif ($_POST['pattern_id'] == "product_images") {
                $count = $ObjProduct->getmediaBysetID($setID, $businessID);
                array_unshift($layout_data, "SKU", "Pair type", "Detailed image", "Preview Image", "Product ID");
                $pattern = $ObjExim->getImagesSchema($setID, $businessID);
                $ctab    = "image";
            }
            if ($count > 0) {
                $ObjExim->export($pattern, $layout_data, $_POST['export_options']);
            } else {
                $this->setMessage("language.msgNoProducts", "message_error");
                $this->ObjView->assign("export_options[attributeSetID]", $_POST['export_options']['attributeSetID']);
                $this->setRedirect("product/export/ctab/" . $ctab . "/");
            }
        }
        $this->ObjView->assign("pdtexportArray", $pdtexportArray);
        $this->ObjView->assign("comboexportArray", $comboexportArray);
        $this->ObjView->assign("imagexportArray", $imagexportArray);
        $this->ObjView->assign("selectOption", 'dexport');
        $this->ObjView->display('ProductExport.tpl');
    }
    //Bulk Import
    public function ImportAction() {
        $patternID                              = $this->getRequestValue("pattern");
        $ObjExim                                = new EximModel();
        $languageIDs                            = $this->ObjView->languageIDs;
        $post_process                           = array();
        $post_process['productTimeZone']        = $this->getSettingValue('site_settings', 'default_timezone');
        $post_process['productDefaultCurrency'] = $this->ObjView->_defaultCurrency;
        $post_process['languageXml']            = $this->ObjView->_languageXML;
		
		$requestReview             = $this->getSettingValue('multi_vendor_settings', 'review_before_publish');
		if (!empty($requestReview))
            $post_process['status']     = 'Pending';
        else {
            $post_process['status']     = 'Inactive';
        }

        $pdtexportArray                         = array(
            $this->getLanguageValue("lblEsku"),
            $this->getLanguageValue("lblProductName"),
            $this->getLanguageValue("lblProductUrl"),
            $this->getLanguageValue("lblEVariantTitle"),
            $this->getLanguageValue("lblEListPrice"),
            $this->getLanguageValue("lblPrice"),
            $this->getLanguageValue("lblDealPrice"),
            $this->getLanguageValue("lblQuantity"),
            $this->getLanguageValue("lblCategory"),
            $this->getLanguageValue("lblBusinessname"),
            $this->getLanguageValue("lblMeasurementLength"),
            $this->getLanguageValue("lblMeasurementWeight"),
            $this->getLanguageValue("lblExBrand"),
            $this->getLanguageValue("lblBoxsize"),
            $this->getLanguageValue("lblBarCode"),
            $this->getLanguageValue("lblMinOrderQty"),
            $this->getLanguageValue("lblMaxOrderQty"),
            $this->getLanguageValue("lblStartDate"),
            $this->getLanguageValue("lblEndDate"),
            $this->getLanguageValue("lblShowCountDownCounter"),
            $this->getLanguageValue("lblIsFeaturedHot"),
            $this->getLanguageValue("lblTrackInventory"),
            $this->getLanguageValue("lblProductReturn"),
            $this->getLanguageValue("lblReturnPeriod"),
            $this->getLanguageValue("lblAdminCommission"),
            $this->getLanguageValue("lblServiceFee"),
            $this->getLanguageValue("lblPreviewImage"),
            $this->getLanguageValue("lblDetailedImage"),
            $this->getLanguageValue("lblTaxClass"),
            $this->getLanguageValue("lblTaxClassID"),
            $this->getLanguageValue("lblTaxToMer"),
            $this->getLanguageValue("lblDescription"),
            $this->getLanguageValue("lblShortDescription"),
            $this->getLanguageValue("lblHighlights"),
            $this->getLanguageValue("lblSearchTags"),
            $this->getLanguageValue("lblMetaTitle"),
            $this->getLanguageValue("lblMetaDescription"),
            $this->getLanguageValue("lblMetaKeywords"),
            $this->getLanguageValue("lblMOptions"),
            $this->getLanguageValue("lblVariants"),
            $this->getLanguageValue("lblCustomOptions"),
            $this->getLanguageValue("lblAttributeSetname"),
            $this->getLanguageValue("lblAttributes"),
            $this->getLanguageValue("lblShippinginfo"),
            $this->getLanguageValue("lblShippingManage"),
            $this->getLanguageValue("lblShippingOrigin"),
            $this->getLanguageValue("lblDeliveryTime"),
            $this->getLanguageValue("lblProductID"),
            $this->getLanguageValue("lblEnableSizeChart") => "Enable Size Chart",
            $this->getLanguageValue("lblSizeChart") => "Size Chart",
            $this->getLanguageValue("lblSellAsBatch") => "Sell As Batch",
            $this->getLanguageValue("lblBatchType") => "Batch Type",
            $this->getLanguageValue("lblQuantityPerBatch") => "Quantity Per Batch",
        );
        $pdt_required                           = array(
            "Product SKU",
            "Product Name",
            "Variant Title",
            "Price",
            "Category",
            "Business name",
            "Attribute Set name",
            "Measurement Length",
            "Measurement Weight"
        );
        $comboexportArray                       = array(
            $this->getLanguageValue("lblProductID"),
            $this->getLanguageValue("lblEsku"),
            $this->getLanguageValue("lblCombinationSKU"),
            $this->getLanguageValue("lblBarCode"),
            $this->getLanguageValue("lblCombination"),
            $this->getLanguageValue("lblAmount"),
            $this->getLanguageValue("lblPriceImpact"),
            $this->getLanguageValue("lblQuantity"),
            $this->getLanguageValue("lblStatus")
        );
        $combo_required                         = array(
            "Product SKU",
            "Combination SKU",
            "Combination",
            "Amount",
            "Quantity"
        );
        $imagexportArray                        = array(
            $this->getLanguageValue("lblProductID"),
            $this->getLanguageValue("lblProductName"),
            $this->getLanguageValue("lblSKU"),
            $this->getLanguageValue("lblPairtype"),
            $this->getLanguageValue("lblPreviewImage"),
            $this->getLanguageValue("lblDetailedImage")
        );
        $img_required                           = array(
            "SKU",
            "Pair type",
            "Detailed image",
            "Preview Image"
        );
        //TAB SETTINGS
        $cstatus                                = $this->getRequestValue("cstatus");
        $ctab                                   = $this->getRequestValue("ctab");
        if ($cstatus == 'imported') {
            if ($this->ObjSession->getSession("error_log") == '1')
                $this->ObjView->assign("error_log", 1);
            $this->ObjView->assign('count_log', $this->ObjSession->getSession("count_log"));
            if ($this->ObjSession->getSession("show_log") == '1')
                $this->ObjView->assign("show_log", 1);
            $this->ObjSession->unsetSession("count_log");
            $this->ObjSession->unsetSession("error_log");
            $this->ObjSession->unsetSession("show_log");
        }
        if ($ctab == 'combo') {
            $this->ObjView->assign("ctab", 1);
            $this->ObjView->assign("pattern", $this->getLanguageValue("lblProductCombos"));
        } elseif ($ctab == 'image') {
            $this->ObjView->assign("itab", 1);
            $this->ObjView->assign("pattern", $this->getLanguageValue("lblProductImages"));
        } else {
            $this->ObjView->assign("ptab", 1);
            $this->ObjView->assign("pattern", $this->getLanguageValue("lblProducts"));
        }
        //TAB SETTINGS
        $layout_data = !empty($_POST['layout_data']) ? $_POST['layout_data'] : array();
        if ($_POST) {
            $post_process['businessID'] = $this->ObjSession->getSession("BUSINESS_USER_ID");
            $post_process['languageID'] = $_POST['import_options']['languageID'];
            $post_process['languageID'] = isset($post_process['languageID']) && $post_process['languageID']!='' ? $post_process['languageID'] : $_POST['import_options']['lang_code'];
            $post_process['languageID'] = isset($post_process['languageID']) && $post_process['languageID']!='' ? $post_process['languageID'] : 1;
            $import_log                 = $ObjExim->import($_POST['pattern_id'], $post_process);
            if ($_POST['pattern_id'] == 'product_combinations')
                $ctab = "combo";
            elseif ($_POST['pattern_id'] == 'product_images')
                $ctab = "image";
            else
                $ctab = "pdt";
        }
        if (isset($import_log['Status']) && $import_log['Status'] == "no_file") {
            $this->setMessage("language.msgeximFileNotUploaded", "message_error");
            $this->setRedirect("product/import/ctab/" . $ctab . "/");
        } elseif (isset($import_log['Status']) && $import_log['Status'] == "import_fail") {
            $error = $this->getLanguageValue('msgeximImportfailed') . " : " . $import_log['Error'];
            $this->setMessage($error, "message_error");
            $this->setRedirect("product/import/ctab/" . $ctab . "/");
        } elseif (isset($import_log['Status'])) {
            if ($import_log['Skipped'] == 'Y')
                $this->ObjSession->setSession("error_log", "1");
            $this->ObjSession->setSession("count_log", $import_log['count_log']);
            $this->ObjSession->setSession("show_log", "1");
            $this->setMessage("language.msgDataImported", "success");
            $this->setRedirect("product/import/ctab/" . $ctab . "/cstatus/imported");
        }
        $this->ObjView->assign("businessID", $this->ObjSession->getSession("BUSINESS_USER_ID"));
        $this->ObjView->assign("pdtexportArray", $pdtexportArray);
        $this->ObjView->assign("pdtReq", $pdt_required);
        $this->ObjView->assign("comboReq", $combo_required);
        $this->ObjView->assign("imgReq", $img_required);
        $this->ObjView->assign("comboexportArray", $comboexportArray);
        $this->ObjView->assign("imagexportArray", $imagexportArray);
        $this->ObjView->assign("selectOption", 'dimport');
        $this->ObjView->display('ProductImport.tpl');
    }
    //To Clone Products 
    public function CloneAction() {
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $pid                    = $this->getRequestValue("id");
        $ObjClone               = new CloneModel();
		$requestReview          = $this->getSettingValue('multi_vendor_settings', 'review_before_publish');
		if (!empty($requestReview)){
            $this->setRedirect("product/index/");
        }
        if (!empty($pid)) {
            $pdata = $ObjClone->fn_clone_product($languageIDs, $pid);
            if (!empty($pdata['product_id'])) {
                $pid = $pdata['product_id'];
                $this->setMessage("language.msgProductCloned", "success");
            }
            $this->setRedirect("product/edit/id/$pid/");
        }
    }
    //Download Error Log
    public function downloadLogAction() {
        $file = __CORE_PUBLIC_PATH . "/uploads/exim/error_log.txt";
        header('Content-type: text/plain');
        header('Content-Length: ' . filesize($file));
        header("Cache-control: private");
        header('Content-Disposition: attachment; filename="error_log.txt"');
        readfile($file);
    }
    //Pre Production//
    public function cleanUrlAction() {
        $ObjCustom = new ProductModel();
        $ObjCustom->cleanUrl();
        exit;
    }
    public function cleanUrlRewriteAction() {
        $ObjCustom = new ProductModel();
        $ObjCustom->cleanUrlRewrite();
        exit;
    }
    public function checkUrlAction() {
        $ObjCustom = new ProductModel();
        $ObjCustom->checkUrl();
        exit;
    }
	 public function quickAddAction() {
        $ObjUsergroup                   = new UsergroupModel();
        $productID                      = $this->getRequestValue("id");
        $productRequestID               = $this->getRequestValue("id");
        $languageIDs                    = $this->ObjView->languageIDs;
		$ObjProductCategory     		= new ProductCategoryModel();
        //Media Settings
        $dataResize['previewHeight']    = $this->getSettingValue('product_cart_settings', 'preview_height');
        $dataResize['previewWidth']     = $this->getSettingValue('product_cart_settings', 'preview_width');
        $dataResize['thumbHeight']      = $this->getSettingValue('product_cart_settings', 'thumb_height');
        $dataResize['thumbWidth']       = $this->getSettingValue('product_cart_settings', 'thumb_width');
        $dataResize['smallthumbWidth']  = $this->getSettingValue('product_cart_settings', 'small_thumb_width');
        $dataResize['smallthumbHeight'] = $this->getSettingValue('product_cart_settings', 'small_thumb_height');
        $productReturn['enableReturn']  = $this->getSettingValue('product_cart_settings', 'enable_product_return');
        $productReturn['returnPeriod']  = $this->getSettingValue('product_cart_settings', 'return_period');
        $this->ObjView->assign('dataResize', $dataResize);
        $this->ObjView->assign('productReturn', $productReturn);
		
		
		$resProductCategories      = $ObjProductCategory->listProductCategories($languageIDs, -1);
        $productCategoryCount   = count($resProductCategories);
        foreach ($resProductCategories as $key => $value) {
            $categoryTree[$resProductCategories[$key]['productCategoryParent']][] = $resProductCategories[$key];
        }
        $resProductCategories = $this->createCategoryTree($categoryTree, $categoryTree[0]); //echo '<pre>'; 
        $this->ObjView->assign("resProductCategories", $resProductCategories);
		
		
        //Media Settings
        if ($this->ObjForm->isValid('Product', 'submitProductDetails')) {
            $_POST['dataResize'] = $dataResize;
            $this->ProductAddform($productID, $productRequestID);
        } elseif (isset($_POST['productOptionAddCount']) && $_POST['productOptionAddCount'] != '') {
            $this->ObjView->assign("productTypeKey", $_POST['productTypeKey']);
            $resProductOptions = isset($_POST['productOptionsGroup']) ? $_POST['productOptionsGroup'] : '';
            $opCount           = 0;
            $resProductOptions = $this->optionPostback($resProductOptions);
            $this->ObjView->assign('resProductOptions_postback', $resProductOptions);
            $this->ObjView->assign('postCallback', '1');
        }
        if ($this->ObjSession->getSession("BUSINESS_USER_ID"))
            $this->ObjView->assign("businessID", $this->ObjSession->getSession("BUSINESS_USER_ID"));
        $this->productAddAssign($productID, $productRequestID);
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
        $this->ObjView->display('ProductQuickAdd.tpl');
	 }
	 public function quickEditAction() {
        $ObjUsergroup       = new UsergroupModel();
        $ObjBrand           = new BrandModel();
        $productRequestID   = $this->getRequestValue("reqID");
        $productID          = $this->getRequestValue("id");
        $languageIDs        = $this->ObjView->languageIDs;
        $ctab               = $this->getRequestValue("tab");
        $settingEditProduct = $this->getSettingValue('multi_vendor_settings', 'allow_edit_approved_products');
        if (($settingEditProduct != 'Yes') && ($productID > 0)) {
            $this->setRedirect("product/show/id/" . $productID . "/");
        }
        if ($productRequestID > 0 || $productID > 0) {
            $ObjProduct = new ProductModel();
            $businessID = $this->ObjSession->getSession("BUSINESS_USER_ID");
            if ($productRequestID)
                $proBusinessID = $ObjProduct->getProductRequestBusinessID($productRequestID);
            else
                $proBusinessID = $ObjProduct->getProductBusinessID($productID);
            if ($businessID != $proBusinessID) {
                if ($productRequestID)
                    $this->setRedirect("product/request/");
                else
                    $this->setRedirect("product/index/");
            }
        }
        //Media Settings
        $dataResize['previewHeight']    = $this->getSettingValue('product_cart_settings', 'preview_height');
        $dataResize['previewWidth']     = $this->getSettingValue('product_cart_settings', 'preview_width');
        $dataResize['thumbHeight']      = $this->getSettingValue('product_cart_settings', 'thumb_height');
        $dataResize['thumbWidth']       = $this->getSettingValue('product_cart_settings', 'thumb_width');
        $dataResize['smallthumbWidth']  = $this->getSettingValue('product_cart_settings', 'small_thumb_width');
        $dataResize['smallthumbHeight'] = $this->getSettingValue('product_cart_settings', 'small_thumb_height');
        $productReturn['enableReturn']  = $this->getSettingValue('product_cart_settings', 'enable_product_return');
        $productReturn['returnPeriod']  = $this->getSettingValue('product_cart_settings', 'return_period');
        $this->ObjView->assign('dataResize', $dataResize);
        $this->ObjView->assign('productReturn', $productReturn);
        //Media Settings
        if (isset($_POST['submitProductDetails'])) {
            if ($this->ObjForm->isValid('Product', 'submitProductDetails')) {
                $_POST['dataResize'] = $dataResize;
                $this->ProductEditform($productID, $productRequestID);
            } elseif ($_POST['productOptionAddCount']) {
                $this->ObjView->assign("productTypeKey", $_POST['productTypeKey']);
                $resProductOptions = $_POST['productOptionsGroup'];
                $opCount           = 0;
                $resProductOptions = $this->optionPostback($resProductOptions, $_POST);
                $this->ObjView->assign('resProductOptions_postback', $resProductOptions);
                $this->ObjView->assign('postCallback', '1');
            }
        }
        if (!($productID || $productRequestID)) {
            $this->setRedirect("product/new/");
        }
        $this->saveCustomAttribute();
        $this->saveCustomOption();
        $this->productEditassign($productID, $productRequestID);
        $paramsArray['productRequestID'] = $productRequestID;
        $paramsArray['productID']        = $productID;
        $paramsArray['BusinessID']       = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $this->bindAttributeForm($paramsArray);
        $this->bindOptionForm($paramsArray);
        $this->bindInventoryForm($paramsArray);
        $this->bindShippingForm($paramsArray);
        $this->ObjView->assign('hiddenProductType', 'product_product');
        if ($ctab)
            $this->ObjView->assign('ctab', $ctab);
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
        $this->ObjView->display('ProductQuickEdit.tpl');
    }
	
	
	    private function createCategoryTree(&$list, $parent) {
        $tree = array();
        if (is_array($parent)) {
            foreach ($parent as $k => $l) {
                if (isset($list[$l['productCategoryParent']]) && !empty($list[$l['productCategoryID']])) {
                    $l['children'] = $this->createCategoryTree($list, $list[$l['productCategoryID']]);
                }
                $tree[] = $l;
            }
        }
        return $tree;
    }
     public function ajaxLinkBaseProductAction()
        {
            //initialize object
            $ObjImage 			= new ImageModel();
            $ObjProduct                 = new ProductModel();
            $languageIDs                = $this->ObjView->languageIDs;
            $languageIDs['Current']     = $languageIDs['Content'];      
            $productID                  = $_POST['productID'];
            $rand=rand(10,300);
            
            $paramArray['selectedProductID']=$productID;
            $paramArray['languageIDs']=$languageIDs;
            $paramArray['view']='Yes';
            $paramArray['businessStatus']="Yes";
            $paramArray['sellersCount']="Yes";
            $resSelectproduct      = $ObjProduct->getProductDetails($paramArray);
            $resSelectproduct      = $resSelectproduct[0];
            
            if (!empty($resSelectproduct['productImage'])){
                $fileName = "uploads/catalog/product/thumb/" . $resSelectproduct['productImage'];
                if ($ObjImage->file_exist($fileName)){
                    $this->ObjView->assign('image_directory', 'Yes');
                }
            }
            $this->ObjView->assign('rand', $rand);
            $this->ObjView->assign('resSelectproduct', $resSelectproduct);
            $this->ObjView->display('LinkBaseProduct.tpl');
        }
    public function ajaxBaseProductAction()
        {
            //initialize object
            $ObjProduct                 = new ProductModel();
            $languageIDs                = $this->ObjView->languageIDs;
            $languageIDs['Current']     = $languageIDs['Content'];      
            $category                   = $_POST['category'];
            $pieces = explode(",", $category);
            $result = array_unique($pieces);
            //echo "<pre>";print_r($result);exit;
            $categories = implode(",",$result);
            //echo "<pre>";print_r($categories);exit;
            $resProducts    = $ObjProduct->getProductTitleBuybox($languageIDs,$categories,$this->ObjSession->getSession("BUSINESS_USER_ID"));
            $this->ObjView->assign('resProducts', $resProducts);
            $this->ObjView->display('BaseProduct.tpl');
        }
         public function businessProductsAction(){
            $ObjBuybox        =   new BuyboxModel();
            $languageIDs      =   $this->ObjView->languageIDs;
            $productID        =   $this->getRequestValue('id');
            $businessProducts =   $ObjBuybox->getBuyBoxProductsBusiness($languageIDs,$productID);
            $this->ObjView->assign('businessProducts', $businessProducts);
            $this->ObjView->display('BuyboxProducts.tpl');
        }
        public function updateAlgoliaRecord($product_id = 0){
		
       
		$languageIDs                    =       $this->ObjView->languageIDs;
		$ObjUrl   			= 	new UrlrewriteModel();
		$ObjSearch   			= 	new SearchModel();
                $ObjCustomOption                =       new CustomOptionModel();
		$ObjProductList			= 	new ProductListModel();
                $ObjProduct			= 	new ProductModel();
		$ObjAttribute     		= 	new AttributeModel();
                $ObjLanguage     		= 	new LanguageModel();
		$cron_details = $ObjSearch->elastic_cron_execution_details();
                $listLangs    = $ObjLanguage->listLanguages(NULL,"Active");
		$userGroupID  = 0;
		if(empty($cron_details) || $product_id>0){
			$page	=	1;
		}else{
			if($cron_details['lastAffectedID']==0 && $cron_details['hour_diff']==0 ){
				echo 'Waiting for 1 hour diff';
				return;
			}  
			else{
				$page	=	$cron_details['lastAffectedID']+1;
			}
			
		}
		
		
		$algolia_application_id 		= 	$this->getSettingValue('algolia_search_settings','algolia_application_id');
		//$algolia_search_only_api_key 	= 	$this->getSettingValue('algolia_search_settings', 'algolia_search_only_api_key');
		$algolia_admin_api_key 			= 	$this->getSettingValue('algolia_search_settings', 'algolia_admin_api_key');
		$ObjAlgolia = 	new Algolia($algolia_application_id, $algolia_admin_api_key);
		//$result = $ObjAlgolia->search('contacts','Stanislaus');
		
		//$page					=	0;
		//while(true){
                        for($i=0;$i<count($listLangs);$i++){
                            $arguments =array(
				'productID'			=>	$product_id,
				'userGroupID'			=>	(int) $userGroupID,
				'page'					=>	($page-1),
                                'updateToLang'                  => $listLangs[$i]['languageID'],
			);
                        $languageIDs['Current'] =   $listLangs[$i]['languageID'];    
			$listProducts           =   $ObjSearch->listProducts($arguments);

			if(empty($listProducts)){
				$ObjSearch->elastic_cron_execution_update(0);
				echo 'Reset to initial stage';
			}
			else{
                            
                                //if($listLangs[$i]['languageID']!=$languageIDs['Current']) {
                                    $langXML                = $ObjLanguage->loadLanguageXMLtoArray(__CORE_PUBLIC_COMMON_FRONTEND_PATH . '/' . __DIR_LANGUAGE . '/' . $listLangs[$i]['LanguageLCIDstring'] . '.xml');
                                    $lblAllDiscountProducts = !empty($langXML['lblAllDiscountProducts'])? $langXML['lblAllDiscountProducts'] : $this->ObjView->_languageXML['lblAllDiscountProducts'];
                                    $lblTenPercentAbove     = !empty($langXML['lblTenPercentAbove'])? $langXML['lblTenPercentAbove'] : $this->ObjView->_languageXML['lblTenPercentAbove'];
                                    $lblTwentyPercentAbove  = !empty($langXML['lblTwentyPercentAbove'])? $langXML['lblTwentyPercentAbove'] : $this->ObjView->_languageXML['lblTwentyPercentAbove'];
                                    $lblThirtyPercentAbove  = !empty($langXML['lblThirtyPercentAbove'])? $langXML['lblThirtyPercentAbove'] : $this->ObjView->_languageXML['lblThirtyPercentAbove'];
                                    $lblFortyPercentAbove   = !empty($langXML['lblFortyPercentAbove'])? $langXML['lblFortyPercentAbove'] : $this->ObjView->_languageXML['lblFortyPercentAbove'];
                                    $lblFiftyPercentAbove   = !empty($langXML['lblFiftyPercentAbove'])? $langXML['lblFiftyPercentAbove'] : $this->ObjView->_languageXML['lblFiftyPercentAbove'];
                                    $lblInStock             = !empty($langXML['lblInStock'])? $langXML['lblInStock'] : $this->ObjView->_languageXML['lblInStock'];
                                    $lblOutOfStock          = !empty($langXML['lblOutOfStock'])? $langXML['lblOutOfStock'] : $this->ObjView->_languageXML['lblOutOfStock'];
                                /*} else {
                                    $lblAllDiscountProducts = $this->ObjView->_languageXML['lblAllDiscountProducts'];
                                    $lblTenPercentAbove     = $this->ObjView->_languageXML['lblTenPercentAbove'];
                                    $lblTwentyPercentAbove  = $this->ObjView->_languageXML['lblTwentyPercentAbove'];
                                    $lblThirtyPercentAbove  = $this->ObjView->_languageXML['lblThirtyPercentAbove'];
                                    $lblFortyPercentAbove   = $this->ObjView->_languageXML['lblFortyPercentAbove'];
                                    $lblFiftyPercentAbove   = $this->ObjView->_languageXML['lblFiftyPercentAbove'];
                                    $lblInStock             = $this->ObjView->_languageXML['lblInStock'];
                                    $lblOutOfStock          = $this->ObjView->_languageXML['lblOutOfStock'];
                                }*/
                                
				foreach($listProducts as $key=>$product){
					
					$current_product_id 	= $product['productID'];
					$productOptionDiscount 	= $product['productOptionDiscount'];
					$inventoryTrackLevel 	= ($product['inventoryTrackLevel']!='')?$product['inventoryTrackLevel']:'No';

					$listProducts[$key]['productOptionDiscount']                            = round($productOptionDiscount);
					$listProducts[$key]['productID'] 					= (int)$product['productID'];
					$listProducts[$key]['businessID'] 					= (int)$product['businessID'];
					$listProducts[$key]['brandID'] 						= (int)$product['brandID'];
					$listProducts[$key]['productOptionID']                                  = (int)$product['productOptionID'];
					$listProducts[$key]['productTitle']                                     = html_entity_decode($product['productTitle']);
					$listProducts[$key]['attributeSetID']                                   = (int)$product['attributeSetID'];
					$listProducts[$key]['productOptionProductPrice']                        = (float)$product['productOptionProductPrice'];
					$listProducts[$key]['productOptionQuantity']                            = (float)$product['productOptionQuantity'];
					if($listProducts[$key]['isProductDeal']=="Yes") {
                                            $listProducts[$key]['offerPrice'] 					= (float)$product['dealPrice'];
                                        } else {
                                            $listProducts[$key]['offerPrice'] 					= (float)$product['offerPrice'];
                                        }
					$listProducts[$key]['productOptionRegularPrice']                        = (float)$product['productOptionRegularPrice'];
					$listProducts[$key]['status']						= $product['productStatus'];
                                        $listProducts[$key]['customOptionCount']                                = $ObjCustomOption->getProductCustomOptionsCount($product['productID']);
                                        
					$listProducts[$key]['dealPrice']                                        = (float)$product['dealPrice'];
                                        $listProducts[$key]['isProductDeal']                                    = $product['isProductDeal'];
					
					if($productOptionDiscount<10 && $productOptionDiscount>0){
						$listProducts[$key]['discount'] = $lblAllDiscountProducts;
					}
					switch((int)($productOptionDiscount/10)){
						case 1:
							$listProducts[$key]['discount'] = $lblTenPercentAbove;
							break;
						case 2:
							$listProducts[$key]['discount'] = $lblTwentyPercentAbove;
							break;
						case 3:
							$listProducts[$key]['discount'] = $lblThirtyPercentAbove;
							break;
						case 4:
							$listProducts[$key]['discount'] = $lblFortyPercentAbove;
							break;
						case 5:
						case 6:
						case 7:
						case 8:
						case 9:
						case 10:
							$listProducts[$key]['discount'] = $lblFiftyPercentAbove;
							break;
					}
                                        $freeProductGifts = 0;
                                        //check free gifts available
                                        if($product['freeProductsCount']>0) {                                
                                            //get free products
                                            $argsFreeProducts                 = array(
                                                'requestedBy' => 'customer',
                                                'requestPage' => 'product_detail',
                                                'limitFrom' => 0,
                                                'limitTo' => '',
                                                'languageIDs' => $languageIDs,
                                                'previewOnly' => '',
                                                'currDateTime' => '',                                    
                                                'selectedProductID' => $current_product_id,
                                                'userGroupID' => (int) $userGroupID

                                            );
                                            $freeProducts   = $ObjProduct->getActiveFreeProducts($argsFreeProducts);  
                                            if(!empty($freeProducts)) {
                                                $freeProductGifts = ($product['freeProductsCount']>count($freeProducts)) ? count($freeProducts): $product['freeProductsCount'];
                                            }

                                        }					
					$listProducts[$key]['freeProductGifts'] = $freeProductGifts;
					$args=array(
						'productID'				=>	$current_product_id,
						'inventoryTrackLevel'  	=>	$inventoryTrackLevel,
                                                'updateCToLang'                  => $listLangs[$i]['languageID'],
					);
					$quantity 							= 	$ObjProductList->getProductOptionQuantitySum($args);
					$listProducts[$key]['categories'] 	= 	$ObjSearch->listCategoryNames($args);
					//$listProducts[$key]['color'] 		= 	"green";
					//$listProducts[$key]['size'] 		= 	"XL";
					
					
					$args=array(
						'objectID'=>$current_product_id,
						'productID'=>$current_product_id,
						'language_ids'=>$languageIDs,
						'type'=>'product',
						'isSystem'=>'1'
					);
					
					$result = $ObjUrl->getRewriteUrl($args);
					$listProducts[$key]['requestPath'] 		= $result['requestPath'];
						//echo $result['requestPath']."<br>";
					$reviewDet                     = $ObjSearch->fetchProductReviews($args);
					$listProducts[$key]['reviews'] = $reviewDet['productReviewsCount'];
                                        $listProducts[$key]['ratingTotal'] = $reviewDet['ratingTotal'];
					if($quantity>0){
						$listProducts[$key]['availability'] = $lblInStock;
					}else{
						$listProducts[$key]['availability'] = $lblOutOfStock;
					}					
					$attributeList    = array();					
					$attrArgs = array(
						'productIDArray' => array($current_product_id),
						'fromModule'=>'elastic'
					);
					
					$resAttributeList = $ObjAttribute->listAttributesForNavigation($languageIDs, $attrArgs);
					
					if (!empty($resAttributeList)) {
						foreach ($resAttributeList as $attributes) {
							$listProducts[$key][$attributes['attributeKey']][] = $attributes['attrOptName'];
						}
					}

				}
				
                               
				$ObjAlgolia->addObjects('products_'.$listLangs[$i]['languageCode'],$listProducts);
				$ObjAlgolia->addObjects('products_popularity_'.$listLangs[$i]['languageCode'],$listProducts);
				$ObjAlgolia->addObjects('products_newlylisted_'.$listLangs[$i]['languageCode'],$listProducts);
				$ObjAlgolia->addObjects('products_price_desc_'.$listLangs[$i]['languageCode'],$listProducts);
				$ObjAlgolia->addObjects('products_price_asc_'.$listLangs[$i]['languageCode'],$listProducts);
				$ObjAlgolia->addObjects('products_discount_'.$listLangs[$i]['languageCode'],$listProducts);
                                $ObjAlgolia->addObjects('productstest_'.$listLangs[$i]['languageCode'],  json_encode($listProducts));
				// erase the old bulk request
			
			
				if(!($product_id>0)){
					$ObjSearch->elastic_cron_execution_update($page);
				}
			}
                        }
			
			//echo'<pre>'. json_encode($listProducts); exit;
			
			
			
		//}
		
	}
        
        public function ajaxAddGroupPriceAction(){
        $ObjUsergroup           =       new UsergroupModel();
        $languageIDs            =       $this->ObjView->languageIDs;
        
        $params         = array(
            'languageIDs' => $languageIDs,
            'sortby' => 'brandName',
            'orderby' => 'ASC'
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        
        $productOptionCount     =       $_POST['productOptionCount'];
        $groupIncr              =       $_POST['groupIncr'];
        
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $this->ObjView->assign("optionIncr", $productOptionCount);
        $this->ObjView->assign("groupIncr", $groupIncr);
        $this->ObjView->display('AjaxBusinessGroupPrice.tpl');
    }
    
    public function buyboxrequestAction(){
        $ObjProduct			=           new ProductModel();
        $languageIDs                    =           $this->ObjView->languageIDs;
        $businessID                     =           $this->ObjSession->getSession("BUSINESS_USER_ID");
        
        if (isset($_POST['submitProductSearch'])) {
            $searchProductName          =           strtolower(trim($_POST['searchProductName']));
            $pos                        =           strpos($searchProductName, "/");
            if ($pos != false) {
                $searchProductName      =           substr($searchProductName, 0, strrpos($searchProductName, "/"));
            }
            $searchProductName          =           $this->encodeUrlString($searchProductName);
            
           
            if ($searchProductName != '') {
                $link                  .=           "name/" . $searchProductName . "/";
            }        
            $this->setRedirect("product/buyboxrequest/" . $link);
        }else{
            $searchProductName          =           $this->decodeUrlString($this->getRequestValue("name"));
        }
        $params                         =           array("productName"=>isset($searchProductName) ? $searchProductName : "");
        
        list($limitFrom, $limitTo)      =           $this->getPageSettings($key = 'page');
        $resProducts                    =           $ObjProduct->getBuyBoxRequestProducts($languageIDs,$businessID,$limitFrom,$limitTo,$params);  
        $resPagesCount                  =           $this->setPagesCount($key = 'page');
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->assign("searchProductName", $searchProductName);
        $this->ObjView->display('ProductBuyboxRequest.tpl');
    }
    
    public function addAction(){
        $ObjProduct			=           new ProductModel();
        $languageIDs                    =           $this->ObjView->languageIDs;
        $businessID                     =           $this->ObjSession->getSession("BUSINESS_USER_ID");
        if(isset($_POST['submitBuyboxSearch']) && $_POST['submitBuyboxSearch']=="Search"){
            $productName                =           isset($_POST['searchProductName']) ? $_POST['searchProductName']: "";
            if($productName!=""){
                $resProducts            =           $ObjProduct->getBuyboxProducts($languageIDs,$productName,$businessID);
            }else{
                $this->setMessage("language.errProductNameSearch","error");
                $this->setRedirect();
            }
        }
        $this->ObjView->assign("searchProductName", $productName);
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->display('ProductAddListOption.tpl');
    }
}
