<?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 2013/06/14 20:52:11
//
class ProductController extends Controller {
    //LIST PRODUCT WITH SEARCH
    public function indexAction() { 
        $ObjBusiness            = new BusinessModel();
        $ObjProduct             = new ProductModel();
        $ObjClone               = new CloneModel();
        $ObjProductList         = new ProductListModel();
        $ObjProductCategory     = new ProductCategoryModel();
        $ObjCustomOption        = new CustomOptionModel();
        $ObjAttr                = new AttributeModel();
        $ObjBrand               = new BrandModel();
        $link                   = '';
        $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');
        
        //load inline
        $resCategories = $ObjProductCategory->listProductCategoryItems($languageIDs, 0);
        $resAttrSet    = $ObjAttr->listAttributeSet();
        if (is_array($resCategories))
            array_shift($resCategories);
        $searchProductID           = $this->getRequestValue("key");
        $searchProductName         = $this->decodeUrlString($this->getRequestValue("name"));
        $searchProductBusinessType = $this->getRequestValue("btype");
        $searchAttrSet             = $this->decodeUrlString($this->getRequestValue("attrSet"));
        $searchProductCategory     = $this->getRequestValue("category");
        $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");
        $brandIDs                  = $this->getRequestValue("brandIDs");
        $businessIDs               = $this->getRequestValue("businessIDs");
        $businessID                = $this->getRequestValue("businessID");
        $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->decodeUrlString($this->getRequestValue("searchQuantityBelow"));
        $businessKey               = $this->decodeUrlString($this->getRequestValue("businessKey"));
        $brandKey                  = $this->decodeUrlString($this->getRequestValue("brandKey"));
        $searchInventory           = $this->getRequestValue("inventory");
        $searchType                = $this->getRequestValue("sType");
        $cloneProductIDs           = $this->getRequestValue("pids");
        $searchDeal		   = $this->getRequestValue("searchDeal");
        $searchBuybox		   = $this->getRequestValue("searchBuybox");
        if ($cloneProductIDs != '')
            $cloneProductIDs = explode("_", $cloneProductIDs);
        if ($searchProductID > 0) {
            $link .= "key/" . $searchProductID . "/";
        }
        if ($searchProductName != '') {
            $link .= "name/" . $this->encodeUrlString($searchProductName) . "/";
        }
        if ($brandKey != '') {
            $link .= "brandKey/" . $this->encodeUrlString($brandKey) . "/";
        }
        if ($businessKey != '') {
            $link .= "businessKey/" . $this->encodeUrlString($businessKey) . "/";
        }
        if ($businessID != '') {
            $link .= "businessID/" . $this->encodeUrlString($businessID) . "/";
        }
        if ($searchAttrSet > 0) {
            $link .= "attrSet/" . $searchAttrSet . "/";
        }
        if ($brandIDs != '') {
            $link .= "brandIDs/" . $brandIDs . "/";
        }
        if ($businessIDs != '') {
            $link .= "businessIDs/" . $businessIDs . "/";
        }
        if ($searchProductBusinessType > 0) {
            $link .= "btype/" . $searchProductBusinessType . "/";
        }
        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 ($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 . "/";
        }
		if ($searchDeal != '') {
            $link .= "searchDeal/" . $searchDeal . "/";
        }
        if ($searchBuybox != '') {
            $link .= "searchBuybox/" . $searchBuybox . "/";
        }
        $link .= "list";
        //Load inline       
        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";
        }
        
        /******************************All Post Options*****************************/
        if (isset($_POST['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";
                            }
                            $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";
                            }
                            $resUpdate                                     = $ObjProduct->updateProductsCombinationsDetails($combination, $combinationParams);
                        }
                    }
                }
                if ($_POST['combinationIDsString'] != '' || $_POST['optionIDsString'] != '') {
                    $this->setMessage("language.lblRecordsUpdated", 3);
                    $this->setRedirect("product/index/" . $link);
                }
            } else {
                $this->ObjView->assign('validated', 'No');
            }
        }
        //status
        else if (isset($_POST['changeStatus'])) {
            $checkProductIDsCount = count($_REQUEST['checkProductIDs']);
            for ($i = 0; $i < $checkProductIDsCount; $i++) {
                $productID = $_REQUEST['checkProductIDs'][$i];
                if ($_POST['changeStatus'] == 'm_clone') {
                    $pdata   = $ObjClone->fn_clone_product($languageIDs, $productID);
                    $p_ids[] = $pdata['product_id'];
                } else {
                    $changestatus = $ObjProduct->changeProductStatus($productID);
                    if ($changestatus && $_POST['changeStatus'] == "Deleted") {
                        $ObjUrl = new UrlrewriteModel();
                        $ObjUrl->deleteUrlRewrites('', 'product', $productID);
                    }
                }
            }
            if (isset($changestatus) && $_POST['changeStatus'] == "Deleted") {
                $this->setMessage("language.msgproductDelete", 3);
            } else {
                if ($_POST['changeStatus'] == "m_clone") {
                    if (count($_REQUEST['checkProductIDs']) > 0) {
                        $this->setMessage("language.msgProductCloned", "success");
                        $redirect = "product/index/pids/" . implode("_", $p_ids);
                        $this->setRedirect($redirect);
                    }
                } else {
                    if (isset($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'];
            $searchProductName = strtolower(trim($_POST['searchProductName']));
            $pos               = strpos($searchProductName, "/");
            $searchAttrSet     = trim($_POST['searchAttrSet']);
            $brandKey          = trim($_POST['brandKey']);
            $businessKey       = trim($_POST['businessKey']);
            $brandIDs          = (isset($_POST['brandIDs'])) ? implode(":", $_POST['brandIDs']) : '';
            $businessIDs       = (isset($_POST['businessIDs'])) ? implode(":", $_POST['businessIDs']) : '';
            if ($pos != false) {
                $searchProductName = substr($searchProductName, 0, strrpos($searchProductName, "/"));
            }
            $searchProductName         = $this->encodeUrlString($searchProductName);
            $searchProductType         = '1';
            $searchProductBusinessType = isset($_POST['searchProductBusinessType']) ? $_POST['searchProductBusinessType'] : '';
            $searchProductCategories   = isset($_POST['searchProductCategory']) ? $_POST['searchProductCategory'] : '';
            if (isset($searchProductCategories) && $searchProductCategories != '')
                $searchProductCategory = implode(":", $searchProductCategories);
            else
                $searchProductCategory = '';
            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);
            }
			$searchDeal    = isset($_POST['searchDeal']) ? $_POST['searchDeal'] : ''; 
            $searchBuybox  = isset($_POST['searchBuybox']) ? $_POST['searchBuybox'] : ''; 
            $sortByOption  = isset($_POST['sortByOption']) ? $_POST['sortByOption'] : '';
            $sortByOrder   = isset($_POST['sortByOrder']) ? $_POST['sortByOrder'] : '';
            $productStatus = isset($_POST['productStatus']) ? $_POST['productStatus'] : '';
            $productStatus = ($productStatus == 'Select Status') ? "" : $productStatus; 
            if ($searchProductID > 0) {
                $link .= "key/" . $searchProductID . "/";
            }
            if ($searchProductName != '') {
                $link .= "name/" . $searchProductName . "/";
            }
            if ($searchProductBusinessType > 0) {
                $link .= "btype/" . $searchProductBusinessType . "/";
            }
            if ($brandIDs != '') {
                $link .= "brandIDs/" . $brandIDs . "/";
            }
            if ($businessIDs != '') {
                $link .= "businessIDs/" . $businessIDs . "/";
            }
			if ($searchDeal != '') {
                $link .= "searchDeal/" . $searchDeal . "/";
            }
            if ($searchBuybox != '') {
                $link .= "searchBuybox/" . $searchBuybox . "/";
            }
            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 ($_POST['searchPriceFrom']) {
                $link .= "pricefrom/" . $this->encodeUrlString($_POST['searchPriceFrom']) . "/";
            }
            if ($_POST['brandKey']) {
                $link .= "brandKey/" . $this->encodeUrlString($_POST['brandKey']) . "/";
            }
            if ($_POST['businessKey']) {
                $link .= "businessKey/" . $this->encodeUrlString($_POST['businessKey']) . "/";
            }
            if ($_POST['businessID']) {
                $link .= "businessID/" . $this->encodeUrlString($_POST['businessID']) . "/";
            }
            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'])) {
                $link .= "gkeyword/" . $_POST['searchGlobalKeyword'] . "/";
            }
            if ($searchOption) {
                $link .= "sType/" . $searchOption . "/";
            }
            if ($_POST['searchQuantityBelow'] != '') {
                $link .= "searchQuantityBelow/" . $this->encodeUrlString($_POST['searchQuantityBelow']) . "/";
            }
            if ($searchAttrSet > 0) {
                $link .= "attrSet/" . $searchAttrSet . "/";
            }
            $this->setRedirect("product/index/" . $link);
        }
        /******************************************************************************/
        $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";
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        
        
        
        $params        = array(
            'requestedBy' => 'admin',
            'languageIDs' => $languageIDs,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'sortBy' => $sortByOption,
            'orderBy' => $sortByOrder,
            'searchProductKeyword' => $searchProductName,
            'searchProductFromDate' => $this->convertDateForSQL($searchProductFromDate, $settingsDateFormat),
            'searchProductToDate' => $this->convertDateForSQL($searchProductToDate, $settingsDateFormat),
            'searchProductStatus' => $productStatus,
            'searchProductCategories' => $searchProductCategories,
            'searchPriceFrom' => $searchPriceFrom,
            'searchPriceUpto' => $searchPriceUpto,
            'searchDiscountFrom' => $searchDiscountFrom,
            'searchDiscountTo' => $searchDiscountTo,
            'searchGlobalKeyword' => $searchGlobalKeyword,
            'searchQuantityBelow' => $searchQuantityBelow,
            'businessKey' => $businessKey,
            'brandKey' => $brandKey,
            'searchInventory' => $searchInventory,
            'searchCloneIds' => $cloneProductIDs,
            'brandIDs' => ($brandIDs != '') ? explode(":", $brandIDs) : array(),
            'businessIDs' => ($businessIDs != '') ? explode(":", $businessIDs) : array(),
            'businessID' => $businessID,
            'searchAttrSet' => $searchAttrSet,
            'searchDeal' => $searchDeal,
            'searchBuybox' => $searchBuybox,
            'searchFrom' => 'admin' 
        );
        
        $resProducts   = $ObjProductList->listProducts($params);
      
        $resPagesCount = $this->setPagesCount($key = 'page');
        if (count($resProducts) > 0) {
            foreach ($resProducts as $key => $products) {
                if ($products['productStatus'] == 'Buybox') {
                    $resPdtID      =$ObjProduct->getProductIDs($products['productID']);
                    $resProducts[$key]['price']=$resPdtID['price'];
               }
                if ($products['InventoryTrackLevel'] == 'No') {
                    $outOfStock = 'No';
                } else {
                    $products['productQuantityNotifyAt'] = isset($products['productQuantityNotifyAt']) ? $products['productQuantityNotifyAt'] : '';
                    $outOfStock                          = $ObjProductList->checkProductOutOfStock($products['productID'], $products['productQuantityNotifyAt'], $products['InventoryTrackLevel']);
                }
                $resProducts[$key]['outOfStock'] = $outOfStock;
                $resProducts[$key]['options']    = $ObjProduct->listProductOptions($languageIDs, $products['productID'], Null, Null, 'list', "", "", "basic","Yes");
                $params                          = array(
                    'productID' => $products['productID'],
                    'view' => 'No',
                    'status' => 'A',
                    'languageIDs' => $languageIDs,
                    'purpose' => "basic"
                );
                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']);
                            if (count($comboArray) > 0) {
                                foreach ($comboArray as $combostr) {
                                    if ($Combination)
                                        $Combination .= ",";
                                    $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                                }
                            }
                            $resProducts[$key]['combination'][$count]['ProductCombo'] = $Combination;
                            $getBusinessComb        =   $ObjCustomOption->getProductBusinessCombination($languageIDs,$comboID);
                            $resProducts[$key]['combination'][$count]['businessCombinations'] = $getBusinessComb;
                            $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 : '';
                }
            }
            
            
        }
        //echo "<pre>";print_r($resProducts);exit;
        $siteUrl        = $this->getSettingValue('site_settings', 'global_http_url');
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listBrands     = array();
        $listBusinesses = array();
        $listBrand      = $ObjBrand->listBrand($params,'All');
        foreach ($listBrand as $brand) {
            $listBrands[] = $brand['brandName'];
        }
        $listBusiness = $ObjBusiness->listBusinessInOptions($languageIDs);
        foreach ($listBusiness as $key => $business) {
            $listBusinesses[$key]['label'] = $business['businessName'];
            $listBusinesses[$key]['value'] = $business['businessID'];
        }
       // echo"<pre>";print_r($resProducts);exit;
        $this->ObjView->assign('listBrands', $listBrands);
        $this->ObjView->assign('listBusinesses', $listBusinesses);
        $this->ObjView->assign('brandIDs', implode("~*", explode(":", $brandIDs)));
        $this->ObjView->assign('businessIDs', implode("~*", explode(":", $businessIDs)));
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('businessKey', $businessKey);
        $this->ObjView->assign('brandKey', $brandKey);
        $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('searchStatus', $searchStatus);
        $this->ObjView->assign('productStatus', $productStatus);
        $this->ObjView->assign('searchProductID', $searchProductID);
        $this->ObjView->assign('searchProductName', $searchProductName);
        $this->ObjView->assign('searchAttrSet', $searchAttrSet);
        if (isset($searchProductType))
            $this->ObjView->assign('searchProductType', $searchProductType);
        $this->ObjView->assign('searchQuantityBelow', $searchQuantityBelow);
        if ($searchProductToDate == $searchProductFromDate) {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate);
        } else {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate . " - " . $searchProductToDate);
        }
        $this->ObjView->assign('searchProductBusinessType', $searchProductBusinessType);
        $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("resAttrSet", $resAttrSet);
        $this->ObjView->assign('searchProductCategorySel', $searchProductCategory);
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->assign("fromDate", $searchProductFromDate);
        $this->ObjView->assign("toDate", $searchProductToDate);
		$this->ObjView->assign("searchDeal", $searchDeal);
        $this->ObjView->assign("searchBuybox", $searchBuybox);
        if ($searchType) {
            $this->ObjView->assign('searchOption', $searchType);
        } else {
            $this->ObjView->assign('searchOption', 'basic');
        }
        //Privilege
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('product/edit/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('product/delete/'));
        $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('product/show/'));
        $this->ObjView->assign("newPrivilege", $this->ObjCommon->hasPrivilege('product/new/'));
        $this->ObjView->assign('clonePrivilege', $this->ObjCommon->hasPrivilege('product/clone/'));
        //Privilege
        $rand = rand(10, 300);
        $this->ObjView->assign('sortByOrder', $sortByOrder);
        $this->ObjView->assign('selectOption', 'List');
        $this->ObjView->assign('rand', $rand);
        $this->ObjView->display('ProductList.tpl');
    }
    //END OF FUNCTION    
    //FUNCTION TO SHOW PRODUCT 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();
        $ObjImage         = new ImageModel();
        $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 = $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;
        $languageIDs['Current'] = $languageIDs['Content'];
        $currentLanguageID      = $languageIDs['Current'];
        $defaultLanguageID      = $languageIDs['Default'];
        $productTab             = $this->getRequestValue("tab");
        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';
            $paramArray['businessStatus']    = "Yes";
            $resSelectproduct                = $ObjProduct->getProductDetails($paramArray);
            $resSelectproduct                = $resSelectproduct[0];
            $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);
            }
            $freeProducts = $ObjProductList->getFreeProducts($productID);            
            if (!empty($freeProducts)) {
                $paramArray['relIDs'] = $freeProducts;
                $resFreeProducts      = $ObjProductList->getProductsForRelated($paramArray);                
                $this->ObjView->assign('resFreeProducts', $resFreeProducts);
            }
            $resProductcategory = $ObjProduct->listProductTocategoryDetails($languageIDs, $productID);
            $this->ObjView->assign('resProductcategory', $resProductcategory);
            $resBusiness       = $ObjBusiness->getBusinessBasic($resSelectproduct['businessID'], $languageIDs);
            $resProductOptions = $ObjProduct->listProductOptions($languageIDs, $productID, "", '', 'list', "", "", "basic","Yes");
            //echo "<pre>"; print_r($resProductOptions); exit;
            //optionmedia		
            $opCount           = 0;
            foreach ($resProductOptions as $reslistOptions) {
                $resProductOptions[$opCount]['offerPrice'] = $ObjProduct->getOptionUserGroupPrice($reslistOptions['productOptionID'], $languageIDs);
                $resProductOptions[$opCount]['tierPrice']  = $ObjProduct->getOptionTierPrice($reslistOptions['productOptionID'], $languageIDs);
                $productOptionMedia                        = $ObjProduct->listProductOptionMedia($reslistOptions['productOptionID']);
                $resProductOptions[$opCount]['media']      = $productOptionMedia;
                $opCount++;
            }
            //optionmedia		
            if (!empty($resSelectproduct['productImage'])) {
                $fileName = "uploads/catalog/product/thumb/" . $resSelectproduct['productImage'];
                if ($ObjImage->file_exist($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('resProductOptions', $resProductOptions);
            $this->ObjView->assign('resSelectproduct', $resSelectproduct);
        }
        if ($resSelectproduct['productID']) {
            $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);
            if (isset($_POST['submitProductReview'])) {
                $resSaveProductreview = $ObjProductReview->saveProductreview($languageIDs, $_POST);
                if ($resSaveProductreview == 'Deleted') {
                    $this->setMessage("language.msgCommentDelete", "success");
                } else {
                    $this->setMessage("language.msgCommentPostAdd", "success");
                }
                $this->setRedirect("/product/show/id/" . $productID . "/tab/4/");
            } else if (isset($_POST['reviewStatus'])) {
                $reschangeProductReviewStatus = $ObjProductReview->changeProductReviewStatus($_POST);
                if ($reschangeProductReviewStatus == 'Deleted') {
                    $this->setMessage("language.msgCommentDelete", "success");
                } else {
                    $this->setMessage("language.msgStatus", "success");
                }
                $this->setRedirect("/product/show/id/" . $productID . "/tab/4/");
            }
            $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();
                if (count($resAttributes) > 0) {
                    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,
                'checkBusinessComb' => 'Yes'
            );
            $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');
            
            if(isset($categoryIDList))
		$categoryList = implode(",", $categoryIDList);
		else
		$categoryList ="";		
            
            $this->ObjView->assign('resAtrributeInputTypes', $resAtrributeInputTypes);
            $this->ObjView->assign('resUserLevelAttributes', $resUserLevelAttributes);
            $this->ObjView->assign("reviewprivilage", $this->ObjCommon->hasPrivilege('product/reviewedit/'));
            $this->ObjView->assign("revdeleteprivilage", $this->ObjCommon->hasPrivilege('product/reviewdelete/'));
            //custom option
            $this->ObjView->display('ProductDetails.tpl');
        } else {
            $this->setRedirect('product/index/');
        }
    }
    //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            = 2;
        while ($i < $count) {
            $arrCertCodes[]['CertificateCode'] = $ObjProduct->getRandomCode($codeLength, $codeGenerateType);
            $i++;
        }
        
        $sql = "select productTitle from dp_product_details where productID='1454' and languageID='2'";
        $res = $ObjProduct->exeQuery($sql);
        $arrCertCodes[]['CertificateCode'] = 'a'.$res['productTitle'];
        if (is_array($arrCertCodes)) {
            $header = array(
                "CertificateCode"
            );
            $data   = $ObjCsv->output('example.csv', $arrCertCodes, $header);
        }
    }
   
    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 PRODUCT OPTIONS
    public function ajaxLoadProductOptionsTplAction() {
        $ObjBusiness            =       new BusinessModel();
        $ObjProduct             =       new ProductModel();
        $languageIDs            =       $this->ObjView->languageIDs;
        $resBusiness            =       $ObjBusiness->listBusinessInOptions($languageIDs);
        $resPeriod              =       $ObjProduct->getDispatchTime();
        $this->ObjView->assign('resBusiness', $resBusiness);
        $this->ObjView->assign('resPeriod', $resPeriod);
        
        $productOptionCount = $_POST["productOptionCount"];
        $productTypeKey     = $_POST["productTypeKey"];
        $productID          = $_POST["productID"];
        $productInvLevel    = $_POST["invTrackLevel"];
        //$productInvLevel    = $ObjProduct->getInventoryTrackLevel($productID);
        $this->ObjView->assign('productInvLevel', $productInvLevel);
        $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
    public function ajaxtimezonevalidateAction() {
        $ObjTimezoneModel = new TimezoneModel();
        $resTimezone      = $ObjTimezoneModel->getTimezoneDetails($_POST['timezoneID']);
        $date1            = strtotime('+ 12 hours', strtotime($_POST['startTime']));
        $date2            = strtotime('+ 36 minutes', strtotime($ObjTimezoneModel->convert_tz("F j, Y", $resTimezone['timeZoneDetail'])));
        if (($date1 - $date2) >= 0) {
            echo 1;
        } else {
            echo 0;
        }
    }
    //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 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'] : '';
        $searchBusiness                  = (isset($_POST['searchBusiness'])) ? $_POST['searchBusiness'] : '';
        $searchType                      = (isset($_POST['type'])) ? $_POST['type'] : '';
        $resListUpcomingProducts         = '';
        $paramArray                      = array();
        $paramArray['currentLanguageID'] = $languageIDs['Current'];
        $paramArray['productID']         = $productID;
        $paramArray['searchKeyword']     = $searchKeyword;
        $paramArray['searchItems']       = $searchItems;
        $paramArray['searchSetID']       = $searchSetID;
        $paramArray['businessID']        = $searchBusiness;
        $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');
        elseif ($searchType == 'Free')
            $this->ObjView->display('FreeProductsLeft.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;
        }
    }
    //END OF FUNCTION
    //FUNCTION TO LIST ALL REVIEWS
    public function reviewAction() {
        $ObjProduct         = new ProductModel();
        $ObjProductReview   = new ProductreviewModel();
        $ObjBusiness        = new BusinessModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $defaultLanguageID  = $languageIDs['Default'];
        $settingsDateFormat = $this->getSettingValue('site_settings', 'date_format');
        $link               = '';
        if (isset($_POST['submitProductReview'])) {
            $resSaveProductreview = $ObjProductReview->saveProductreview($languageIDs, $_POST);
            if ($resSaveProductreview == 'Deleted') {
                $this->setMessage("language.msgCommentDelete", "success");
            } else {
                $this->setMessage("language.msgCommentPostAdd", "success");
            }
            $this->setRedirect();
        } else if (isset($_POST['reviewStatus'])) {
            $resChangeProductReviewStatus = $ObjProductReview->changeProductReviewStatus($_POST);
            if ($resChangeProductReviewStatus == 'Deleted') {
                $this->setMessage("language.msgCommentDelete", "success");
            } else {
                $this->setMessage("language.msgStatus", "success");
            }
            $this->setRedirect();
        }
        if (isset($_POST['submitProductReviewSearch'])) {
            $searchProductID   = isset($_POST['searchProductID']) ? $_POST['searchProductID'] : '';
            $searchProductName = $_POST['searchProductName'];
            $searchProductName = $this->encodeUrlString($searchProductName);
            $searchUserName    = trim($_POST['searchUserName']);
            $searchUserName    = $this->encodeUrlString($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 ($status == 'Select') {
                $status = '';
            }
            $searchRating = $_POST['rating'];
            $searchUserip = $this->encodeUrlString($_POST['userip']);
            if ($searchProductID > 0) {
                $link .= "key/" . $searchProductID . "/";
            }
            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 ($status) {
                $link .= "status/" . $status . "/";
            }
            if ($searchRating) {
                $link .= "rating/" . $searchRating . "/";
            }
            if ($searchUserip) {
                $link .= "userip/" . $searchUserip . "/";
            }
            if ($sortby = $this->getRequestValue("sortby")) {
                $link .= "sortby/" . $sortby . "/";
            }
            if ($orderby = $this->getRequestValue("orderby")) {
                $link .= "orderby/" . $orderby . "/";
            }
            $this->setRedirect("product/review/" . $link);
        } else {
            $searchProductID       = $this->getRequestValue("key");
            $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");
            $searchRating          = $this->getRequestValue("rating");
            $searchUserip          = $this->decodeUrlString($this->getRequestValue("userip"));
            if ($searchProductID > 0) {
                $link .= "key/" . $searchProductID . "/";
            }
            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 . "/";
            }
            if ($searchRating) {
                $link .= "rating/" . $searchRating . "/";
            }
            if ($searchUserip) {
                $link .= "userip/" . $this->encodeUrlString($searchUserip) . "/";
            }
            $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['rating']           = $searchRating;
        $params['userip']           = $searchUserip;
        $resAllProductReviewDetails = $ObjProductReview->getAllProductReviewDetails($params);
        $resPagesCount              = $this->setPagesCount($key = 'page');
        $resMerchantReviewCount     = $ObjBusiness->getMerchantReviewCount('', '');
        /* Privilages*/
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('product/reviewedit/'));
        $newPrivilage = $this->ObjCommon->hasPrivilege('product/new/');
        $this->ObjView->assign("newPrivilage", $newPrivilage);
        $this->ObjView->assign("reviewPrivilage", $this->ObjCommon->hasPrivilege('business/showreview/'));
        $this->ObjView->assign("userPrivilage", $this->ObjCommon->hasPrivilege('user/show/'));
        $this->ObjView->assign("productPrivilage", $this->ObjCommon->hasPrivilege('product/show/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('product/reviewdelete/'));
        /* Privilages*/
        $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('resMerchantReviewCount', $resMerchantReviewCount);
        $this->ObjView->assign('status', $status);
        $this->ObjView->assign('selectOption', 'productreview');
        $this->ObjView->assign('rating', $searchRating);
        $this->ObjView->assign('userip', $searchUserip);
        $this->ObjView->display('ProductReview.tpl');
    }
    //END OF FUNCTION
    public function revieweditAction() {
        $ObjProductReview = new ProductreviewModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $productReviewID  = $this->getRequestValue('id');
        $actionType       = $this->getRequestValue('do');
        $productID        = $this->getRequestValue('productid');
        if ($actionType == 'delete' && $productReviewID) {
            $POST = array(
                "reviewStatus" => "Deleted",
                "productReviewBulkStatus" => array(
                    $productReviewID
                )
            );
            $ObjProductReview->changeProductReviewStatus($POST);
            $this->setMessage("language.msgCommentDelete", "success");
            if ($productID) {
                $this->setRedirect('product/show/id/' . $productID . '/');
            } else {
                $this->setRedirect('product/review/');
            }
        }
        if ($productReviewID && $this->ObjForm->isValid('formReviewEditSubmit', 'submitReviewEdit')) {
            $resSaveProductreview = $ObjProductReview->saveProductreview($languageIDs, $_POST);
            echo '<script type="text/javascript">parent.location=self.parent.location.href+"tab/active/"; $.colorbox.close();</script>';
            $this->setMessage("language.msgCommentPostAdd", "success");
            exit;
        }
        $reviewDetails = $ObjProductReview->getProductReviewComment($productReviewID);
        $this->ObjView->assign('userComment', $reviewDetails['reviewText']);
        $this->ObjView->assign('productReviewID', $productReviewID);
        $this->ObjView->assign($reviewDetails);
        $this->ObjView->display('ProductReviewEdit.tpl');
    }
    //Add Products
    public function newAction($productRequestID = '') {
        
        $ObjUsergroup                   = new UsergroupModel();
        $ObjBrand                       = new BrandModel();
        $ObjProductCategory             = new ProductCategoryModel();
        $languageIDs                    = $this->ObjView->languageIDs;
        $productID                      = $this->getRequestValue("id");
        $productRequestID               = $this->getRequestValue("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');
        $this->ObjView->assign('dataResize', $dataResize);
        //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']);
//                $msgCu	= '';
//		if (!empty($clonedata['product_id'])) {
//                    $pid            = $clonedata['product_id'];
//                    $LinkBuybox     = $ObjProduct->saveProductLinkBuybox($languageIDs, $_POST, $pid);
//                    $this->setMessage($this->getLanguageValue("msgAddProduct").$msgCu, "success");	
//		}
//		if ($productRequestID)
//		{
//		    $ObjProduct->changeProductRequestStatus("Approved", $productRequestID);
//		    //SEND Approved mail to business user						
//		    $this->productapproval($pid);
//		}
//		$this->setRedirect("product/edit/id/$pid/");
//            }else{
                $_POST['dataResize'] = $dataResize;
                $this->ProductAddform($productID, $productRequestID);
            //}
        } elseif (isset($_POST['productOptionAddCount'])) {
                $this->ObjView->assign("productTypeKey", $_POST['productTypeKey']);
                $resProductOptions = isset($_POST['productOptionsGroup']) ? $_POST['productOptionsGroup'] : array();
                $opCount           = 0;
                $resProductOptions = $this->optionPostback($resProductOptions);
                $this->ObjView->assign('resProductOptions_postback', $resProductOptions);
                $this->ObjView->assign('postCallback', '1');
        }
        if ($this->getRequestValue("businessID"))
            $this->ObjView->assign("businessID", $this->getRequestValue("businessID"));
        $this->productAddAssign($productID, $productRequestID);
        $params         = array(
            'languageIDs' => $languageIDs,
            'sortby' => 'brandName',
            'orderby' => 'ASC'
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $listBrand = $ObjBrand->listBrand($params,'All');
        $this->ObjView->assign('listBrand', $listBrand);
        // Product Details Layout
        $detailsLayout = $ObjProductCategory->listLayoutDetails('details'); 
        $this->ObjView->assign("resDetailsLayout", $detailsLayout);
        $this->ObjView->assign('sysKeys', SYSTEM_DIR_KEYS);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);      
        
        $this->ObjView->display('ProductAdd.tpl');
    }
    //Add Products
    //Edit Products
    public function editAction() {
        $productID                      = $this->getRequestValue("id");       
        $ObjUsergroup                   = new UsergroupModel();
        $ObjBrand                       = new BrandModel();
        $ObjProductCategory             = new ProductCategoryModel();
        $ctab                           = $this->getRequestValue("tab");
        $languageIDs                    = $this->ObjView->languageIDs;
		//echo "<pre>";print_r($_POST);exit;
        //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');
        $this->ObjView->assign('dataResize', $dataResize);
        //URL Rewrite Settings
        $settingsRedirectUrl = $this->getSettingValue("seo_settings", "redirect_for_url");
        $settingsRedirectUrl = ($settingsRedirectUrl == "Yes") ? "Yes" : 1;
        $this->ObjView->assign('settingsRedirectUrl', $settingsRedirectUrl);
        //URL Rewrite Settings
        //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);
//                        }
//                    }
//					//$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']) {
                    $resProductOptions = $_POST['productOptionsGroup'];
                    //echo "<pre>"; print_r($resProductOptions); exit;
                    $opCount           = 0;
                    $resProductOptions = $this->optionPostback($resProductOptions);    
                    
                    $this->ObjView->assign('resProductOptions_postback', $resProductOptions);
                    $this->ObjView->assign('postCallback', '1');
            }
        }
        if (!$productID) {
            $this->setRedirect("product/new/");
        }
        $this->saveCustomAttribute();
        $this->saveCustomOption();
        //Product Clone Privilege
        $clonePrivilege = $this->ObjCommon->hasPrivilege('product/clone/');
        $this->ObjView->assign('clonePrivilege', $clonePrivilege);
        $this->productEditassign($productID);
        $paramsArray['productID'] = $productID;
        $this->bindAttributeForm($paramsArray);
        $this->bindOptionForm($paramsArray);
        $this->bindInventoryForm($paramsArray);
        $this->bindShippingForm($paramsArray);
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $listBrand = $ObjBrand->listBrand($params,'All');
        $this->ObjView->assign('listBrand', $listBrand);
        // Product Details Layout
        $detailsLayout = $ObjProductCategory->listLayoutDetails('details');
        $this->ObjView->assign("resDetailsLayout", $detailsLayout);
        if ($ctab)
            $this->ObjView->assign('ctab', $ctab);
        $this->ObjView->assign('sysKeys', SYSTEM_DIR_KEYS);
        $this->ObjView->assign('FILE_UPLOAD_LIMIT', $this->getFileUploadLimit());
        $this->ObjView->assign('VALID_IMAGE_FILES', VALID_IMAGE_FILES);
        $this->ObjView->display('ProductAdd.tpl');
    }
    //Edit Products
    //Assign Product Data
    function productAddAssign($productID, $productRequestID) {
        $ObjProduct                = new ProductModel();
        $ObjAttr                   = new AttributeModel();
        $ObjImage                  = new ImageModel();
        $ObjBusiness               = new BusinessModel();
        $ObjTaxclassModel          = new TaxclassModel();
        $ObjProductCategory        = new ProductCategoryModel();
        $ObjUser                   = new UserModel();
        $ObjProductReq             = new ProductRequestModel();
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
        $languageIDs               = $this->ObjView->languageIDs;
        //new default
        $languageIDs['Current']    = $languageIDs['Content'];
        $defaultTimeZone           = $this->getSettingValue('site_settings', 'default_timezone');
        $resBusiness               = $ObjBusiness->listBusinessInOptions($languageIDs);
        foreach ($resBusiness as $key => $business) {
            $resBusiness[$key]['label'] = $business['businessName'];
            $resBusiness[$key]['value'] = $business['businessID'];
        }    
        $resTaxClass               = $ObjTaxclassModel->listTaxClasses("", "", "", "Active", "product");
        $resAttrSet                = $ObjAttr->listAttributeSet();
        $this->ObjView->assign('defaultCurrency', $this->ObjView->_defaultCurrency);
        $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);
		
		
        $resPeriod = $ObjProduct->getDispatchTime();
        $this->ObjView->assign('resPeriod', $resPeriod);
        if (isset($_POST['submitProductDetails'])) {
            if (!empty($_POST['productCategoryID'])) {
                foreach ($_POST['productCategoryID'] as $values) {
                    $resProductcategory[] = isset($values['productCategoryID']) ? $values['productCategoryID'] : '';
                }
                $this->ObjView->assign('resProductcategory', $resProductcategory);
            }
            if (!empty($_POST['productImageThumb_temp'])) {
                $_POST['thumbPreview'] = 'Yes';
            }
        }
        
        if (isset($productRequestID) && ($productRequestID > 0)) {
            $param['languageIDs']       = $languageIDs;
            $param['selectedProductID'] = $productID;
            $resSelectproduct           = $ObjProductReq->getProductRequestDetails($param);
            $resSelectproduct           = $resSelectproduct[0];
            if (empty($resSelectproduct)) {
                $this->setRedirect("product/request/");
            }
            $resProductcategory = $ObjProductReq->listProductRequestTocategoryDetails($languageIDs, $productRequestID);
            foreach ($resProductcategory as $values) {
                $resProductcategory[] = $values['productCategoryID'];
            }
            if ($resSelectproduct['productStartTime']) {
                $productStartTime                     = explode(" ", $resSelectproduct['productStartTime']);
                $resSelectproduct['productStartTime'] = $productStartTime[0];
            }
            if ($resSelectproduct['productEndTime']) {
                $productEndTime                     = explode(" ", $resSelectproduct['productEndTime']);
                $resSelectproduct['productEndTime'] = $productEndTime[0];
            }
            $this->ObjView->assign('productDefaultCurrency', $resSelectproduct['productDefaultCurrency']);
            $this->ObjView->assign('resProductcategory', $resProductcategory);
            $this->ObjView->assign('productID', $productID);
            $this->ObjView->assign('productReqID', $productRequestID);
            $this->ObjView->assign('productRequestID', $productRequestID);
            $resProductOptions = $ObjProductReq->listProductReqOptions($languageIDs, $productRequestID, "", "", 'list');
            //optionmedia
            foreach ($resProductOptions as $key => $reslistOptions) {
                $productOptionMedia = $ObjProductReq->listRequestOptionMedia($reslistOptions['productRequestOptionID']);
                foreach ($productOptionMedia as $k => $productmedia) {
                    $result = $ObjImage->file_exist("uploads/catalog-request/product/preview-main/" . $productmedia['productMedia']);
                    if ($result) {
                        $productOptionMedia[$k]['productthumb'] = $productmedia['productMedia'];
                    }
                }
                $productOptionID                        = $reslistOptions['productRequestOptionID'];
                $resProductOptions[$key]['group_price'] = $ObjProductReq->getOptionRequestUserGroupPrice($productOptionID);
                $resProductOptions[$key]['tier_price']  = $ObjProductReq->getOptionRequestTierPrice($productOptionID);
                $resProductOptions[$key]['media']       = $productOptionMedia;
            }
            //optionmedia
            $this->ObjView->assignValues($resSelectproduct);
            $this->ObjView->assign('productStatus', 'Active');
            $this->ObjView->assign('resProductOptions', $resProductOptions);
            $this->ObjView->assign('productQuantityUnlimited', $resSelectproduct['productQuantityUnlimited']);
        }
        $resSelectproduct['productFinePrint']  = isset($resSelectproduct['productFinePrint']) ? $resSelectproduct['productFinePrint'] : '';
        $resSelectproduct['productHighlights'] = isset($resSelectproduct['productHighlights']) ? $resSelectproduct['productHighlights'] : '';
        $resSelectproduct['attributeSetID']    = isset($resSelectproduct['attributeSetID']) ? $resSelectproduct['attributeSetID'] : '';
        $resSelectproduct['parentProductID']   = isset($resSelectproduct['parentProductID']) ? $resSelectproduct['parentProductID'] : '';
        $resSelectproduct['linkProductID']     = isset($resSelectproduct['linkProductID']) ? $resSelectproduct['linkProductID'] : '';
        ##########################################################	
        $taxApplicable                         = $this->getSettingValue('product_cart_settings', 'tax_applicable');
        $this->ObjView->assign('taxApplicable', $taxApplicable);
        $this->ObjView->assign('productTimeZone', $defaultTimeZone);
        $this->ObjView->assign('resBusiness', $resBusiness);
        $currDate = $ObjProduct->getCurrentDate();
        $this->ObjView->assign('currDate', $currDate);
        $this->ObjView->assign('resTaxClass', $resTaxClass);
        $this->ObjView->assign('productFinePrint', $resSelectproduct['productFinePrint']);
        $this->ObjView->assign('productHighlights', $resSelectproduct['productHighlights']);
        //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('resSelectproduct', $resSelectproduct);
        if (!empty($resSelectproduct['productImage'])) {
            $result = $ObjImage->file_exist("uploads/catalog-request/product/preview-main/" . $resSelectproduct['productImage']);
            if ($result) {
                $this->ObjView->assign('productImageThumb', $resSelectproduct['productImage']);
                $this->ObjView->assign('thumbPreview', 'Yes');
            }
        }
        $this->ObjView->assign('resAttrSet', $resAttrSet);        
        $this->ObjView->assign('attrSetID', $resSelectproduct['attributeSetID']);
        $this->ObjView->assign('baseProductID', '');
        $this->ObjView->assign('buyboxStatus', '');
        $this->ObjView->assign('productSoldQuantity', '');
        $this->ObjView->assign('parentProductID', '');
        $this->ObjView->assign('resProducts', '');
    }
    //Assign Product Data
    //Edit section  for all product types		
    function productEditassign($productID) {
        $ObjProduct                = new ProductModel();
        $ObjProductList            = new ProductListModel();
        $ObjUser                   = new UserModel();
        $ObjBusiness               = new BusinessModel();
        $ObjTaxclassModel          = new TaxclassModel();
        $ObjImage                  = new ImageModel();
        $ObjProductCategory        = new ProductCategoryModel();
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
        $ObjAttr                   = new AttributeModel();
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
        $languageIDs               = $this->ObjView->languageIDs;
        $languageIDs['Current']    = $languageIDs['Content'];
        //$enable_cdn     =   $this->getSettingValue('site_settings', 'enable_cdn_images');	   
        $defaultTimeZone           = $this->getSettingValue('site_settings', 'default_timezone');
        $resBusiness               = $ObjBusiness->listBusinessInOptions($languageIDs);
        foreach ($resBusiness as $key => $business) {
            $resBusiness[$key]['label'] = $business['businessName'];
            $resBusiness[$key]['value'] = $business['businessID'];
        }  
        $resProducts               = $ObjProduct->getProductTitleBuybox($languageIDs);
        $resAttrSet                = $ObjAttr->listAttributeSet();
        $resTaxClass               = $ObjTaxclassModel->listTaxClasses("", "", "", "Active", "product");
        $resPeriod                 = $ObjProduct->getDispatchTime();
        $this->ObjView->assign('resPeriod', $resPeriod);
        if ($productID) {
            $paramArray['selectedProductID'] = $productID;
            $paramArray['languageIDs']       = $languageIDs;
            $paramArray['businessStatus']    = "Yes";
            $paramArray['view']              = 'Yes';
            $resSelectproduct                = $ObjProduct->getProductDetails($paramArray);
            //echo "<pre>";print_r($resSelectproduct);exit;
            $resSelectproduct                = $resSelectproduct['0'];
            if ($resSelectproduct['multiOptionsAvailable'] == 'No')
                $default = "Yes";
            else
                $default = "";
            $timezonval = $resSelectproduct['productTimeZone'];
            $this->ObjView->assign('productTimeZoneSelect', $timezonval);
            //MIC	
            $this->ObjView->assign('showCountTimer', $resSelectproduct['showCountTimer']);
            //MIC	
            if (empty($resSelectproduct)) {
                $this->setRedirect("/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);
			
			
			
			
			
		$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);
			
			
			
			
			
			
			
            //$resCategoryTree = array_slice($resCategoryTree, 1);
            $this->ObjView->assign('resCategoryTree', $resProductCategories);
            $resProductOptions = $ObjProduct->listProductOptions($languageIDs, $productID, "", $default, 'list');
            //optionmedia		
            $opCount           = 0;
            foreach ($resProductOptions as $key => $reslistOptions) {
                $productOptionID                        = $reslistOptions['productOptionID'];
                $resProductOptions[$key]['group_price'] = $ObjProduct->getOptionUserGroupPrice($productOptionID);
                $resProductOptions[$key]['tier_price']  = $ObjProduct->getOptionTierPrice($productOptionID);
                $productOptionMedia                     = $ObjProduct->listProductOptionMedia($productOptionID);
                foreach ($productOptionMedia as $k => $productmedia) {
                    $result = $ObjImage->file_exist("uploads/catalog/product/preview-main/" . $productmedia['productMedia']);
                    if ($result) {
                        $productOptionMedia[$k]['productthumb'] = $productmedia['productMedia'];
                    }
                }
                $resProductOptions[$opCount]['media'] = $productOptionMedia;
                $resBusinessOptions = $ObjProduct->getBusinessOptions($languageIDs,$productOptionID);
                if(count($resBusinessOptions)>0){
                    foreach($resBusinessOptions as $key=>$busOptions){
                        $busProductOptionID    =  $busOptions['productOptionID'];
                        $busOptBusinessID      =  $busOptions['businessID'];
                        $groupPriceValues      =  $ObjProduct->getbusinessGroupPrice($busProductOptionID,$busOptBusinessID);
                        $resBusinessOptions[$key]['group_price'] = $groupPriceValues;
                    }
                }
                $resProductOptions[$opCount]['businessOptionsGroup'] = $resBusinessOptions;
                $opCount++;
            }
            $resBusinessComb            =       $ObjBusiness->listBusinessInOptions($languageIDs,0,"","","","","","","","Yes",$resProductOptions[0]['productOptionID']);
            $this->ObjView->assign('resBusinessComb', $resBusinessComb);
            //optionmedia
            $resProductcategory = $ObjProduct->listProductTocategoryDetails($languageIDs, $productID);
            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);
            $this->ObjView->assign('selectProductImages', isset($selectProductImages) ? $selectProductImages : '');
            if (isset($_POST['submitProductDetails'])) {
                if (!empty($_POST['productCategoryID'])) {
                    foreach ($_POST['productCategoryID'] as $values) {
                        if (isset($values['productCategoryID']))
                            $resProductcategory[] = $values['productCategoryID'];
                    }
                    $this->ObjView->assign('resProductcategory', $resProductcategory);
                }
                $this->ObjView->assign('buyboxStatus', $_POST['buyboxStatus']);
            }
        } 
		//echo "<pre>";print_r($resProductcategory);exit;
        $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);
        }
        $freeProducts = $ObjProductList->getFreeProducts($productID);
        if (!empty($freeProducts)) {
            $paramArray['relIDs']       = $freeProducts;
            $resRightFreeProducts       = $ObjProductList->getProductsForRelated($paramArray);
            $this->ObjView->assign('resRightFreeProducts', $resRightFreeProducts);
            $productFreeProducts        = implode("~*", $freeProducts);
            $this->ObjView->assign('$productFreeProducts', $productFreeProducts);
        }
		
		if(isset($categoryIDList))
		$categoryList = implode(",", $categoryIDList);
		else
		$categoryList ="";		
	
        $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('resTaxClass', $resTaxClass);
        $this->ObjView->assign('productFinePrint', $resSelectproduct['productFinePrint']);
        $this->ObjView->assign('productTitle', $resSelectproduct['productTitle']);
        $this->ObjView->assign('productHighlights', $resSelectproduct['productHighlights']);
        $this->ObjView->assign('productDescription', $resSelectproduct['productDescription']);
        $this->ObjView->assign('productCommissionRate', $resSelectproduct['productCommissionRate']);
        $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->ObjView->_defaultCurrency);
        $this->ObjView->assign('resSelectproduct', $resSelectproduct);
        $this->ObjView->assign('resProducts', $resProducts);
        if (!empty($resSelectproduct['productImage'])) {
            $result = $ObjImage->file_exist("uploads/catalog/product/preview-main/" . $resSelectproduct['productImage']);
            if ($result) {
                $this->ObjView->assign('productImageThumb', $resSelectproduct['productImage']);
                $this->ObjView->assign('thumbPreview', 'Yes');
            }
        }
        $this->ObjView->assign('resAttrSet', $resAttrSet);
        $this->ObjView->assign('resSelectproduct', $resSelectproduct);
    }
    //End
    //Product Edit for All producttypes		
    public function ProductEditform($productID) {
        $ObjProduct                = new ProductModel();
        $languageIDs               = $this->ObjView->languageIDs;
        $languageIDs['Current']    = $languageIDs['Content'];
        $imageFlag                 = 0;
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
        $product_sef_format                 = $this->getSettingValue('seo_settings', 'product_sef_format');
        $product_sef_format=    isset($product_sef_format)  ? $product_sef_format   : false;
        $_POST['productStartTime'] = $this->convertDateForSQL($_POST['productStartTime'], $settingsDateFormat);
        $_POST['productEndTime']   = $this->convertDateForSQL($_POST['productEndTime'], $settingsDateFormat);
        //URL Rewrite Settings	
        $settingsUrlSuffix         = $this->getSettingValue("seo_settings", "product_url_suffix");
        //URL Rewrite Settings
        if (empty($_POST['productUrl']))
            $_POST['productUrl'] = $this->ObjCommon->generateKey("product", $_POST["productTitle"]);
        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);
            //EXIT;
        } else
            $_POST['productImage'] = $_POST['hidMainImage'];
        //ProductActiveFromANd To
        $_POST['layoutActiveFrom']     = $this->convertDateForSql($_POST['layoutActiveFrom'], $settingsDateFormat);
        $_POST['layoutActiveTo']       = $this->convertDateForSql($_POST['layoutActiveTo'], $settingsDateFormat);
        $_POST['ProductDetailsLayout'] = $_POST['productDetailsLayout'];
		//echo "<pre>";print_r($_POST);exit;
        $productID                     = $ObjProduct->saveProduct($languageIDs, $_POST, $productID);
        //URL Rewrite 							
        $args                          = array(
            'productUrl' => $_POST['productUrl']
        );
        $Urlrewrite                    = new UrlrewriteModel();
        $SefModel                      = new SefModel();
        if ($_POST['oldProductUrl'] != $_POST['productUrl']) {
            $_POST['redirectOption'] = isset($_POST['redirectOption']) ? $_POST['redirectOption'] : '';
            $SefModel->_refreshProductRewrites($languageIDs['AllList'], $productID, $settingsUrlSuffix, $args, $_POST['redirectOption'],$product_sef_format);
        }
        
        if($product_sef_format){
            $catEsixts = $Urlrewrite->getproductCategories($productID);
            $catEsixts = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($catEsixts)), 0);
                
            if(!empty($_POST['productCategoryID'])) {                
                $categoryIDs  = explode(",",$_POST['productCategoryID'][0]);                
                foreach ($categoryIDs as $key => $category) {
                    
                    if($category>0) {
                        $args['category']        = $category;
                        $action                  = (!(in_array($category, $catEsixts))) ? 'insert' : '';
                       
                        $_POST['redirectOption'] = isset($_POST['redirectOption']) ? $_POST['redirectOption'] : '';
                        if ($_POST['oldProductUrl'] != $_POST['productUrl'] || !(in_array($category, $catEsixts)))
                            $SefModel->_refreshProductRewrites($languageIDs['AllList'], $productID, $settingsUrlSuffix, $args, $_POST['redirectOption'],$product_sef_format, $action);
                    }
                }

                $deletedCat = array_diff($catEsixts, $categoryIDs);
                //echo "<pre>";print_r($deletedCat);exit;
                if ($deletedCat)
                    $Urlrewrite->deleteUrlRewrites(implode(",", $deletedCat), "product", $productID);
            }
         }
        $this->setMessage("language.msgProductDetailsSave", "success");
        $this->setRedirect("product/edit/id/" . $productID . "/");
    }
    //End
    //To save All Products
    public function ProductAddform($productID = '', $productRequestID = '') {
        $ObjProduct  = new ProductModel();
        $languageIDs = $this->ObjView->languageIDs;
        $msgCu       = '';
        $product_sef_format                 = $this->getSettingValue('seo_settings', 'product_sef_format');
        $product_sef_format=    isset($product_sef_format)  ? $product_sef_format   : false;
        $ObjImage    = new ImageModel();
        if ($productRequestID == '')
            $languageIDs['Current'] = $languageIDs['Content'];
        $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
        $_POST['productStartTime'] = $this->convertDateForSQL($_POST['productStartTime'], $settingsDateFormat);
        $_POST['productEndTime']   = $this->convertDateForSQL($_POST['productEndTime'], $settingsDateFormat);
        $_POST['shippingSetting']  = $this->getSettingValue('shipping_settings', 'shipping_origin_type');
        //URL Rewrite Settings		
        $settingsUrlSuffix         = $this->getSettingValue("seo_settings", "product_url_suffix");
        if (empty($_POST['productUrl']))
            $_POST['productUrl'] = $this->ObjCommon->generateKey("product", $_POST["productTitle"]);
        //URL Rewrite Settings
        //ProductActiveFromANd To
        $_POST['layoutActiveFrom']     = $this->convertDateForSql($_POST['layoutActiveFrom'], $settingsDateFormat);
        $_POST['layoutActiveTo']       = $this->convertDateForSql($_POST['layoutActiveTo'], $settingsDateFormat);
        $_POST['ProductDetailsLayout'] = $_POST['productDetailsLayout'];
        if ($_POST['shippingSetting'] == 'admin') {
            $_POST['shippingOrigin'] = '0';
        } else {
            $_POST['shippingOrigin'] = 'NULL';
        }
        $productImage = $_POST['productImage'];
        if (isset($productImage) && $productImage != '') {
            if ($productRequestID > 0) {
                $upload_images = $this->getSettingValue('site_settings', 'upload_images_to');
                $main_path     = __DIR_PUBLIC . '/' . __UPLOADS_FOLDER . 'catalog-request/product/large/' . $_POST['productImage'];
                /*if($upload_images != 'filesystem'){	
                $main_path_new = $ObjImage->copy_to_temp(__DIR_PUBLIC . '/'.__UPLOADS_FOLDER.'catalog-request/product/large/'.$_POST['productImage']);
                $main_path =__DIR_PUBLIC . '/'.__UPLOADS_FOLDER.'temp/'.$main_path_new;
                }*/
                $thumb_reqImg  = __UPLOADS_FOLDER . 'catalog-request/product/preview-main/' . $_POST['productImage'];
                $thumb_path    = __DIR_PUBLIC . '/' . $thumb_reqImg;
                //Request Thumb Exist
                if ($_POST["productImageThumb_temp"] == '' && $_POST["productImageThumb"]) {
                    if ($ObjImage->file_exist($thumb_reqImg))
                        $_POST["productImageThumb_temp"] = $thumb_path;
                }
                if ($_POST["productImage_temp"] == '' && $_POST["productImage"] != '') {
                    $_POST["productImage_temp"] = $main_path;
                    $_POST['productImage']      = $productImage = $ObjProduct->getImageName($_POST['productImage']);
                }
                $paramMedia['imageType'] = 'request';
            }
            $paramMedia['productImage']    = $_POST['productImage'];
            $paramMedia['mainImage_temp']  = $_POST["productImage_temp"];
            $paramMedia['thumbImage_temp'] = $_POST["productImageThumb_temp"];
            $paramMedia['mainImage']       = $productImage;
            $paramMedia['destFolder']      = 'product';
            $paramMedia['mediaParam']      = $_POST['dataResize'];
            $_POST['mediaParam']           = $_POST['dataResize'];
            $paramMedia['productID']       = $productID;
            $_POST['productImage']         = $ObjProduct->generateMedia($paramMedia);
        }
        if ($productID && $productRequestID) {
            $productID = $ObjProduct->saveProduct($languageIDs, $_POST, "", $productRequestID, false);
            $ObjProduct->assignShippingToProduct($productRequestID, $productID);
            $ObjProduct->assignRequestAttributesToProduct($productRequestID, $productID, $languageIDs);
        } else {
            $productID = $ObjProduct->saveProduct($languageIDs, $_POST, "");
            $ObjProduct->assignDefaultSmService($productID);
        }
        if ($productID && $productRequestID) {
            $_POST['productRequestID'] = $productRequestID;
            $ObjProduct->changeProductRequestStatus("Approved", $productRequestID);
            //SEND Approved mail to business user						
            $this->productapproval($productID);
        }
        //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
        $this->setMessage($this->getLanguageValue("msgAddProduct") . $msgCu, "success");
        $this->setRedirect("product/edit/id/" . $productID . "/");
        $this->ObjView->assign('dataResize', $dataResize);
    }
    //End
    //Product Approval Mail
    public function productapproval($productID) {
        $ObjEmailtemplate       = new EmailtemplateModel();
        $ObjProduct             = new ProductModel();
        $ObjBusiness            = new BusinessModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $resbusinessDetails     = $ObjBusiness->getBusinessBasic($_POST['businessID'], $languageIDs);
        $languageIDs['Current'] = $resbusinessDetails['businessDefaultLanguageID'];
        $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-request-approved');
        $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);
        $bodytag = str_replace('{$url}', rtrim($siteUrl, "/") . '/business/product/show/id/' . $productID . '/', $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("email_templates/Layout.tpl", $languageIDs);
        ;
        $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()) {
        }
    }
    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              = isset($paramsArray['productID']) ? $paramsArray['productID'] : '';
        $productRequestID       = isset($paramsArray['productRequestID']) ? $paramsArray['productRequestID'] : '';
        $bindAttributeForm      = 0;
        if ($productID > 0 || $productRequestID > 0) {
            $bindAttributeForm                        = 1;
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = $productRequestID;
            $customAttributeArray['attributeSetID']   = ($attrSetID=='') ? $ObjProduct->getAttrSetID($productID):$attrSetID;
            $resAttributes                            = $ObjAttribute->listProductAttributes($languageIDs, $customAttributeArray);
            $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);
            }
            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) {
                        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);
    }
    //Ajax Reload Custom attributes
    public function ajaxReloadCustomAttributesAction() {
        $productID                         = $this->escape($_POST["productID"]);
        $productRequestID                  = $this->escape($_POST["productRequestID"]);
        $paramArray['productID']           = $productID;
        $paramArray['productRequestID']    = $productRequestID;         
        $paramArray['attributeSetID']      = $this->escape($_POST["attrSetID"]);
        if($paramArray['attributeSetID'])
            $paramArray['excludePostCallback'] = '';
        else {
            $paramArray['excludePostCallback'] = 'Yes';
        }
        
        $this->bindAttributeForm($paramArray,$paramArray['attributeSetID'],$_POST["prevAttrSetID"]);
        $this->ObjView->assign('productID', $productID);
        $this->ObjView->assign('productReqID', $productRequestID);
        $this->ObjView->assign('selAttrSetID', $_POST["attrSetID"]);
        $this->ObjView->assign('productRequestID', $productRequestID);
        $this->ObjView->display('CustomAttributeAjax.tpl');
    }
    //Custom Attribute save
    public function saveCustomAttribute() {
        $ObjAttribute           = new AttributeModel();
        $productID              = $this->getRequestValue("id");
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($this->ObjForm->isValid('formCustomAttributeAdd', 'submitAttributeDetails')) {
            $_POST['settingsDateFormat'] = $this->getSettingValue('site_settings', 'date_format');
            $POST                        = $_POST;
            $FILES                       = $_FILES;
            $ObjAttribute->assignCustomAttributeToProduct($languageIDs, $productID, $POST, $FILES);
            $this->setMessage("language.msgAttributeUpdate", "success");
            $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 > 0 || $attrReqValueID > 0) {
            if ($attrReqValueID) {
                $image_loc = "catalog-request";
                $fileName  = $ObjAttribute->getAttributeFile($languageIDs, $attrReqValueID, 'Yes');
            } else {
                $image_loc = "catalog";
                $fileName  = $ObjAttribute->getAttributeFile($languageIDs, $attrValueID);
            }
            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']);
            }
        }
    }
    //Get Default Currency	
    public function ajaxgetDefaultCurrencyAction() {
        //echo $this->getSettingValue('site_settings', 'default_currency');exit;
        echo $this->ObjView->_defaultCurrency;exit;
    }
    //Retain Option Data For PostBack
    public function optionPostback($resProductOptions) {
        //echo "<pre>"; print_r($resProductOptions); exit;
        $ObjImage = new ImageModel();
        $ObjBusiness = new BusinessModel();
        $languageIDs            = $this->ObjView->languageIDs;
        if (!empty($_POST["productRequestID"]))
            $loc = "catalog-request";
        else
            $loc = "catalog";
        if (isset($resProductOptions) && $resProductOptions != '' && count($resProductOptions) > 0) {
          
            foreach ($resProductOptions as $key=>$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++) {
                    $productImg = $_POST["productOptionImage_" . $option_count . '_' . $i];
                    //$productImageType=$_POST["productOptionImage_" .$option_count.'_'. $i . "_temp"];
                    if (!empty($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;
                //echo "<pre>"; print_r($reslistOptions['businessOptionsGroup']);
                foreach($reslistOptions['businessOptionsGroup'] as $busGroupKey=>$busGroupVal){
                    if($busGroupVal['assignBusinessID']>0){
                        $busidVal       =   $busGroupVal['assignBusinessID'];
                    }else{
                        $busidVal       =   $busGroupVal['hiddenBusinessID'];
                    }
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['businessName']  =  $ObjBusiness->getBusinessNameByBusID($languageIDs,$busidVal);
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['productOptionBusinessID']  =  $busGroupVal['hiddenProductOptionBusinessID'];
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['businessID']  =  $busidVal;
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['productOptionRegularPrice']  =  $busGroupVal['businessOptionReqPrice'];
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['productOptionProductPrice']  =  $busGroupVal['businessOptionSalePrice'];
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['dealPrice']  =  $busGroupVal['businessOptionDealPrice'];
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['productOptionQuantity']  =  $busGroupVal['businessQuantity'];
                    $resProductOptions[$key]['businessOptionsGroup'][$busGroupKey]['busWareHouse']  =  $busGroupVal['businessWareHouse'];
                }
                
                $opCount                                   = isset($opCount) ? $opCount : 0;
                $opCount++;
            }
        }
        //echo "<pre>"; print_r($resProductOptions); exit;
        return $resProductOptions;
    }
    // CHANGE Product Status
    public function ajaxChangeStatusAction() {
        $ObjProduct            = new ProductModel();
        $_POST['changeStatus'] = 'Deleted';
        $did                   = $_POST['did'];
        $statusChange          = $ObjProduct->changeProductStatus($did);
        $ObjUrl                = new UrlrewriteModel();
        $ObjUrl->deleteUrlRewrites('', 'product', $did);
        $this->setMessage("language.msgproductDelete", 3);
        echo 1;
    }
    //Bind Custom Option 			 
    public function bindOptionForm($paramsArray = array()) {
        $ObjCustom              = new CustomOptionModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = isset($paramsArray['productID']) ? $paramsArray['productID'] : '';
        $productRequestID       = isset($paramsArray['productRequestID']) ? $paramsArray['productRequestID'] : '';
        $bindOptionForm         = 0;
        if ($productID > 0 || $productRequestID > 0) {
            $bindOptionForm                           = 1;
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = $productRequestID;
            $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);
    }
    //Bind Inventory	
    public function bindInventoryForm($paramsArray = array()) {
        $ObjCustom              = new CustomOptionModel();
        $ObjProduct             = new ProductModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = isset($paramsArray['productID']) ? $paramsArray['productID'] : '';
        $productRequestID       = isset($paramsArray['productRequestID']) ? $paramsArray['productRequestID'] : '';
        $bindOptionForm         = 0;
        $variantIDs             = array();
        if ($productID > 0 || $productRequestID > 0) {
            $bindInventoryForm                        = 1;
            $customAttributeArray['productID']        = $productID;
            $customAttributeArray['productRequestID'] = $productRequestID;
            $customAttributeArray['excludeVariant']   = "Yes";
            $customAttributeArray['status']           = "A";
            $resCombAttributes                        = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
            $i                                        = 0;
            foreach ($resCombAttributes as $options) {
                $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);
        }
        $params       = array(
            'productID' => $productID,
            'view' => 'Yes',
            'status' => 'All',
            'languageID' => $languageIDs['Current'],
            'checkBusinessComb' => 'Yes' 
        );
        $productCombo     = $ObjCustom->getProductCustomCombination($params);
        $productComboMini = $ObjCustom->getProductCustomCombinationMini($params);
        /*$count        = 0;
        foreach ($productCombo as $combo) {
            $comboID     = $combo['combinationID'];
            $Combination = '';
            $comboArray  = $ObjCustom->getCombinationVariants($languageIDs, $combo['combination']);
            if (count($comboArray) > 0) {
                foreach ($comboArray as $combostr) {
                    if ($Combination)
                        $Combination .= ",";
                    $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                    $variantIDs[]                        = isset($combostr['customOptionVariantID']) ? $combostr['customOptionVariantID'] : '';
                    $productCombo[$count]['variantID'][] = isset($combostr['customOptionVariantID']) ? $combostr['customOptionVariantID'] : '';
                }
            }
            $productCombo[$count]['ProductCombo'] = $Combination;
            $productCombo[$count]['soldQunatity'] = $ObjProduct->getSoldQuantity($combo['combinationHash']);
            $count++;
        }*/
        $resproductCombo = array();
        $resproductStock = array();
        $resproductComboMini = array();
        $resproductStockMini = array();
        if(!empty($productCombo)) {
            $resproductCombo = $productCombo['results'];
            $resproductStock = $productCombo['stock'];
        }
        if(!empty($productComboMini)) {
            $resproductComboMini = $productComboMini['results'];
            $resproductStockMini = $productComboMini['stock'];
        }
        //echo "<pre>";print_r($resproductStock);exit;
        $this->ObjView->assign('resproductCombo', $resproductCombo);        
        $this->ObjView->assign('resproductStock', $resproductStock);
        $this->ObjView->assign('resproductComboMini', $resproductComboMini);        
        $this->ObjView->assign('resproductStockMini', $resproductStockMini);
        $this->ObjView->assign('bindInventoryForm', $bindInventoryForm);
    }
    public function bindShippingForm($paramsArray = array()) {
        $ObjDelzone             = new DeliveryZoneModel();
        $ObjProduct             = new ProductModel();
        $ObjShipMethod          = new ShippingmethodModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $productID              = isset($paramsArray['productID']) ? $paramsArray['productID'] : '';
        $productRequestID       = isset($paramsArray['productRequestID']) ? $paramsArray['productRequestID'] : '';
        $BusinessID             = isset($paramsArray['BusinessID']) ? $paramsArray['BusinessID'] : '';
        $bindShippingForm       = 0;
        if ($productID > 0 || $productRequestID > 0) {
            $bindShippingForm     = 1;
            $shipping_origin_type = $this->getSettingValue('shipping_settings', 'shipping_origin_type');
            $resBasic             = $ObjProduct->getBasicByproductID($productID);
            $this->ShippingAssign($productID, $resBasic['businessID']);
            $shippingSetting = $resBasic['shippingSetting'];
            $BusinessID      = $resBasic['businessID'];
            $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);
    }
    //Import Global Options	
    public function importGlobalOptionAction() {
        $ObjCustom                   = new CustomOptionModel();
        $ObjProduct                  = new ProductModel();
        $languageIDs                 = $this->ObjView->languageIDs;
        $languageIDs['Current']      = $languageIDs['Content'];
        $scope                       = $this->escape($this->decodeUrlString($this->getRequestValue("scope")));
        $productID                   = $this->escape($this->getRequestValue("productID"));
        $productRequestID            = $this->escape($this->getRequestValue("productRequestID"));
        $resBasic                    = $ObjProduct->getBasicByproductID($productID, $productRequestID);
        $saveParamArray['proUriKey'] = $resBasic['productUrl'];
        if (($productID > 0 || $productRequestID > 0)) {
            if (isset($_POST["customOptionIDs"]) && $_POST["customOptionIDs"] != '') {
                $saveParamArray['customOptionIDs']       = $_POST["customOptionIDs"];
                $saveParamArray['AsLinkcustomOptionIDs'] = $_POST["AsLinkcustomOptionIDs"];
                $saveParamArray['productID']             = $productID;
                $saveParamArray['productRequestID']      = $productRequestID;
                $ObjCustom->importGlobalOptions($languageIDs, $saveParamArray);
                echo '<script type="text/javascript">parent.$.colorbox.close();parent.reloadCustomOptions(3);</script>';
                exit;
            }
            $languageIDs['Current']                       = $languageIDs['Content'];
            $attributeParams['excludeImportedAttributes'] = 'Yes';
            $attributeParams['status']                    = 'A';
            $attributeParams['isGlobal']                  = '1';
            $attributeParams['productID']                 = $productID;
            $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('productRequestID', $productRequestID);
        $this->ObjView->display('ProductCustomOptionAjax.tpl');
    }
    //Custom Option save
    public function saveCustomOption() {
        $ObjCustom              = new CustomOptionModel();
        $productID              = $this->getRequestValue("id");
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($this->ObjForm->isValid('formCustomOptionAdd', 'submitOptionDetails')) {          
            $ObjCustom->assignCustomOptionToProduct($languageIDs, $productID, $_POST);
            $this->setMessage("language.msgOptionUpdate", "success");
            $this->setRedirect("product/edit/id/" . $productID . "/tab/coption/");
        }
    }
    //Ajax Add/Update Combinations 	
    public function ajaxAddCombinationAction() {
        $ObjCustom                     = new CustomOptionModel();
        $ObjUsergroup                  = new UsergroupModel();
        $ObjProduct                    = new ProductModel();
        $ObjBusiness                   = new BusinessModel();
        $ObjImage                      = new ImageModel();
        $languageIDs                   = $this->ObjView->languageIDs;
        $languageIDs['Current']        = $languageIDs['Content'];
        $actionForm                    = "formComboAdd";
        $actionButton                  = 'submitCombo';
        $variantIDs                    = array();
        $_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['businessID']            = $resProBasic['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();
                if ($rescombo != 3 && $rescombo != 4) {
                    $params       = array(
                        'productID' => $_POST['productID'],
                        'view' => 'Yes',
                        'status' => 'All',
                        'languageIDs' => $languageIDs,
                        'checkBusinessComb' => 'Yes'
                    );
                    //selct whole data			
                    $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]['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);
                    exit;
                } else {
                    $returnData['validationError'] = 'No';
                    $returnData['message']         = $rescombo;
                    echo json_encode($returnData);
                    exit;
                }
            } else {
                $returnData['validationError'] = 'Yes';
                echo json_encode($returnData);
                exit;
            }
        } else {
            $productID                              = $_POST['productID'];
            $combinationID                          = $_POST['combinationID'];
            $customAttributeArray['excludeVariant'] = "Yes";
            $customAttributeArray['productID']      = $productID;
            $resCombAttributes                      = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
            $i                                      = 0;
            foreach ($resCombAttributes as $options) {
                $variantArray                     = $ObjCustom->getCustomOptionVariants($languageIDs, $options['customOptionID']);
                $resCombAttributes[$i]['variant'] = $variantArray;
                $i++;
            }
            $this->ObjView->assign('resCombAttributes', $resCombAttributes);
            $comboDetails = $ObjCustom->getProductCombinationByID($combinationID);
            if (!empty($comboDetails['productMedia'])) {
                $fileName     = "uploads/catalog/product-combination/preview-main/" . $comboDetails['productMedia'];
                $MainfileName = "uploads/catalog/product-combination/large/" . $comboDetails['productMedia'];
                if ($ObjImage->file_exist($fileName)) {
                    $this->ObjView->assign('combothumbPreview', 'Yes');
                    $this->ObjView->assign('comboThumb', $comboDetails['productMedia']);
                } else
                    $this->ObjView->assign('comboThumb', "");
                if ($ObjImage->file_exist($MainfileName)) {
                    $this->ObjView->assign('hidComboMain', $comboDetails['productMedia']);
                } else
                    $this->ObjView->assign('hidComboMain', '');
            }
            $combinationArray = explode('_', $comboDetails['combination']);
            unset($combinationArray[0]);
            if($comboDetails['combinationID']>0){
                $comboBusinessDetails   =   $ObjCustom->getProductBusinessCombination($languageIDs,$comboDetails['combinationID']);
                $comboDetails['comboBusinessDet']   =   $comboBusinessDetails;
            }
            $productOptionID        =       $ObjProduct->getDefaultOptionID($productID);
            $resBusinessComb        =       $ObjBusiness->listBusinessInOptions($languageIDs,0,"","","","","","","","Yes",$productOptionID);
            $this->ObjView->assign('resBusinessComb', $resBusinessComb);
            $this->ObjView->assign('comboDetails', $comboDetails);
            $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);
            exit;
            //return true;   
        }
    }
    //Ajax Add/Update Shipping Method  
    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 ($resship != 3) {
                    //selct whole data			
                    $productShip = $ObjProduct->getProductShippings($_POST['productID'], $languageIDs, ((isset($_POST['productRequestID'])) ? $_POST['productRequestID'] : ''));
                    $this->ObjView->assign('resproductShip', $productShip);
                    $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 if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'RL') {
            $productID = $_POST['productID'];
            $this->ShippingAssign($productID, $_POST['merchantID']);
            $html                 = $this->ObjView->fetch('AddProductShipBlock.tpl');
            $returnData['action'] = 'Show';
            $returnData['html']   = $html;
            echo json_encode($returnData);
            exit;
        } else {
            $productID  = $_POST['productID'];
            $shippingID = $_POST['shippingID'];
            $this->ShippingAssign($productID, $_POST['merchantID']);
            $shipDetails = $ObjProduct->getProductShippingByID($shippingID);
            $resTaxClass = $ObjTaxclassModel->listTaxClasses("", "", "", "Active", "product");
            $this->ObjView->assign('resTaxClass', $resTaxClass);
            $dZones       = $ObjProduct->getZonesByShippingID($shippingID);
            if(!empty($dZones))
                $dZonesString = implode("~*", $dZones);
            else
                $dZonesString = '';
            $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;
        }
    }
    //Ajax Delete Combination	
    public function AjaxDestroyComboAction() {
        $ObjCustom    = new CustomOptionModel();
        $_POST['id']  = $_POST['comboID'];
        $statusUpdate = $ObjCustom->updateComboStatus($_POST);
        echo "1";
    }
    //Ajax Delete Shipping
    public function AjaxDestroyShipAction() {
        $ObjProduct  = new ProductModel();
        $_POST['id'] = $_POST['shipID'];
        if (!isset($_POST['status'])) {
            $_POST['status'] = 'D';
        }
        $statusUpdate = $ObjProduct->updateProShipStatus($_POST);
        echo "1";
    }
    //Assign shipping Values
    public function ShippingAssign($productID, $businessID) {
        $ObjDelzone             = new DeliveryZoneModel();
        $ObjProduct             = new ProductModel();
        $ObjShipMethod          = new ShippingmethodModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $resDelZones            = $ObjDelzone->listDeliveryZones($languageIDs, '', '', '', 'Active', 'options', '', $businessID);
		//echo "<pre>";print_r($resDelZones);exit;
        $resSmService           = $ObjShipMethod->groupSmServices();
        $productShip            = $ObjProduct->getProductShippings($productID, $languageIDs);
        $this->ObjView->assign('resproductShip', $productShip);
        $this->ObjView->assign('resDelZones', $resDelZones);
        $this->ObjView->assign('resSmService', $resSmService);
        $this->ObjView->assign('productID', $productID);
        $this->ObjView->assign('productRequestID', isset($productRequestID) ? $productRequestID : '');
        $this->ObjView->assign('merchantID', $businessID);
        $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 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;
    }
    //Reload Combo   
    public function AjaxReloadAddComboAction() {
        $productID              = $_POST['productID'];
        $ObjCustom              = new CustomOptionModel();
        $ObjProduct             = new ProductModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $resProductOptionMenu   = $ObjProduct->getProductOptionsDetails($languageIDs, $productID);
        $this->ObjView->assign('resProductOptionMenu', $resProductOptionMenu);
        $customAttributeArray['excludeVariant'] = "Yes";
        $customAttributeArray['productID']      = $productID;
        $resCombAttributes                      = $ObjCustom->listCustomProductOption($languageIDs, $customAttributeArray);
        $i                                      = 0;
        foreach ($resCombAttributes as $options) {
            $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;
    }
    //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              = trim($data['value']);
        $count            = 1;
        //Product Add n Edit,From Post Value
        $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];
        }
        $option_id       = ($productRequestID > 0) ? 0 : $option_id;
        $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, '', $businessID)) {
            return true;
        } else {
            return false;
        }
    }
    //To check ProductUrl already exist.  for Callback validdation in product list and edit.	
    function checkComSKUexist($data) {
        $SKU = $data['value'];
        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;
        }
    }
    //Bulk Export 
    public function ExportAction() {
        $patternID          = $this->getRequestValue("pattern");
        $ObjExim            = new EximModel();
        $ObjProduct         = new ProductModel();
        $ObjCustom          = new CustomOptionModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $ObjAttr            = new AttributeModel();
        $ObjBusiness        = new BusinessModel();
        $ObjBrand           = new BrandModel();
        $ObjProductCategory = new ProductCategoryModel();
        $resBusiness        = $ObjBusiness->listBusinessInOptions($languageIDs);
        $resAttrSet         = $ObjAttr->listAttributeSet();
        $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);
        $params     = array(
            'languageIDs' => $languageIDs
        );
        $listBrand  = $ObjBrand->listBrand($params,'All');
        $resAttrSet = $ObjAttr->listAttributeSet();
        $ListAll    = array(
            0 => 'all',
            'attributeSetID' => 'all',
            1 => 'All',
            'attributeSetName' => 'All'
        );
        array_unshift($resAttrSet, $ListAll);
        $this->ObjView->assign('resAttrSet', $resAttrSet);
        $this->ObjView->assign('resBusiness', $resBusiness);
        $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("lblProdctDeal") => "Prodct Deal",
            $this->getLanguageValue("lblDealDiscount") => "Deal Discount(%)",
            $this->getLanguageValue("lblDealStartDate") => "Deal Start Date",
            $this->getLanguageValue("lblDealEndDate") => "Deal End Date",
            $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 == 'attribute')
            $this->ObjView->assign("atab", 1);
        elseif ($ctab == 'pdt') {
            $this->ObjView->assign("ptab", 1);
        }
        elseif ($ctab == 'customoption') {
            $this->ObjView->assign("cttab", 1);
        }
        
        //if (!empty($layout_data)) {
        if (!empty($_POST)) {
            
            
            $setID                   = $_POST['export_options']['attributeSetID'];
            $businessID              = $_POST['export_options']['businessID'];
            $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['searchProductCategory']) ? $_POST['searchProductCategory'] : '';
            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","Deal 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,$_POST['export_options']['languageID']);
                $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,$_POST['export_options']['languageID']);                
                $ctab    = "image";
            } elseif ($_POST['pattern_id'] == "product_attributes") {
                
                $resProd      = $ObjProduct->getProductsBysetID($setID, $businessID, $limitFrom, $limitTo, $brandID, $searchProductCategories);
                $count        = count($resProd);
                $layout_data  = array('Product ID','Product SKU','Business name','Product Name','Attributes');
                $attrParamArray['attributeSetID'] = $setID;
                $attrParamArray['productID']      = '';
                $attrParamArray['attrStatus']     = 'A';
                $attrParamArray['mode']           = 'attributeSet';
                $attrLangIDs                      = $languageIDs;
                $attrLangIDs['Current']           = $_POST['export_options']['languageID']; 
                $attrType                         = ($setID>0)?'':'Y';
                $getattrDet   = $ObjAttr->listAttributesGroupWise($attrLangIDs,$attrParamArray,$attrType);
                if(!empty($getattrDet)) {
                    foreach($getattrDet as $det) {
                        $layout_data['Attributes'][$det['attributeID']] =  $det['attributeKey'];//($setID>0)?'{'.$det['attributeID'].'}('.$det['name'].') '.$det['attrName']:'{'.$det['attributeID'].'} '.$det['attrName'];
                    }
                }  
                //array_unshift($layout_data, "SKU", "Attributes",  "Product ID");
                $pattern = $ObjExim->getAttributesSchema($setID, $businessID,$_POST['export_options']['languageID']);                         
                $ctab    = "attribute";
            } elseif ($_POST['pattern_id'] == "product_custom_options") {
                $resProd      = $ObjProduct->getProductsBysetID($setID, $businessID, $limitFrom, $limitTo, $brandID, $searchProductCategories);
                $count        = count($resProd);
                //array_unshift($layout_data, "SKU", "Custom Options",  "Product ID");
                $layout_data  = array('Product ID','Product SKU','Business name','Product Name','Custom Options');
                $custLangIDs                      = $languageIDs;
                $custLangIDs['Current']           = $_POST['export_options']['languageID']; 
                $resoptions                       = $ObjCustom->listCustomProductOption($custLangIDs, array());
                if(!empty($resoptions)) {
                    foreach($resoptions as $det) {
                        $layout_data['Custom Options'][$det['customOptionID']] = $det['customOptionName']."-".$det['customOptionID'];
                    }
                }  
                $pattern = $ObjExim->getCustomOptionsSchema($setID, $businessID,$_POST['export_options']['languageID']);                 
                $ctab    = "customoption"; 
            }
            if ($count > 0) {  
                $_POST['export_options']['pattern_id'] = $_POST['pattern_id'];                
                $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("attributeexportArray", array());
        $this->ObjView->assign("customoptionexportArray", array());
        $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;
        $ObjBusiness                            = new BusinessModel();
        $resBusiness                            = $ObjBusiness->listBusinessInOptions($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;
        $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("lblProdctDeal"),
            $this->getLanguageValue("lblDealDiscount"),
            $this->getLanguageValue("lblDealStartDate"),
            $this->getLanguageValue("lblDealEndDate"),
            $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"
        );
        $attrexportArray                        = array(
            $this->getLanguageValue("lblProductID"),
            $this->getLanguageValue("lblSKU"),
            $this->getLanguageValue("lblBusinessName"),
            $this->getLanguageValue("lblProductName"),            
            $this->getLanguageValue("lblAttributes")            
        );
        $attrReq                           = array(
            "SKU",
            "Attributes"            
        );
        $customexportArray                        = array(
            $this->getLanguageValue("lblProductID"),
            $this->getLanguageValue("lblSKU"),
            $this->getLanguageValue("lblBusinessName"),
            $this->getLanguageValue("lblProductName"),            
            $this->getLanguageValue("lblCustomOptions")            
        );
        $customReq                           = array(
            "SKU",
            "Global Custom Options"            
        );
        
        //TAB SETTINGS
        $cstatus                                = $this->getRequestValue("cstatus");
        $ctab                                   = $this->getRequestValue("ctab");
        if ($cstatus == 'imported') {
            $count_log = $this->ObjSession->getSession("count_log");
            //print_r($this->ObjSession->getSession("count_log"));exit;
            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"));
        } elseif ($ctab == 'attributes') {
            $this->ObjView->assign("atab", 1);
            $this->ObjView->assign("pattern", $this->getLanguageValue("lblProductAttributes"));
        } elseif ($ctab == 'custom_options') {
            $this->ObjView->assign("cttab", 1);
            $this->ObjView->assign("pattern", $this->getLanguageValue("lblCustomOptions"));
        } 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'] = $_POST['import_options']['businessID'];
            $post_process['languageID'] = $_POST['import_options']['languageID'];
            $_POST['import_options']['lang_code'] = $this->ObjCommon->langArray[$post_process['languageID']]['LanguageLCIDstring'];
            $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";
            elseif ($_POST['pattern_id'] == 'product_attributes')
                $ctab = "attributes";
            elseif ($_POST['pattern_id'] == 'product_custom_options')
                $ctab = "custom_options";
            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']) && $count_log['total'] == 0) {
            $error = $this->getLanguageValue('msgeximImportfailed') . " : " . "Error in imported data";
            $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("pdtexportArray", $pdtexportArray);
        $this->ObjView->assign("pdtReq", $pdt_required);
        $this->ObjView->assign("comboReq", $combo_required);
        $this->ObjView->assign("imgReq", $img_required);
        $this->ObjView->assign("customReq", $customReq);
        $this->ObjView->assign("attrReq", $attrReq);
        $this->ObjView->assign("comboexportArray", $comboexportArray);
        $this->ObjView->assign("imagexportArray", $imagexportArray);
        $this->ObjView->assign("attrexportArray", $attrexportArray);
        $this->ObjView->assign("customexportArray", $customexportArray);
        $this->ObjView->assign("selectOption", 'dimport');
        $this->ObjView->assign('resBusiness', $resBusiness);
        $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();
        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);
    }
    public function usergroupprice($params) {
        return true;
    }
    public function tierprice_quantity($params) {
        return true;
    }
    public function tierprice_price($params) {
        return true;
    }
    //END OF FUNCTION
    public function reviewDeleteAction() {
        $ObjProductReview = new ProductreviewModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $productReviewID  = $this->getRequestValue('id');
        $productID        = $this->getRequestValue('productid');
        if ($productReviewID) {
            $POST = array(
                "reviewStatus" => "Deleted",
                "productReviewBulkStatus" => array(
                    $productReviewID
                )
            );
            $ObjProductReview->changeProductReviewStatus($POST);
            $this->setMessage("language.msgCommentDelete", "success");
            if ($productID) {
                $this->setRedirect('product/show/id/' . $productID . '/');
            } else {
                $this->setRedirect('product/review/');
            }
        }
    }
    //Approve Product Request
    public function approveProductAction() {
        $productRequestID = $this->getRequestValue("id");
        $this->ObjView->assign("approveProduct", "Yes");
        $this->newAction($productRequestID);
    }
    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);
        if(strtolower($type)=='free'){
            $resListUpcomingProducts = $ObjProduct->saveFreeProductProductIDs($productID, $droppedProductIDs, $type,$_POST['freecnt']);
        } else {
            $resListUpcomingProducts = $ObjProduct->saveSellProductProductIDs($productID, $droppedProductIDs, $type);
        }
        echo 1;
    }
    public function ajaxchangereviewstatusAction() {
        $ObjProductReview                  = new ProductreviewModel();
        $POST['productReviewBulkStatus'][] = $_POST['rid'];
        $POST['reviewStatus']              = 'active';
        $resChangeStatus                   = $ObjProductReview->changeProductReviewStatus($POST);
        $this->setMessage("language.msgReviewApproved", "success");
    }
    public function ajaxGetMerchantCommisionAction() {
        $ObjBusiness            = new BusinessModel();
        $businessID             = $_POST['businessID'];
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $resMerchantComm        = $ObjBusiness->getBusinessCommision($businessID);
        if ($resMerchantComm) {
            echo $resMerchantComm;
        } else {
            echo 0;
        }
    }
    //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 deleteProductsAction() {
        $ObjCustom = new ProductModel();
        if ($this->ObjForm->isValid('product_delete', 'submit_delete')) {
            $ObjCustom->bulkDeleteProducts();
            $this->setMessage("Products Deleted Successfully", "success");
            $this->setRedirect('product/index/');
        }
        $this->ObjView->display('BulkProductDelete.tpl');
    }
    public function updateVariantTitleAction() {
        $ObjCustom = new ProductModel();
        $ObjCustom->updateVariantTitle();
        ECHO "SUCCESS";
        exit;
    }
    public function ajaxLinkBaseProductAction()
        {
            //initialize object
            $ObjImage 			= new ImageModel();
            $ObjProduct                 = new ProductModel();
            $languageIDs                = $this->ObjView->languageIDs;
            $languageIDs['Current']     = $languageIDs['Content'];      
            $productID                  = $_POST['productID'];
            $currProductID              = $_POST['pid'];
            $rand=rand(10,300);
            
            $paramArray['selectedProductID']=$productID;
            $paramArray['languageIDs']      =$languageIDs;
            $paramArray['view']             ='Yes';
            $paramArray['businessStatus']   ="Yes";
            $resSelectproduct      = $ObjProduct->getProductDetails($paramArray);
            if(!empty($resSelectproduct)) {
                $resSelectproduct      = $resSelectproduct[0];
            } else {
                $resSelectproduct      = array();
            }
            if (!empty($resSelectproduct['productImage'])){
                $fileName = "uploads/catalog/product/thumb/" . $resSelectproduct['productImage'];
                if ($ObjImage->file_exist($fileName)){
                    $this->ObjView->assign('image_directory', 'Yes');
                }
            }
            $buyboxBusIds =  $ObjProduct->getBuyboxBusinessIds($productID,$currProductID); 
            $this->ObjView->assign('buyboxBusIds', implode(':',$buyboxBusIds));
            $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->ObjView->assign('resProducts', $resProducts);
            $this->ObjView->display('BaseProduct.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 productImgAction() {
        $objProduct                 = new ProductModel();
        $ObjExim = new EximModel();
        $languageIDs                            = $this->ObjView->languageIDs;
        $businessName = 'Mokhtalef';
        $businessID = '6';    
        echo "done";exit;
        $dir    = '/home/jihazi/public_html/public/uploads/exim/product-images/'.$businessName.'/'; 
        $sql = "select * from dp_product_options where productID in (select productID from dp_products where businessID='".$businessID."' and productImage='')";
        $res = $objProduct->exeQuery($sql,'Y');
        
        //echo "Product Images";
        //exit;
        foreach($res as $re) { 
            
            $productID  = $re['productID'];
            $filename1 = $re['optionSKU'];
            $main_image = '';
            $ext = "";
            $main_image = $this->checkFile($filename1,$dir);
            
            if($main_image=='') {
                $filename1 = $re['optionSKU']."-1";
                $main_image = $this->checkFile($filename1,$dir);
                if($main_image=='') {
                    $filename1 = $re['optionSKU']."-2";
                    $main_image = $this->checkFile($filename1,$dir);
                    if($main_image=='') {
                        $filename1 = $re['optionSKU']."-3";
                        $main_image = $this->checkFile($filename1,$dir);
                        if($main_image=='') {
                            $filename1 = $re['optionSKU']."-4";
                            $main_image = $this->checkFile($filename1,$dir);
                            if($main_image=='') {
                                $filename1 = $re['optionSKU']."-5";
                                $main_image = $this->checkFile($filename1,$dir);
                            }
                        }
                    }
                }
                
            }
            echo $productID." ".$main_image."<br>";
            if($productID>0 && $main_image!='') {
                    
                    $object_id = $objProduct->getProductOptionId($productID);
                    $img1 = 'public/uploads/exim/product-images/'.$businessName.'/'.$main_image;
                    //$ObjExim->fn_exim_set_product_main_import_images('public/uploads/exim/product-images/al_falak', '', $productID, $main_image);
                    $sql = "update dp_products set import_main_image='".$img1."',productImage='' where productID='".$productID."'";
                    $objProduct->setSqlQuery($sql);
                    $sp = explode("-",$main_image);
                    $sp1 = $sp[1];
                    $la = 5;
                    if(empty($sp1)) {
                        $fi = 1;
                       
                    } else {
                        if($sp1==1) {
                            $fi = $la - $sp1;
                        }
                    }
                    
                    //additional
                    for($add=0;$add<=$la;$add++) {
                        if($add==0){
                            $sub = '';
                        } else {
                            $sub = $add;
                        }
                        $filename1 = $re['optionSKU']."-".$sub;
                        
                        $add_image = $this->checkFile($filename1,$dir);
                        if($add_image=='') {
                            $filename1 = $re['optionSKU']."_".$sub;
                            $add_image = $this->checkFile($filename1,$dir);
                        }
                        //echo $add_image."<br>";
                        if($add_image!='') {                            
                            $ObjExim->fn_exim_set_import_image('public/uploads/exim/product-images/'.$businessName, '', $object_id, $add_image, $re['optionSKU'], 'DO', $businessID);
                        }                        
                    } 
                    
                    
                } else {
                    echo "not ".$productID." ".$main_image."<br>";
                }
        }
        exit;
    }
    public function checkFile($filename,$dir) {
        $ext = '';
        $main_image = '';
        $filename1 = $dir.$filename;
         if(file_exists($filename1.".jpg") || file_exists($filename1.".png") || file_exists($filename1.".jpeg") || file_exists($filename1.".JPG") || file_exists($filename1.".PNG") || file_exists($filename1.".JPEG")) {
                
                if(file_exists($filename1.".jpg")) {
                    $ext = ".jpg";
                     
                }
                if(file_exists($filename1.".png")) {
                    $ext = ".png";
                }
                if(file_exists($filename1.".jpeg")) {
                    $ext = ".jpeg";
                }
                if(file_exists($filename1.".JPG")) {
                    $ext = ".JPG";
                }
                if(file_exists($filename1.".PNG")) {
                    $ext = ".PNG";
                }
                if(file_exists($filename1.".JPEG")) {
                    $ext = ".JPEG";
                }
                if($ext!='') {
                    $main_image = $filename.$ext;
                } 
                
            }
            return $main_image;
    }
    public function testImgAction() {
        $dir    = '/home/pan02_users/resmi/jihazi/public/uploads/exim/product-images/istyle';
        $files1 = scandir($dir);
        $files2 = scandir($dir, 1);
        $f = 0;

        $objProduct                 = new ProductModel();
        $ObjExim = new EximModel();
        $languageIDs                            = $this->ObjView->languageIDs;
        unset($files2[0]);
        unset($files2[1]);
        foreach($files2 as $fi) {
    
        $f = $f + 1;

        $data = explode(".",$fi);

        $ext = ".".$data[1];
        $sp = explode("-",$data[0]);
        $sku = $sp[0];
        $productID = 0;
        //echo $sku." ".$sku."-1".$ext;
        //exit;
        if($sku!='') {
            $productID = $objProduct->getProductIDBySKU($sku);
        }
        if($productID>0) {
            echo $productID . "- ".$fi."<br>";
            exit;
            $main_image = $sku."-1".$ext;
            //$ObjExim->fn_exim_set_product_main_import_images('public/uploads/exim/product-images/al_falak', '', $productID, $main_image);
            //$arrn = array("2","3","4","5");
            //foreach($arrn as $arn) {
                if($sp[1]>1) {
                    if(file_exists($dir."/".$sku."-".$sp[1].$ext)) {
                        $object_id = $objProduct->getProductOptionId($productID);
                        $ObjExim->fn_exim_set_import_image('public/uploads/exim/product-images/al_falak', '', $object_id, $sku."-".$sp[1].$ext, $sku, 'DO', '12');
                    }
                }
            //}
        
            if($f>4) {
               // exit;
            }
        } else {
            echo "not ".$fi."<br>";
        }
        /*$sql = "select import_main_image,productID from dp_products where productImage='' and import_main_image like '%".$fi."%'";
        $res = $objProduct->exeQuery($sql);
        if(empty($res)) {
            $f = $f + 1;
            echo "hh ".$fi;
            echo "<br>";
        } else {

        }*/


    }

    echo $f;
    exit;

    echo "<pre>";print_r($files1);
    }
    public function updateAttributeValuesAction($resImportAttr) {
        $objProduct                 = new ProductModel();
        $ObjCsv                     = new Csv();
        $import_log                 = array();
        $post_process['businessID'] = $_POST['import_options']['businessID'];
        $post_process['imgPath']    = $_POST['import_options']['images_path'];

        //$import_log                 = $ObjExim->import($_POST['pattern_id'], $post_process);
        /*if ($_FILES['file_csv_file']['tmp_name'][0] != '') {
            $importFile = $_FILES['file_csv_file']['tmp_name'][0];
        } else {
            $this->setMessage($this->getLanguageValue('msgeximFileNotUploaded'), 'message_error');
            $this->setRedirect("product/importcustom/ctab/" . $ctab . "/");
        }*/
        //$ObjCsv->auto($importFile);
        //$resImportAttr = $ObjCsv->data;
        //echo "<pre>";print_r($resImportAttr);exit;
        $arrkeys = array_keys($resImportAttr[0]);
        $c              = 0;
        $attrKeysArr    = array();
        $kn = '';
        foreach($arrkeys as $keyv=>$ar) {

            if($ar=='product_weight') {
                $kn = $keyv;
            }
            if($keyv>$kn && $kn>0) {
                $attrKeysArr[] = $ar;
            }
        }
        
        
        foreach($resImportAttr as $data) {            
             
             $productID    = $objProduct->getProductIDBySKU($data['sku']);                        
             if($productID>0) {
                 
                                   
                foreach($attrKeysArr as $fld) {      
                                $langarr = array("1","2"); 
                                $val = $data[$fld]; 
                               
                                if($fld!='' && $val!='') {
                                    $fld = str_replace("_", "-", $fld);
                                    $sqlAttr    = "Select attributeID,attrInputType from dp_attributes where attributeKey='".$fld."' and attrStatus='A'";                                                                                                                                           
                                    $rsAttr     = $objProduct->exeQuery($sqlAttr);
                                    if(!empty($rsAttr)) {
                                        $attributeID   = $rsAttr['attributeID'];
                                        $attrInputType = $rsAttr['attrInputType'];                                        
                                                                              
                                        if($attributeID>0) { 
                                           
                                                $saveAttr     = 0;
                                                if($attrInputType=='textbox') {
                                                   $attrOptionID = 0;
                                                   $saveAttr     = 1;
                                                } else {
                                                   
                                                    $sqlSearch = "SELECT  attrOptDet.attrOptionID from dp_attribute_option_details attrOptDet join dp_attribute_options attrOpt on (attrOptDet.attrOptionID=attrOpt.attrOptionID AND attrOptDet.languageID='" . $languageIDs['Current'] . "')";
                                                    $sqlSearch .=  " where attrOpt.attributeID='".$attributeID."' and attrOptDet.attrOptName='".$val."'";                                                                                                        
                                                    
                                                    $rsSearch   = $objProduct->exeQuery($sqlSearch);
                                                    $attrOptionID = (!empty($rsSearch)) ? $rsSearch['attrOptionID'] : 0;
                                                    if($attrOptionID>0) {
                                                        $saveAttr     = 1;
                                                    } else{
                                                        $saveAttr     = 0;
                                                    }
                                                }
                                                $attrValueID = 0;                                                
                                                if($saveAttr>0) {
                                                  $sqlExistsattr = "select attrValueID,productID from dp_product_attribute_values where productID='".$productID."' and attributeID='".$attributeID."'";
                                                  $rsSearchattr  = $objProduct->exeQuery($sqlExistsattr);
                                                  if(empty($rsSearchattr)) {
                                                        $sqlIns = "INSERT INTO dp_product_attribute_values 
                                                                                           (
                                                                                                   productID,
                                                                                                   attributeID,
                                                                                                   attrOptionID
                                                                                           ) 
                                                                                   VALUES 
                                                                                           (
                                                                                                   '" . $productID . "',
                                                                                                   '" . $attributeID . "',
                                                                                                   '". $attrOptionID."'
                                                                                           )
                                                                                   ";
                                                        $attrValueID  =  $objProduct->setSqlQuery($sqlIns,'ID');
                                                  } else {                                                      
                                                        $attrValueID  =  $rsSearchattr['attrValueID'];                                                        
                                                  }
                                                }
                                                 
                                                 //
                                                 if($attrValueID>0) {
                                                     foreach($langarr as $lang) {
                                                        $sqlExistsattrval = "select attrValDetID,attrValueID from dp_product_attribute_value_details where attrValueID='".$attrValueID."' and languageID='".$lang."'";
                                                        $rsSearchattrval  = $objProduct->exeQuery($sqlExistsattrval); 
                                                        if(empty($rsSearchattrval)) {
                                                            $sqlUpd        =   "INSERT INTO dp_product_attribute_value_details 
                                                                                   (
                                                                                           attrValueID,
                                                                                           languageID,
                                                                                           attrDetValue
                                                                                   ) 
                                                                                   VALUES 
                                                                                   (
                                                                                           '" . $attrValueID . "',
                                                                                           '" . $lang . "',
                                                                                           '" . $val . "'
                                                                                    )
                                                                                   ";
                                                            
                                                            $objProduct->setSqlQuery($sqlUpd);
                                                        } else {
                                                            $sqlUpd = "update dp_product_attribute_value_details set attrDetValue='" . $val . "' where attrValDetID='".$rsSearchattrval['attrValDetID']."'";
                                                            $objProduct->setSqlQuery($sqlUpd);
                                                        }
                                                        
                                                     }
                                                      
                                                     echo "succ ".$productID."<br>";   
                                                 }
                                                 else {
                                                    echo "not ".$productID."<br>"; 
                                                }
                                                
                                           
                                        }

                                    }
                                }
                        } 
                           
                //exit;
             }
        }
        echo "Done";exit;
    }
    public function updateProductNameAction($resImportAttr) {
        $objProduct                 = new ProductModel();
        
        foreach($resImportAttr as $data) {
            $productDet       = $objProduct->getProductIDBySKU($data['sku'],'Yes');
            $productID        = !empty($productDet) ? $productDet['productID']:0;
            $productOptionID  = !empty($productDet) ? $productDet['productOptionID']:0;
            if($productID>0) {
                $_POST['productTitle']                  =   $data['product_name'];
                $_POST['productDescription']            =   $data['description'];
                $_POST['productMetaTitle']              =   $data['meta_title'];
                $_POST['productShortDescription']       =   $data['short_description'];
                $_POST['productMetaDescription']        =   $data['meta_description'];
                $_POST['productMetaKeywords']           =   $data['meta_keyword'];
                
                $response = $objProduct->updateProductDetails($productID,2,$productOptionID,$_POST);
                
                if($response) {
                    echo "succ ".$productID."<br>";    
                } else {
                    echo "not ".$productID."<br>";
                }                
            }
           
        }
        echo "done";
        exit;
    }
    //Bulk Import
    public function ImportCustomAction() {
        $patternID                              = $this->getRequestValue("pattern");
        $ObjExim                                = new EximModel();
        $languageIDs                            = $this->ObjView->languageIDs;
        $ObjBusiness                            = new BusinessModel();
        $resBusiness                            = $ObjBusiness->listBusinessInOptions($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;
       
        
       
        //TAB SETTINGS
        $cstatus                                = $this->getRequestValue("cstatus");
        $ctab                                   = $this->getRequestValue("ctab");
		
        if ($cstatus == 'imported') {
            $count_log = $this->ObjSession->getSession("count_log");
            //print_r($this->ObjSession->getSession("count_log"));exit;
            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", 'Custom Options');
        } elseif ($ctab == 'attr') {
            $this->ObjView->assign("atab", 1);
            $this->ObjView->assign("pattern", "Custom Attributes");
        } 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) {
            
            $objBrand                   = new BrandModel();
            $objProduct                 = new ProductModel();
           
            $ObjCsv                     = new Csv();
            $import_log                 = array();
            $post_process['businessID'] = $_POST['import_options']['businessID'];
            $post_process['imgPath']    = $_POST['import_options']['images_path'];            
            //$import_log                 = $ObjExim->import($_POST['pattern_id'], $post_process);
            if ($_FILES['file_csv_file']['tmp_name'][0] != '') {
                $importFile = $_FILES['file_csv_file']['tmp_name'][0];
            } else {
                $this->setMessage($this->getLanguageValue('msgeximFileNotUploaded'), 'message_error');
                $this->setRedirect("product/importcustom/ctab/" . $ctab . "/");
            }                              
            //$this->updateAttributeValuesAction($resImportAttr);
            if ($_POST['pattern_id'] == 'product_attributes') {
                $ctab = "attr";                
                $ObjCsv->auto($importFile);
                $resImportAttr = $ObjCsv->data;
                foreach($resImportAttr as $data) {
                    
                    $productID  =   $objProduct->getProductIDBySKU($data['sku']);
                    
                    if($productID>0) {                        
                        $arrNewAttr = array_keys($data);                       
                        $objProduct->setSqlQuery("DELETE productAttrValDet FROM dp_product_attribute_values productAttrVal
                                                                     LEFT JOIN dp_product_attribute_value_details productAttrValDet
                                                                     ON productAttrVal.attrValueID = productAttrValDet.attrValueID						
                                                                     LEFT JOIN dp_attributes attr ON attr.attributeID = productAttrVal.attributeID	
                                                                     WHERE productAttrVal.productID = '" . $productID . "'
                                                                     AND productAttrValDet.languageID = '" . $languageIDs['Current'] . "'   AND attr.attrInputType!='file'
                        ");
                        $objProduct->setSqlQuery("DELETE FROM dp_product_attribute_values where productID = '" . $productID . "'");
                        if(!empty($arrNewAttr)) {
                            $fkey = 2;
                            $lkey = count($arrNewAttr)-1;                                  
                            for($at=$fkey;$at<=$lkey;$at++) {
                                $fld = $data[$arrNewAttr[$at]];                                
                                if($fld!='') {
                                    $sqlAttr    = "Select attributeID,attrInputType from dp_attributes where attributeKey='".$arrNewAttr[$at]."' and attrStatus='A'";                                                                                                       
                                    $rsAttr     = $objProduct->exeQuery($sqlAttr);
                                    if(!empty($rsAttr)) {
                                        $attributeID   = $rsAttr['attributeID'];
                                        $attrInputType = $rsAttr['attrInputType'];                                        
                                        $fld = str_replace(", ",",",$fld);                                        
                                        $fld = explode(",",$fld);                                        
                                        if(!empty($fld) && $attributeID>0) { 
                                            foreach($fld as $val) { 
                                                $saveAttr     = 0;
                                                if($attrInputType=='textbox') {
                                                   $attrOptionID = 0;
                                                   $saveAttr     = 1;
                                                } else {
                                                    if($arrNewAttr[$at]=='metal-purity') {
                                                        $val = str_replace('kt', 'KT', $val);
                                                    }
                                                    $sqlSearch = "SELECT  attrOptDet.attrOptionID from dp_attribute_option_details attrOptDet join dp_attribute_options attrOpt on (attrOptDet.attrOptionID=attrOpt.attrOptionID AND attrOptDet.languageID='" . $languageIDs['Current'] . "')";
                                                    $sqlSearch .=  " where attrOpt.attributeID='".$attributeID."' and attrOptDet.attrOptName='".$val."'";                                                                                                        
                                                    
                                                    $rsSearch   = $objProduct->exeQuery($sqlSearch);
                                                    $attrOptionID = (!empty($rsSearch)) ? $rsSearch['attrOptionID'] : 0;
                                                    if($attrOptionID>0) {
                                                        $saveAttr     = 1;
                                                    } else{
                                                        $saveAttr     = 0;
                                                    }
                                                }
                                                $attrValueID = 0;
                                                if($saveAttr>0) {
                                                 $sqlIns = "INSERT INTO dp_product_attribute_values 
                                                                                    (
                                                                                            productID,
                                                                                            attributeID,
                                                                                            attrOptionID
                                                                                    ) 
                                                                            VALUES 
                                                                                    (
                                                                                            '" . $productID . "',
                                                                                            '" . $attributeID . "',
                                                                                            '". $attrOptionID."'
                                                                                    )
                                                                            ";
                                                 $attrValueID  =  $objProduct->setSqlQuery($sqlIns,'ID');
                                                }
                                                 //
                                                 if($attrValueID>0) {
                                                     $sqlIns        =   "INSERT INTO dp_product_attribute_value_details 
                                                                            (
                                                                                    attrValueID,
                                                                                    languageID,
                                                                                    attrDetValue
                                                                            ) 
                                                                            VALUES 
                                                                            (
                                                                                    '" . $attrValueID . "',
                                                                                    '" . $languageIDs['Current'] . "',
                                                                                    '" . $val . "'
                                                                             )
                                                                            ";
                                                     $objProduct->setSqlQuery($sqlIns);
                                                 }
                                                
                                            }
                                        }

                                    }
                                }
                            }
                           
                        }
                                                
                   }
                }               
                $import_log['Status'] = 'Success';
             }  elseif ($_POST['pattern_id'] == 'product_images') {
                            
                $ctab = "image";                
                $ObjCsv->auto($importFile);
                $resImportImages = $ObjCsv->data;     
               
                //echo "<pre>";print_r($resImportImages);exit;
                foreach($resImportImages as $img) {
                   
                    $productID  =   $objProduct->getProductIDBySKU($img['sku']);  
					$productOptionID	=	 $objProduct->getProductOptionId($productID);                    
                    if($productID>0) {
                        
                        if($img['gallery']!='' || $img['thumbnail']!='') {
                            $objProduct->setSqlQuery("DELETE FROM dp_product_media  WHERE  productObjectType='DO' AND productObjectID='".$resGet['productOptionID']."' AND productID ='" . $productID."'");
                            $productImage = '';
                            $pr = 0;        
                            if($img['thumbnail']!='') {
                                $thumbImgsp         = explode("/",$img['thumbnail']);
                                $thumbImg           = $thumbImgsp[count($thumbImgsp)-1];                                 
                                $info               = pathinfo($thumbImg);
                                $dirs               = basename($thumbImg, '.' . $info['extension']);
                                $imgFolder          = (count($thumbImgsp)>1 && !empty($thumbImgsp[count($thumbImgsp)-2]))?strtolower($thumbImgsp[count($thumbImgsp)-2]['0']):strtolower($dirs['0']);    
                                $thumbImage         = $imgFolder."/".$thumbImg;     
                                $sqlIns             = "INSERT INTO `dp_product_media`(
										`productID`, `productObjectID`, `productObjectType`, `productMedia`, `productMediaType`, `productMediaPriority`, `productMediaStatus`, `productHoverImage`
								)
								VALUES
								(
								'" . $productID . "',
								'" . $productOptionID. "',
                                                                'DO',    
								'" . $thumbImage . "',								
								'I',
                                                                '".$pr."',
								'A',
                                                                '1'
								)";
                              
                                $res = $objProduct->setSqlQuery($sqlIns);
                            }
                            if($img['gallery']!='') {
                                $gallerySplit = explode(",",$img['gallery']);                            
                                foreach($gallerySplit as $gal) {
                                    $pr++;
                                    $productImagesp     = explode("/",$gal);
                                    $productImage       = $productImagesp[count($productImagesp)-1];
                                    $info               = pathinfo($productImage);
                                    $dirs               = basename($productImage, '.' . $info['extension']);  
                                    $imgFolder          = (count($productImagesp)>1 && !empty($productImagesp[count($productImagesp)-2]))?strtolower($productImagesp[count($productImagesp)-2]['0']):strtolower($dirs['0']);    
                                    $gallerImage        = $imgFolder."/".$productImage;            
                                    $sqlIns             = "INSERT INTO `dp_product_media`(
                                                                                    `productID`, `productObjectID`, `productObjectType`, `productMedia`, `productMediaType`, `productMediaPriority`, `productMediaStatus`, `productHoverImage`
                                                                    )
                                                                    VALUES
                                                                    (
                                                                    '" . $productID . "',
                                                                    '" . $productOptionID. "',
                                                                    'DO',    
                                                                    '" . $gallerImage . "',								
                                                                    'I',
                                                                    '".$pr."',
                                                                    'A',
                                                                    '0'
                                                                    )";

                                    $res = $objProduct->setSqlQuery($sqlIns);

                                }
                            }
                        }
                    }
                    
                }
                $import_log['Status'] = 'Success';
                
            } else {
                
                $ctab = "pdt";               
                $ObjCsv->auto($importFile);
                $resImportProducts = $ObjCsv->data;
                $ObjExim = new EximModel();
                $params = array();
                $params['languageIDs']  =   $languageIDs;
                $params['limitFrom']    =   0;
                $params['limitTo']      =   1;
                $product_sef_format                 =    $this->getSettingValue('seo_settings', 'product_sef_format');
                $product_sef_format                 =    isset($product_sef_format)  ? $product_sef_format   : false;
                //URL Rewrite Settings	
                $settingsUrlSuffix                  =    $this->getSettingValue("seo_settings", "product_url_suffix");                  
                $c = 0;
                echo "Import Custom";
                exit;
                $arrkeys = array_keys($resImportProducts[0]);
                $c              = 0;
                $attrKeysArr    = array();
                $kn = '';
                foreach($arrkeys as $keyv=>$ar) {
                    
                    if($ar=='product_type_id') {
                        $kn = $keyv;
                    }
                    if($keyv>$kn && $kn>0) {
                        $attrKeysArr[] = $ar;
                    }
                }
                
		//for category upd		
                /*$SefModel = new SefModel();
                foreach($resImportProducts as $keyc=>$_POST) {
                    //echo $_POST['category_ids'];
                    //exit;
                    $det  =   $objProduct->getProductIDBySKU($_POST['sku'],'Y');
                    
                    $productID  = $det['productID'];
                    $_POST['productUrl'] = $det['productUrl'];
                    if($productID > 0) {
                      $args     = array(
                            'productUrl' => $_POST['productUrl'],
                            'product_sef_format' => $product_sef_format
                        );
                        
                        $catIDs                                    =   $_POST['category_ids']; 
                        if($catIDs[0]==2) {
                            $catIDs = substr($catIDs,1);
                        } 
                        if($catIDs[0]==',') {
                            $catIDs = substr($catIDs,1);
                        } 
                        $_POST['pcatIDs']                          = explode(",",$catIDs);
                        $sqlCatIns = "delete from `dp_url_rewrite` where objectID='" . $productID . "' and type='product' and parentID>0";
                            $objProduct->setSqlQuery($sqlCatIns);
                             $sqlCatIns = "delete from `dp_product_to_category` where productID='" . $productID . "'";
                            $objProduct->setSqlQuery($sqlCatIns);
                         foreach ($_POST['pcatIDs'] as $keycx => $category) {                           
							if($category>0) {
                                                           
                            $sqlCatIns = "INSERT INTO `dp_product_to_category` (`productID`, `productCategoryID`) VALUES ('" . $productID . "', '" . $category . "')";
                            $objProduct->setSqlQuery($sqlCatIns);
                            $args['category'] = $category;
                            
                            $SefModel->_refreshProductRewrites($languageIDs['AllList'], $productID, $settingsUrlSuffix, $args, 'insert');
			}
                        }
                    }
                    
                }*/
                
                foreach($resImportProducts as $keyc=>$_POST) {
                    
                    
                    
                    $_POST['productTimeZone']               =   5;
                    $_POST['productMinBuyLimit']            =   1;
                    $_POST['measurementLength']             =   1;
                    $_POST['measurementWeight']             =   5;
                    $_POST['taxClassID']                    =   0;
                    $attrSet                                =   $_POST['attribute_set'];//str_replace("&", "&amp;", $_POST['attribute_set']); 
                    
                    $attributeDet                           =   $objProduct->exeQuery("select attributeSetID FROM  `dp_attribute_set` WHERE  `attributeSetName` LIKE  '%".htmlentities($attrSet)."%' LIMIT 0 , 1");
                    $_POST['attributeSetID']                =   $attributeDet['attributeSetID'];                    
                    
                    $brandName                              =   $_POST['brand'];   
                    
                    $params['brandName']                    =   $brandName;              
                    //get brandID
                    $brandDet                               =   $objBrand->listBrand($params,'All');
                    
                    $_POST['brandID']                       =   $brandDet[0]['brandID'];
                    $_POST['productDefaultCurrency']        =   13;
                    $_POST['businessID']                    =   $post_process['businessID'];
                    $_POST['productStatus']                 =   ($_POST['status']=='Enabled')?'Active':'Inactive';
                    $_POST['InventoryTrackLevel']           =   ($_POST['qty']>=0)?'Product':'No';
                    $_POST['productTitle']                  =   $_POST['product_name'];
                    $_POST['productDescription']            =   $_POST['description'];
                    $_POST['productMetaTitle']              =   $_POST['meta_title'];
                    $_POST['productShortDescription']       =   $_POST['short_description'];
                    $_POST['productMetaDescription']        =   $_POST['meta_description'];
                    $_POST['productMetaKeywords']           =   '';
                    $_POST['productUrl']                    =   $this->ObjCommon->generateKey("product", $_POST["productTitle"]);
                    $_POST['taxToBusiness']                 =   'No';
                    $_POST['setAsProductDeal']              =   'No';
                    $_POST['productAttrType']               =   !empty($_POST['product_type'])?ucfirst($_POST['product_type']):'';                   
                    
                   
                    $_POST['shippingSetting']               =   $this->getSettingValue('shipping_settings', 'shipping_origin_type');
                    if ($_POST['shippingSetting'] == 'admin') {
                        $_POST['shippingOrigin'] = '0';
                    } else {
                        $_POST['shippingOrigin'] = 'NULL';
                    }
                    
                    $_POST['dealStartTime']                 =   '';
                    $_POST['dealEndTime']                   =   '';
                    $_POST['dealDiscount']                  =   '';
                    $_POST['dealMaxBuyLimit']               =   '';                    
                    $_POST['enableMultipleOptions']         =   'No';
                    $_POST['productOptionQuantity']         =   $_POST['qty'];
                    $_POST['productReturnable']             =   'Yes';
                    $_POST['returnPeriod']                  =   '10';                   
                    $_POST['productDispatchTime']           =   '';
                    $_POST['productDiscount']               =   '';
                    $_POST['featuredStatus']                =   ($_POST['featured']<=0)?'No':'Yes';
                            
                    $_POST['skuRef']                           =   $_POST['sku'];
                    $mainPrice                                 =   $_POST['price'];
                    $salePrice                                 =   $_POST['special_price'];
                    if($mainPrice!='' && $salePrice!='') {
                        $_POST['productDiscount']              =   ($mainPrice-$salePrice)*100/$mainPrice;
                    }
                    //category
                    $catIDs                                    =   $_POST['category_ids'];                    
                    if($catIDs[0]==2) {
                        $catIDs = substr($catIDs,1);
                    } 
                    /*if($catIDs[0]==',') {
                        $catIDs = substr($catIDs,1);
                    }*/ 
                    $_POST['pcatIDs']                          = str_split($catIDs, 3);//explode(",",$catIDs);//  str_split($catIDs, 3);
                    $_POST['productCategoryID']                = ','.implode(",", $_POST['pcatIDs']);
                    
                    //options
                    $options                                   =   array();
                    $options[0]['option_id']                   =   '-1';
                    $options[0]['is_delete']                   =   0;
                    $options[0]['productOptionName']           =   $_POST['productTitle'];
                    $options[0]['optionSKU']                   =   $_POST['sku'];
                    $options[0]['optionBarCode']               =   '';
                    $options[0]['productOptionRegularPrice']   =   $_POST['price'];
                    $options[0]['productOptionProductPrice']   =   $_POST['special_price'];
                    $options[0]['productOptionQuantity']       =   $_POST['qty'];
                    $options[0]['productOptionStatus']         =   $_POST['productStatus'];
                    $options[0]['packageWeight']               =   ($_POST['product_weight']=='N/A')?'':$_POST['product_weight'];
                    $options[0]['packageLength']               =   '';
                    $options[0]['packageWidth']                =   '';
                    $options[0]['packageHeight']               =   '';
                    $options[0]['productOptionImageSort']      =   '';
                    $_POST['productOptionsGroup']              =   $options;
                                        
                    //product images
                    $productImage   = $_POST['sku'].".jpg";//$_POST['image'];
                    //$productImagesp = explode("/",$productImage);
                    //$productImage   = $productImagesp[count($productImagesp)-1];                    
                    //$productImage   = $productImage[0].".jpg";
                    //$_POST['productImage'] = '';
                    
                    $productImage    = $_POST['image'];
                    $productImagesp  = explode("/",$productImage);
                    $productImage    = $productImagesp[count($productImagesp)-1];
                    
                   /* $productSImage   = $_POST['small_image'];
                    $productSImagesp = explode("/",$productSImage);
                    $productSImage   = $productSImagesp[count($productSImagesp)-1];
                    */
                    //$productImage = '';
                    //$productImage = str_replace('t','T',$productImage);
                    //$productImage = str_replace('s','S',$productImage);
                   
                    $productID = $objProduct->saveProduct($languageIDs, $_POST, '', '', true,'import');
                    
                    if($productID>0) {
                       
                        if (isset($productImage) && $productImage != '') {    
                            /*$info                   = pathinfo($productImage);
                            $dirs                   = basename($productImage, '.' . $info['extension']);  
                            $imgFolder              = (count($productImagesp)>1 && !empty($productImagesp[count($productImagesp)-2]))?strtolower($productImagesp[count($productImagesp)-2]['0']):strtolower($dirs['0']);                            
                            $_POST['productImage']  = $imgFolder."/".$productImage;*/
                            $ObjExim->fn_exim_set_product_main_import_images($post_process['imgPath'], '', $productID, $productImage);
                        }  
                        //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['pcatIDs'] as $keycx => $category) {                           
                                                            if($category>0) {
                                $sqlCatIns = "INSERT INTO `dp_product_to_category` (`productID`, `productCategoryID`) VALUES ('" . $productID . "', '" . $category . "')";
                                $objProduct->setSqlQuery($sqlCatIns);
                                $args['category'] = $category;
                                $SefModel->_refreshProductRewrites($languageIDs['AllList'], $productID, $settingsUrlSuffix, $args, '',$product_sef_format,'insert');
                                                            }
                            }
                         }
                        
                        //add attributes
                                                  
                        $objProduct->setSqlQuery("DELETE productAttrValDet FROM dp_product_attribute_values productAttrVal
                                                                     LEFT JOIN dp_product_attribute_value_details productAttrValDet
                                                                     ON productAttrVal.attrValueID = productAttrValDet.attrValueID						
                                                                     LEFT JOIN dp_attributes attr ON attr.attributeID = productAttrVal.attributeID	
                                                                     WHERE productAttrVal.productID = '" . $productID . "'
                                                                     AND productAttrValDet.languageID = '" . $languageIDs['Current'] . "'   AND attr.attrInputType!='file'
                        ");
                        $objProduct->setSqlQuery("DELETE FROM dp_product_attribute_values where productID = '" . $productID . "'");
                        $fld = $data[$arrNewAttr[$at]];    
                        foreach($attrKeysArr as $fld) {      
                                
                                $val = $_POST[$fld]; 
                               
                                if($fld!='' && $val!='') {
                                    $fld = str_replace("_", "-", $fld);
                                    $sqlAttr    = "Select attributeID,attrInputType from dp_attributes where attributeKey='".$fld."' and attrStatus='A'";                                                                                                                                           
                                    $rsAttr     = $objProduct->exeQuery($sqlAttr);
                                    if(!empty($rsAttr)) {
                                        $attributeID   = $rsAttr['attributeID'];
                                        $attrInputType = $rsAttr['attrInputType'];                                        
                                                                              
                                        if($attributeID>0) { 
                                           
                                                $saveAttr     = 0;
                                                if($attrInputType=='textbox') {
                                                   $attrOptionID = 0;
                                                   $saveAttr     = 1;
                                                } else {
                                                   
                                                    $sqlSearch = "SELECT  attrOptDet.attrOptionID from dp_attribute_option_details attrOptDet join dp_attribute_options attrOpt on (attrOptDet.attrOptionID=attrOpt.attrOptionID AND attrOptDet.languageID='" . $languageIDs['Current'] . "')";
                                                    $sqlSearch .=  " where attrOpt.attributeID='".$attributeID."' and attrOptDet.attrOptName='".$val."'";                                                                                                        
                                                    
                                                    $rsSearch   = $objProduct->exeQuery($sqlSearch);
                                                    $attrOptionID = (!empty($rsSearch)) ? $rsSearch['attrOptionID'] : 0;
                                                    if($attrOptionID>0) {
                                                        $saveAttr     = 1;
                                                    } else{
                                                        $saveAttr     = 0;
                                                    }
                                                }
                                                $attrValueID = 0;
                                                if($saveAttr>0) {
                                                 $sqlIns = "INSERT INTO dp_product_attribute_values 
                                                                                    (
                                                                                            productID,
                                                                                            attributeID,
                                                                                            attrOptionID
                                                                                    ) 
                                                                            VALUES 
                                                                                    (
                                                                                            '" . $productID . "',
                                                                                            '" . $attributeID . "',
                                                                                            '". $attrOptionID."'
                                                                                    )
                                                                            ";
                                                 $attrValueID  =  $objProduct->setSqlQuery($sqlIns,'ID');
                                                }
                                                 //
                                                 if($attrValueID>0) {
                                                     $sqlIns        =   "INSERT INTO dp_product_attribute_value_details 
                                                                            (
                                                                                    attrValueID,
                                                                                    languageID,
                                                                                    attrDetValue
                                                                            ) 
                                                                            VALUES 
                                                                            (
                                                                                    '" . $attrValueID . "',
                                                                                    '" . $languageIDs['Current'] . "',
                                                                                    '" . $val . "'
                                                                             )
                                                                            ";
                                                     $objProduct->setSqlQuery($sqlIns);
                                                 }
                                                
                                           
                                        }

                                    }
                                }
                        }
                           
                        //end of attributes
                        
                        $objProduct->updateShippingSettings($_POST,'Y',$productID);
                        $objProduct->assignDefaultSmService($productID);
                            
                        
                        /*if(!empty($_POST['productCategoryID'][0])) {
                            $productCategoryID = explode(",",$_POST['productCategoryID'][0]);                        
                            foreach ($productCategoryID as $key => $category) {
                                $args['category'] = $category;
                                $SefModel->_refreshProductRewrites($languageIDs['AllList'], $productID, $settingsUrlSuffix, $args, 'insert');
                            }
                        }*/
                       
                    }                           					
                }                                
                $import_log['Status'] = 'Success';
            }
            
        }   
        if (isset($import_log['Status']) && $import_log['Status'] == "no_file") {
            $this->setMessage("language.msgeximFileNotUploaded", "message_error");
            $this->setRedirect("product/importcustom/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/importcustom/ctab/" . $ctab . "/");
        }  /*elseif (isset($import_log['Status']) && $count_log['total'] == 0) {
            $error = $this->getLanguageValue('msgeximImportfailed') . " : " . "Error in imported data";
            $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/importcustom/ctab/" . $ctab . "/cstatus/imported");
        }
        $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->assign('resBusiness', $resBusiness);
        $this->ObjView->display('ProductImportCustom.tpl');
    }
	/*private function getCategoryList($resProductCategories, $cat,$val1=array()) {
	     foreach ($resProductCategories as $value) {
			if($value['productCategoryParent'] == 0){
				if($value['productCategoryID'] == $cat){				
					array_push($val1,$value['productCategoryID']);
					return $val1;
				}
			}else{						
				if($value['productCategoryID'] == $cat){			
					array_push($val1,$value['productCategoryID']);
					$this->getCategoryList($value['children'],$value['productCategoryParent'],$val1);
				}
				
			}
		}						
	}*/


        
    public function ajaxBusinessLocationsAction(){
        $ObjBusiness            =       new BusinessModel();
        $languageIDs            =       $this->ObjView->languageIDs;
        $businessID             =       $_POST['businessID'];
        $sellerIncr             =       $_POST['sellerIncr'];
        $productOptionCount     =       $_POST['productOptionCount'];
        $businessLocations      =       $ObjBusiness->listBusinessLocations(0,"",'Active',$businessID,$languageIDs);
        $this->ObjView->assign("businessLocations", $businessLocations);
        $this->ObjView->assign("sellerIncr", $sellerIncr);
        $this->ObjView->assign("productOptionCount", $productOptionCount);
        $this->ObjView->display('AjaxBusinessLocations.tpl');
    }
    
    public function ajaxAddMerchantAction(){
        $ObjBusiness            =       new BusinessModel();
        $ObjProduct             =       new ProductModel();
        $ObjUsergroup           =       new UsergroupModel();
        $languageIDs            =       $this->ObjView->languageIDs;
        $resBusiness            =       $ObjBusiness->listBusinessInOptions($languageIDs);
        $resPeriod              =       $ObjProduct->getDispatchTime();
        $addEditPopup           =       $this->getRequestValue("openpopup");
        $addEditPopup           =       isset($addEditPopup) ? $addEditPopup : "";
        
        if($addEditPopup=="s"){
            $prodOptionBusID    =       $this->getRequestValue("id");
            $prodOptionBusID    =       isset($prodOptionBusID) ? $prodOptionBusID : 0;
            $productOptionCount =       $this->getRequestValue("pdOpt");
            $sellerIncrCount    =       $this->getRequestValue("slrIncr");
            $currProductID      =       $this->getRequestValue("pdid");
            $currProductOptionID=       $this->getRequestValue("pdOpid");
            
            $productInvLevel    =       $ObjProduct->getProductInvLevel($currProductID);
            $this->ObjView->assign("productInvLevel", $productInvLevel);
            
            $setAsProductDeal   =       $ObjProduct->getProductSetProductDeal($currProductID);
            $this->ObjView->assign("setAsProductDeal", $setAsProductDeal);
            
            if($prodOptionBusID>0){
                $busOptions         =       $ObjProduct->getProductBusinessOptions($prodOptionBusID);
                $busProductOptionID =       $busOptions['productOptionID'];
                $busOptBusinessID   =       $busOptions['businessID'];
                $groupPriceValues   =       $ObjProduct->getbusinessGroupPrice($busProductOptionID,$busOptBusinessID);
                $busOptions['group_price'] = $groupPriceValues;
            }
        
            $params         = array(
                'languageIDs' => $languageIDs,
                'sortby' => 'brandName',
                'orderby' => 'ASC'
            );
            $listUsergroups = $ObjUsergroup->listUsergroups($params);
            
            if(isset($_POST['submitSeller']) && $_POST['submitSeller']=="Save"){
                $businessOptGroup   =   $_POST['productOptionsGroup'][$productOptionCount]['businessOptionsGroup'][$sellerIncrCount];
                $updateMerchant     =   $ObjProduct->addBusinessOptions($currProductOptionID,$businessOptGroup,$currProductID,$prodOptionBusID);
                echo '<script type="text/javascript">window.parent.location = window.parent.location.href;parent.$.colorbox.close(); </script>';
                $this->setMessage("language.msgMerchantAssignedSuccess", 3);
                exit;
            }
            
            $this->ObjView->assign("listUsergroups", $listUsergroups);
            $this->ObjView->assign("resBusiness", $resBusiness);
            $this->ObjView->assign("busOptCount", $busOptions);
            $this->ObjView->assign("prodOptionBusID", $prodOptionBusID);
            $this->ObjView->assign("currProductOptionID", $currProductOptionID);
            $this->ObjView->assign("editMerchantVal", "Yes");
        }else{
            $productOptionCount =       $_POST['productOptionCount'];
            $sellerIncrCount    =       $_POST['sellerIncrCount'];
            $currProductID      =       $_POST['pdid'];
            $invLevel           =       $_POST['invLevel'];
            $setProductDeal     =       $_POST['setAsProductDeal'];
            
            if($invLevel!=""){
                $productInvLevel    =       $invLevel;
                $this->ObjView->assign("productInvLevel", $productInvLevel);
            }else{
                $productInvLevel    =       $ObjProduct->getProductInvLevel($currProductID);
                $this->ObjView->assign("productInvLevel", $productInvLevel);
            }
            
            if($setProductDeal!=""){
                $setAsProductDeal   =       $setProductDeal;
                $this->ObjView->assign("setAsProductDeal", $setProductDeal);
            }else{
                $setAsProductDeal   =       $ObjProduct->getProductSetProductDeal($currProductID);
                $this->ObjView->assign("setAsProductDeal", $setAsProductDeal);
            }
        }
        
        $this->ObjView->assign("resBusiness", $resBusiness);
        $this->ObjView->assign('resPeriod', $resPeriod);
        $this->ObjView->assign("sellerIncr", $sellerIncrCount);
        $this->ObjView->assign("productOptionCount", $productOptionCount);
        $this->ObjView->assign("productForm", "Product");
        if($addEditPopup=="s"){
            $this->ObjView->display('SellerEdit.tpl');
        }else{
            $this->ObjView->display('AjaxAssignSellers.tpl');
        }
        
    }
    
    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'];
        $sellerIncr             =       $_POST['sellerIncr'];
        $groupIncr              =       $_POST['groupIncr'];
        
        $this->ObjView->assign('listUsergroups', $listUsergroups);
        $this->ObjView->assign("productOptionCount", $productOptionCount);
        $this->ObjView->assign("sellerIncr", $sellerIncr);
        $this->ObjView->assign("groupIncr", $groupIncr);
        $this->ObjView->display('AjaxBusinessGroupPrice.tpl');
    }
    
    public function ajaxdeleteMerchantAction(){
        $ObjProduct             =       new ProductModel();
        $productOptionBusinessID=       $_POST['productOptionBusinessID'];
        $productOptionID        =       $_POST['productOptionID'];
        $deleteMerchant         =       $ObjProduct->deleteMerchant($productOptionBusinessID,$productOptionID);
        echo 1; exit;
    }
    
    public function ajaxAddComboMerchantAction(){
        $ObjBusiness            =       new BusinessModel();
        $ObjProduct             =       new ProductModel();
        $languageIDs            =       $this->ObjView->languageIDs;
        $productID              =       $_POST['productID'];
        $combocount             =       $_POST['combocount'];
        $comboBusIncr           =       $_POST['comboBusIncr'];
        
        $productOptionID        =       $ObjProduct->getDefaultOptionID($productID);
        $resBusinessComb        =       $ObjBusiness->listBusinessInOptions($languageIDs,0,"","","","","","","","Yes",$productOptionID);
        $this->ObjView->assign("resBusinessComb", $resBusinessComb);
        $this->ObjView->assign("combocount", $combocount);
        $this->ObjView->assign("comboBusIncr", $comboBusIncr);
        $this->ObjView->display('ProductCombinationSeller.tpl');
    }
    
    public function ajaxChangeDefBusinessAction(){
        $ObjProduct             =       new ProductModel();
        $productID              =       $_POST['productID'];
        $productOptionID        =       $_POST['prodOptID'];
        $businessID             =       $_POST['businessID'];
        $changeDefBusiness      =       $ObjProduct->changeDefaultBusiness($productID,$productOptionID,$businessID);
        if($changeDefBusiness=="1"){
            $this->setMessage("language.msgDefBusinessChanged", 3);
        }else{
            $this->setMessage("language.msgDefBusinessChangedError", 3);
        }
        echo $changeDefBusiness;
    }

    public function leaseimportAction(){
		$ObjProduct  			= 		new ProductModel();
		$ObjEmailtemplate       = 		new EmailtemplateModel();
		$languageIDs            = 		$this->ObjView->languageIDs;
		$errorStr	 			= 		'';
		$modelCodes				= 		array();
		$inert_details	 		= 		array();
		$successStr  			= 		'';			
		$trp                            =               '';
		if ($this->ObjForm->isValid('formImportdata', 'submit_import'))
        {	
			if ($_FILES['csv_file']['tmp_name'] != '')
            {
				require_once __ROOT_PATH."/vendor/phpoffice/phpexcel/Classes/PHPExcel.php";
				$tmpfname       = $_FILES['csv_file']['tmp_name'];

				$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
				$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
				$excelObj    = $excelReader->load($tmpfname);
				$worksheet   = $excelObj->getSheet(0);
				$lastRow     = $worksheet->getHighestRow();
                                $trp         = $_POST['trpOption'];
				for ($row = 1; $row <= $lastRow; $row++) {
					
					$modelCode 	= $worksheet->getCell('A'.$row)->getValue();	

					if($row == 1) {	
						// header
						 if((trim($worksheet->getCell('A'.$row)->getValue()) != 'Variant Code' && trim($worksheet->getCell('A'.$row)->getValue()) != 'Model code') 
						 ) {
							 $this->setMessage("language.errHeadersFormatWrong","message_error");
							 $this->setRedirect();
						}  
						$headerArray 		=  array(
									'1'		=>			$worksheet->getCell('B'.$row)->getValue(),
									'2'		=>			$worksheet->getCell('C'.$row)->getValue(),
									'3'		=>			$worksheet->getCell('D'.$row)->getValue(),
									'4'		=>			$worksheet->getCell('E'.$row)->getValue(),
									'5'		=>			$worksheet->getCell('F'.$row)->getValue(),
									'6'		=>			$worksheet->getCell('G'.$row)->getValue(),
									'7'		=>			$worksheet->getCell('H'.$row)->getValue(),
									'8'		=>			$worksheet->getCell('I'.$row)->getValue(),
									'9'		=>			$worksheet->getCell('J'.$row)->getValue(),
									'10'	=>			$worksheet->getCell('K'.$row)->getValue(),
									'11'	=>			$worksheet->getCell('L'.$row)->getValue(),
									'12'	=>			$worksheet->getCell('M'.$row)->getValue(),
									'13'	=>			$worksheet->getCell('N'.$row)->getValue(),
									'14'	=>			$worksheet->getCell('O'.$row)->getValue(),
									'15'	=>			$worksheet->getCell('P'.$row)->getValue(),
									'16'	=>			$worksheet->getCell('Q'.$row)->getValue(),
									'17'	=>			$worksheet->getCell('R'.$row)->getValue(),
									'18'	=>			$worksheet->getCell('S'.$row)->getValue(),
									'19'	=>			$worksheet->getCell('T'.$row)->getValue(),
									'20'	=>			$worksheet->getCell('U'.$row)->getValue(),
									'21'	=>			$worksheet->getCell('V'.$row)->getValue(),
									'22'	=>			$worksheet->getCell('W'.$row)->getValue(),
									'23'	=>			$worksheet->getCell('X'.$row)->getValue(),
									'24'	=>			$worksheet->getCell('Y'.$row)->getValue()		
						);
						
					}
					else if($row>1 && !empty($modelCode)) {	
					
							$valuesArray[] =  array(
										$worksheet->getCell('A'.$row)->getValue(),
										$worksheet->getCell('B'.$row)->getValue(),
										$worksheet->getCell('C'.$row)->getValue(),
										$worksheet->getCell('D'.$row)->getValue(),
										$worksheet->getCell('E'.$row)->getValue(),
										$worksheet->getCell('F'.$row)->getValue(),
										$worksheet->getCell('G'.$row)->getValue(),
										$worksheet->getCell('H'.$row)->getValue(),
										$worksheet->getCell('I'.$row)->getValue(),
										$worksheet->getCell('J'.$row)->getValue(),
										$worksheet->getCell('K'.$row)->getValue(),
										$worksheet->getCell('L'.$row)->getValue(),
										$worksheet->getCell('M'.$row)->getValue(),
										$worksheet->getCell('N'.$row)->getValue(),
										$worksheet->getCell('O'.$row)->getValue(),
										$worksheet->getCell('P'.$row)->getValue(),
										$worksheet->getCell('Q'.$row)->getValue(),
										$worksheet->getCell('R'.$row)->getValue(),
										$worksheet->getCell('S'.$row)->getValue(),
										$worksheet->getCell('T'.$row)->getValue(),
										$worksheet->getCell('U'.$row)->getValue(),
										$worksheet->getCell('V'.$row)->getValue(),
										$worksheet->getCell('W'.$row)->getValue(),
										$worksheet->getCell('X'.$row)->getValue(),
										$worksheet->getCell('Y'.$row)->getValue()		
							);	
					}		
							
				}

				//echo '<pre>';//print_r($headerArray);print_r($valuesArray);
				$inert_details = array();
				foreach($valuesArray as $key1 => $element) {
					$value_modelCode = $element[0];
					foreach($element as $key => $value) {
						if($key>0 && $value!='') {
						$headerValue 	= $headerArray[$key];
                                                $headerValue 	= explode('_',$headerValue);
						//$headerValue 	= explode('|',$headerValue);
						//$duration 		= explode(':',trim($headerValue[0]));
						//$duration 		= trim($duration[1]);
						//$mileage 		= explode(':',trim($headerValue[1]));
						//$mileage 		= trim($mileage[1]);
						//$trp 			= explode(':',trim($headerValue[2]));
						//$trp 			= trim($trp[1]);
                                                $mileage 		= trim($headerValue[0]);
                                                $duration 		= trim($headerValue[1]);
						$inert_details[$value_modelCode.'-'.$mileage]['modelCode'] = $value_modelCode.'-'.$_POST['year'];
						$inert_details[$value_modelCode.'-'.$mileage]['mileage'] = $mileage;
						if($trp == 'N' && $duration == '12')
							$inert_details[$value_modelCode.'-'.$mileage]['withoutTrp12'] = $value;
						if($trp == 'N' && $duration == '24')
							$inert_details[$value_modelCode.'-'.$mileage]['withoutTrp24'] = $value;
						if($trp == 'N' && $duration == '36')
							$inert_details[$value_modelCode.'-'.$mileage]['withoutTrp36'] = $value;
						if($trp == 'Y' && $duration == '12')
							$inert_details[$value_modelCode.'-'.$mileage]['Trp12'] = $value;
						if($trp == 'Y' && $duration == '24')
							$inert_details[$value_modelCode.'-'.$mileage]['Trp24'] = $value;
						if($trp == 'Y' && $duration == '36')
							$inert_details[$value_modelCode.'-'.$mileage]['Trp36'] = $value;
						
							
						$modelCodes[$value_modelCode]= $value_modelCode.'-'.$_POST['year']; 
						}
					}
				}
				//echo '<pre>';print_r($inert_details);print_r($modelCodes);//exit;
				if(!empty($inert_details)) {
					$ObjProduct->InsertProductLeasePrice($inert_details,$trp);
				}
				if(!empty($modelCodes)) {
					$inDBmodelCodes = $ObjProduct->getProductIdFromVariantCodes($modelCodes);
					$notInDBModelCodes=array();
					$notInDBModelCodes=array_diff($modelCodes,$inDBmodelCodes);
					if(!empty($notInDBModelCodes)) {
						$notInDBModelCodes=array_map(function ($str) { return str_replace('-'.$_POST['year'], "",$str); }, $notInDBModelCodes);
						//error log
						$errorStr = '<div class="message_error">'.$this->getLanguageValue('lblVehicleNotExist').'!<br> '.$this->getLanguageValue('lblForModelCodes').' -  ';
						$errorStr .= implode(', ',$notInDBModelCodes);
						$errorStr .= '</div>';
						
						$emailbody  = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'common-notification-email');
						$from                   = array(
							$emailbody['emailFromEmail'],
							$emailbody['emailFromName']
						);
						$siteName               = $this->getSettingValue('site_settings', 'site_name');
						$siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
						$notifyEmail            = $this->getSettingValue('site_settings', 'global_notification_email');
						$companyLogo            = $this->getSettingValue('company_information', 'company_logo');
						$subject                = $emailbody['emailSubject'];
						$subject                = str_replace('{$subject}', 'Lease Price Import', $subject);
						$bodytag                = $this->getLanguageValue('lblHi').",<br />
													".$this->getLanguageValue('lblRegardingLeasePriceImport1')." ".date('d-m-Y H:i:s')."<br />
													".$this->getLanguageValue('lblRegardingImport2')." - ".implode(', ',$notInDBModelCodes)." <br />
													<br />
													 "; 
						$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);
						$body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
						$mail_settings                  = $this->getSettingValue('mail_settings');
						 $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
						$ObjMail                        = new Mail($mail_settings);
						$ObjMail->IsHTML();
						$ObjMail->sendMail($from, $notifyEmail, $subject, $body);
						if ($ObjMail->Send()) {
						}
					}				
				}
				$successStr = $this->getLanguageValue('lblLeasePriceImportSuccess');	
			}
			else
			{
				$this->setMessage($this->getLanguageValue('errFile'), 'error');
				$this->setRedirect();
			}
				
		}
		$earliest_year 	= 2018; 
		$latest_year 	= date('Y', strtotime('+1 year')); 
		$yearArray		=  range( $earliest_year ,  $latest_year);
		foreach ($yearArray as $key => $value)	{
			$years[$key][0] = $value;
			$years[$key][1] = $value;
		}//print_r($years);
		$this->ObjView->assign("yearArray", $years);	
                $this->ObjView->assign("trpOption", $trp);
		$this->ObjView->assign("errorStr", $errorStr);
		$this->ObjView->assign("successStr", $successStr);
		$this->ObjView->display('LeaseImport.tpl');
	}
	public function financeimportAction(){
		$ObjProduct  			= 		new ProductModel();
		$ObjEmailtemplate       = 		new EmailtemplateModel();
		$languageIDs            = 		$this->ObjView->languageIDs;
		$errorStr	 			= 		'';
		$variantCodes			= 		array();
		$insert_details	 		= 		array();
		$successStr  			= 		'';			
		
		if ($this->ObjForm->isValid('formImportdata', 'submit_import'))
        {	
			if ($_FILES['csv_file']['tmp_name'] != '')
            {
				require_once __ROOT_PATH."/vendor/phpoffice/phpexcel/Classes/PHPExcel.php";
				$tmpfname       = $_FILES['csv_file']['tmp_name'];

				$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
				$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
				$excelObj    = $excelReader->load($tmpfname);
				$worksheet   = $excelObj->getSheet(0);
				$lastRow     = $worksheet->getHighestRow();

				for ($row = 1; $row <= $lastRow; $row++) {
					
					$params 		= array();
					$variantCode 	= $worksheet->getCell('A'.$row)->getValue();	
					$financeRate   	= $worksheet->getCell('B'.$row)->getValue();
					$shortDesc   	= $worksheet->getCell('C'.$row)->getValue();
					$detDesc   		= $worksheet->getCell('D'.$row)->getValue();
					if($row == 1) {	
						// header
						if((trim($variantCode) != 'Variant code') || (trim($financeRate) != 'Finance Rate %') || (trim($shortDesc) != 'Short Description of Promotion (Max 25 Charecters)') || (trim($detDesc) != 'Detailed Description of Promotion')) {
							 $this->setMessage("language.errHeadersFormatWrong","message_error");
							 $this->setRedirect();
						} 
					}
					else if($row>1 && !empty($variantCode)) {	
							$params['variantCode'] 				= $variantCode.'-'.$_POST['year'];
							$params['financeRate'] 				= $financeRate*100;
							$params['shortDescription'] 		= $shortDesc;
							$params['detailedDescription'] 		= nl2br($detDesc);
							//echo '<pre>';print_r($params);exit;	
							$insert_details[] = $params;
							$variantCodes[$variantCode]= $variantCode.'-'.$_POST['year']; 
						}
				}
				//echo '<pre>';print_r($insert_details);//print_r($variantCodes);//exit;
				if(!empty($insert_details)) {
					$ObjProduct->InsertProductFinanceRate($insert_details);
				}

				if(!empty($variantCodes)) {
					$inDBVariantCodes = $ObjProduct->getProductIdFromVariantCodes($variantCodes);
					//$inDBVariantCodes = array();
					$notInDBVariantCodes=array();
					$notInDBVariantCodes=array_diff($variantCodes,$inDBVariantCodes);
					if(!empty($notInDBVariantCodes)) {
						$notInDBVariantCodes=array_map(function ($str) { return str_replace('-'.$_POST['year'], "",$str); }, $notInDBVariantCodes);
						//error log
						$errorStr = '<div class="message_error">'.$this->getLanguageValue('lblVehicleNotExist').'!<br> '.$this->getLanguageValue('lblForModelCodes').' -  ';
						$errorStr .= implode(', ',$notInDBVariantCodes);
						$errorStr .= '</div>';
						
						$emailbody  = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'common-notification-email');
						$from                   = array(
							$emailbody['emailFromEmail'],
							$emailbody['emailFromName']
						);
						$siteName               = $this->getSettingValue('site_settings', 'site_name');
						$siteUrl                = $this->getSettingValue('site_settings', 'global_http_url');
						$notifyEmail            = $this->getSettingValue('site_settings', 'global_notification_email');
						$companyLogo            = $this->getSettingValue('company_information', 'company_logo');
						$subject                = $emailbody['emailSubject'];
						$subject                = str_replace('{$subject}', 'Finance Rate Import', $subject);
						$bodytag                = $this->getLanguageValue('lblHi').",<br />
													".$this->getLanguageValue('lblRegardingFinanceRateImport1')." ".date('d-m-Y H:i:s')."<br />
													".$this->getLanguageValue('lblRegardingImport2')." - ".implode(', ',$notInDBVariantCodes)." <br />
													<br />
													 "; 
						$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);
						$body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
						$mail_settings                  = $this->getSettingValue('mail_settings');
						 $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
						$ObjMail                        = new Mail($mail_settings);
						$ObjMail->IsHTML();
						$ObjMail->sendMail($from, $notifyEmail, $subject, $body);
						if ($ObjMail->Send()) {
						}
					}				
				}
				$successStr = $this->getLanguageValue('lblFinanceRateImportSuccess');
			}
			else
			{
				$this->setMessage($this->getLanguageValue('errFile'), 'error');
				$this->setRedirect();
			}
				
		}
		$earliest_year 	= 2018; 
		$latest_year 	= date('Y', strtotime('+1 year')); 
		$yearArray		=  range( $earliest_year ,  $latest_year);
		foreach ($yearArray as $key => $value)	{
			$years[$key][0] = $value;
			$years[$key][1] = $value;
		}//print_r($years);
		$this->ObjView->assign("yearArray", $years);
		$this->ObjView->assign("errorStr", $errorStr);
		$this->ObjView->assign("successStr", $successStr);
		$this->ObjView->display('FinanceImport.tpl');
	}
	public function serviceimportAction(){
		$ObjProduct  			= 		new ProductModel();
		$ObjEmailtemplate       = 		new EmailtemplateModel();
		$languageIDs            = 		$this->ObjView->languageIDs;
		$errorStr	 			= 		'';
		$variantCodes			= 		array();
		$insert_details	 		= 		array();
		$successStr  			= 		'';			
		
		if ($this->ObjForm->isValid('formImportdata', 'submit_import'))
        {	
			if ($_FILES['csv_file']['tmp_name'] != '')
            {
				require_once __ROOT_PATH."/vendor/phpoffice/phpexcel/Classes/PHPExcel.php";
				$tmpfname       = $_FILES['csv_file']['tmp_name'];

				$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
				$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
				$excelObj    = $excelReader->load($tmpfname);
				$worksheet   = $excelObj->getSheet(0);
				$lastRow     = $worksheet->getHighestRow();

				for ($row = 1; $row <= $lastRow; $row++) {
					
					$params 			= array();
					$variantCode 		= $worksheet->getCell('A'.$row)->getValue();	
					$longDescription   	= $worksheet->getCell('B'.$row)->getValue();
					if($row == 1) {	
						// header
						if((trim($variantCode) != 'Variant') || (trim($longDescription) != 'Long Description')) {
							 $this->setMessage("language.errHeadersFormatWrong","message_error");
							 $this->setRedirect();
						} 
					}
					else if($row>1 && !empty($variantCode)) {	
							$params['variantCode'] 				= $variantCode;
							$params['longDescription'] 			= nl2br($longDescription);
							$insert_details[] = $params;
							$variantCodes[$variantCode]= $variantCode; 
						}
				}
				//echo '<pre>';print_r($insert_details);print_r($variantCodes);exit;
				if(!empty($insert_details)) {
					$ObjProduct->InsertProductServiceDetails($insert_details);
				}
				
				$successStr = $this->getLanguageValue('lblServicePackageImportSuccess');
			}
			else
			{
				$this->setMessage($this->getLanguageValue('errFile'), 'error');
				$this->setRedirect();
			}
				
		}
		$this->ObjView->assign("successStr", $successStr);
		$this->ObjView->display('ServicePackageImport.tpl');
	}
	//DOWNLOAD SAMPLE TEMPLATE
    public function ajaxSampleDownloadAction() {
		$type   = $this->getRequestValue("type");
		if($type =='leaseImport')
			$file = 'Sample_Leasing_File.xlsx';
		else if($type == 'financeRate')
			$file = 'Sample_Finance_Rate.xlsx';
		else if($type == 'servicePackage')
			$file = 'Sample_Service_Package.xlsx';
		ob_end_clean();
		header('Content-type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="'.$file.'"');
		readfile(__CORE_PUBLIC_PATH . "/uploads/sample/".$file);
		exit;
	}
	public function listleasesAction(){
		$ObjProduct  	= 		new ProductModel();
		$link           = 		'product/listleases/';
		 if (isset($_POST['search'])) {
            if ($_POST['variantCode'] != "") {
                $link .= "variantCode/" . $this->encodeUrlString($_POST['variantCode']) . "/";
            }
			if ($_POST['year'] != "") {
                $link .= "year/" . $this->encodeUrlString($_POST['year']) . "/";
            }
            $this->setRedirect($link);
        } else {
            if ($this->getRequestValue('variantCode')) {
                $variantCode = $this->decodeUrlString($this->getRequestValue('variantCode'));
            }
			if ($this->getRequestValue('year')) {
                $year = $this->decodeUrlString($this->getRequestValue('year'));
            }
        }
		list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'variantCode' => isset($variantCode) ? $variantCode : '',
            'year' => isset($year) ? $year : ''
        );
		$listLeasePrices = $ObjProduct->listLeasePrices($params);
		foreach ($listLeasePrices as $key => $value) {
			$variantArray = explode('-',$value['variantCode']);
			$listLeasePrices[$key]['variantCode'] = $variantArray[0];
		}
		$resPagesCount = $this->setPagesCount($key = 'page');
		$earliest_year 	= 2018; 
		$latest_year 	= date('Y', strtotime('+1 year')); 
		$yearArray		=  range( $earliest_year ,  $latest_year);
		foreach ($yearArray as $key => $value)	{
			$years[$key][0] = $value;
			$years[$key][1] = $value;
		}//print_r($years);
		$this->ObjView->assign("yearArray", $years);
		$this->ObjView->assign("listLeasePrices", $listLeasePrices);
		$this->ObjView->assign("variantCode", isset($variantCode) ? $variantCode : '');
		$this->ObjView->assign("year", isset($year) ? $year : '');
		$this->ObjView->display('ListLeasePrices.tpl');	
	 }
	public function listfinanceRateAction(){
		$ObjProduct  	= 		new ProductModel();
		$link           = 		'product/listfinanceRate/';
		 if (isset($_POST['search'])) {
            if ($_POST['variantCode'] != "") {
                $link .= "variantCode/" . $this->encodeUrlString($_POST['variantCode']) . "/";
            }
			if ($_POST['year'] != "") {
                $link .= "year/" . $this->encodeUrlString($_POST['year']) . "/";
            }
            $this->setRedirect($link);
        } else {
            if ($this->getRequestValue('variantCode')) {
                $variantCode = $this->decodeUrlString($this->getRequestValue('variantCode'));
            }
			if ($this->getRequestValue('year')) {
                $year = $this->decodeUrlString($this->getRequestValue('year'));
            }
        }
		list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'variantCode' => isset($variantCode) ? $variantCode : '',
            'year' => isset($year) ? $year : ''
        );
		$listfinanceRates = $ObjProduct->listfinanceRates($params);
		foreach ($listfinanceRates as $key => $value) {
			$variantArray = explode('-',$value['variantCode']);
			$listfinanceRates[$key]['variantCode'] = $variantArray[0];
		}
		$resPagesCount = $this->setPagesCount($key = 'page');
		$earliest_year 	= 2018; 
		$latest_year 	= date('Y', strtotime('+1 year')); 
		$yearArray		=  range( $earliest_year ,  $latest_year);
		foreach ($yearArray as $key => $value)	{
			$years[$key][0] = $value;
			$years[$key][1] = $value;
		}//print_r($years);
		$this->ObjView->assign("yearArray", $years);
		$this->ObjView->assign("listfinanceRates", $listfinanceRates);
		$this->ObjView->assign("variantCode", isset($variantCode) ? $variantCode : '');
		$this->ObjView->assign("year", isset($year) ? $year : '');
		$this->ObjView->display('ListFinanceRates.tpl');	
	 }
	 public function listservicePackageAction(){
		$ObjProduct  	= 		new ProductModel();
		$link           = 		'product/listservicePackage/';
		 if (isset($_POST['search'])) {
            if ($_POST['variantCode'] != "") {
                $link .= "variantCode/" . $this->encodeUrlString($_POST['variantCode']) . "/";
            }
            $this->setRedirect($link);
        } else {
            if ($this->getRequestValue('variantCode')) {
                $variantCode = $this->decodeUrlString($this->getRequestValue('variantCode'));
            }
        }
		list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'variantCode' => isset($variantCode) ? $variantCode : ''
        );
		$listServicePackages = $ObjProduct->listServicePackages($params);
		$resPagesCount = $this->setPagesCount($key = 'page');

		$this->ObjView->assign("listServicePackages", $listServicePackages);
		$this->ObjView->assign("variantCode", isset($variantCode) ? $variantCode : '');
		$this->ObjView->display('ListServicePackages.tpl');	
	 }
	//LIST PRODUCT WITH SEARCH
    public function reviewProductsAction() { 
        $ObjProduct             = new ProductModel();
        $ObjProductList         = new ProductListModel();
        $ObjProductCategory     = new ProductCategoryModel();
        $ObjCustomOption        = new CustomOptionModel();
        $ObjAttr                = new AttributeModel();
        $ObjBrand               = new BrandModel();
        $link                   = '';
        $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');
        
        //load inline
        $resCategories = $ObjProductCategory->listProductCategoryItems($languageIDs, 0);
        $resAttrSet    = $ObjAttr->listAttributeSet();
        if (is_array($resCategories))
            array_shift($resCategories);
        $searchProductID           = $this->getRequestValue("key");
        $searchProductName         = $this->decodeUrlString($this->getRequestValue("name"));
        $searchProductBusinessType = $this->getRequestValue("btype");
        $searchAttrSet             = $this->decodeUrlString($this->getRequestValue("attrSet"));
        $searchProductCategory     = $this->getRequestValue("category");
        $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");
        $brandIDs                  = $this->getRequestValue("brandIDs");
        $businessIDs               = $this->getRequestValue("businessIDs");
        $businessID                = $this->getRequestValue("businessID");
        $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->decodeUrlString($this->getRequestValue("searchQuantityBelow"));
        $businessKey               = $this->decodeUrlString($this->getRequestValue("businessKey"));
        $brandKey                  = $this->decodeUrlString($this->getRequestValue("brandKey"));
        $searchInventory           = $this->getRequestValue("inventory");
        $searchType                = $this->getRequestValue("sType");
        $cloneProductIDs           = $this->getRequestValue("pids");
        $searchDeal		   = $this->getRequestValue("searchDeal");
        $searchBuybox		   = $this->getRequestValue("searchBuybox");
        if ($cloneProductIDs != '')
            $cloneProductIDs = explode("_", $cloneProductIDs);
        if ($searchProductID > 0) {
            $link .= "key/" . $searchProductID . "/";
        }
        if ($searchProductName != '') {
            $link .= "name/" . $this->encodeUrlString($searchProductName) . "/";
        }
        if ($brandKey != '') {
            $link .= "brandKey/" . $this->encodeUrlString($brandKey) . "/";
        }
        if ($businessKey != '') {
            $link .= "businessKey/" . $this->encodeUrlString($businessKey) . "/";
        }
        if ($businessID != '') {
            $link .= "businessID/" . $this->encodeUrlString($businessID) . "/";
        }
        if ($searchAttrSet > 0) {
            $link .= "attrSet/" . $searchAttrSet . "/";
        }
        if ($brandIDs != '') {
            $link .= "brandIDs/" . $brandIDs . "/";
        }
        if ($businessIDs != '') {
            $link .= "businessIDs/" . $businessIDs . "/";
        }
        if ($searchProductBusinessType > 0) {
            $link .= "btype/" . $searchProductBusinessType . "/";
        }
        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 ($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 . "/";
        }
		if ($searchDeal != '') {
            $link .= "searchDeal/" . $searchDeal . "/";
        }
        if ($searchBuybox != '') {
            $link .= "searchBuybox/" . $searchBuybox . "/";
        }
        $link .= "list";
        //Load inline       
        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";
        }
        
		//status
        if (isset($_POST['changeStatus'])) {
            $checkProductIDsCount = count($_REQUEST['checkProductIDs']);
            for ($i = 0; $i < $checkProductIDsCount; $i++) {
                $productID = $_REQUEST['checkProductIDs'][$i];
				$changestatus = $ObjProduct->changeProductStatus($productID);
				if ($changestatus && $_POST['changeStatus'] == "Deleted") {
					$ObjUrl = new UrlrewriteModel();
					$ObjUrl->deleteUrlRewrites('', 'product', $productID);
				}
            }
            if (isset($changestatus) && $_POST['changeStatus'] == "Deleted") {
                $this->setMessage("language.msgproductDelete", 3);
            } else {
				if (isset($changestatus))
					$this->setMessage("language.msgProductUpdateStatus", 3);

            }
            $this->setRedirect("product/reviewProducts/" . $link);
        } else 	if (isset($_POST['submitProductSearch'])) {
            $link = '';
            $searchProductID   = isset($_POST['searchProductID']) ? $_POST['searchProductID'] : '';
            $searchOption      = $_POST['searchOption'];
            $searchProductName = strtolower(trim($_POST['searchProductName']));
            $pos               = strpos($searchProductName, "/");
            $searchAttrSet     = trim($_POST['searchAttrSet']);
            $brandKey          = trim($_POST['brandKey']);
            $businessKey       = trim($_POST['businessKey']);
            $brandIDs          = (isset($_POST['brandIDs'])) ? implode(":", $_POST['brandIDs']) : '';
            $businessIDs       = (isset($_POST['businessIDs'])) ? implode(":", $_POST['businessIDs']) : '';
            if ($pos != false) {
                $searchProductName = substr($searchProductName, 0, strrpos($searchProductName, "/"));
            }
            $searchProductName         = $this->encodeUrlString($searchProductName);
            $searchProductType         = '1';
            $searchProductBusinessType = isset($_POST['searchProductBusinessType']) ? $_POST['searchProductBusinessType'] : '';
            $searchProductCategories   = isset($_POST['searchProductCategory']) ? $_POST['searchProductCategory'] : '';
            if (isset($searchProductCategories) && $searchProductCategories != '')
                $searchProductCategory = implode(":", $searchProductCategories);
            else
                $searchProductCategory = '';
            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);
            }
			$searchDeal    = isset($_POST['searchDeal']) ? $_POST['searchDeal'] : ''; 
            $searchBuybox  = isset($_POST['searchBuybox']) ? $_POST['searchBuybox'] : ''; 
            $sortByOption  = isset($_POST['sortByOption']) ? $_POST['sortByOption'] : '';
            $sortByOrder   = isset($_POST['sortByOrder']) ? $_POST['sortByOrder'] : '';
            $productStatus = isset($_POST['productStatus']) ? $_POST['productStatus'] : '';
            $productStatus = ($productStatus == 'Select Status') ? "" : $productStatus; 
            if ($searchProductID > 0) {
                $link .= "key/" . $searchProductID . "/";
            }
            if ($searchProductName != '') {
                $link .= "name/" . $searchProductName . "/";
            }
            if ($searchProductBusinessType > 0) {
                $link .= "btype/" . $searchProductBusinessType . "/";
            }
            if ($brandIDs != '') {
                $link .= "brandIDs/" . $brandIDs . "/";
            }
            if ($businessIDs != '') {
                $link .= "businessIDs/" . $businessIDs . "/";
            }
			if ($searchDeal != '') {
                $link .= "searchDeal/" . $searchDeal . "/";
            }
            if ($searchBuybox != '') {
                $link .= "searchBuybox/" . $searchBuybox . "/";
            }
            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 ($_POST['searchPriceFrom']) {
                $link .= "pricefrom/" . $this->encodeUrlString($_POST['searchPriceFrom']) . "/";
            }
            if ($_POST['brandKey']) {
                $link .= "brandKey/" . $this->encodeUrlString($_POST['brandKey']) . "/";
            }
            if ($_POST['businessKey']) {
                $link .= "businessKey/" . $this->encodeUrlString($_POST['businessKey']) . "/";
            }
            if ($_POST['businessID']) {
                $link .= "businessID/" . $this->encodeUrlString($_POST['businessID']) . "/";
            }
            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'])) {
                $link .= "gkeyword/" . $_POST['searchGlobalKeyword'] . "/";
            }
            if ($searchOption) {
                $link .= "sType/" . $searchOption . "/";
            }
            if ($_POST['searchQuantityBelow'] != '') {
                $link .= "searchQuantityBelow/" . $this->encodeUrlString($_POST['searchQuantityBelow']) . "/";
            }
            if ($searchAttrSet > 0) {
                $link .= "attrSet/" . $searchAttrSet . "/";
            }
            $this->setRedirect("product/reviewProducts/" . $link);
        }
        /******************************************************************************/
        $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";
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        
        
        
        $params        = array(
            'requestedBy' => 'admin',
            'languageIDs' => $languageIDs,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'sortBy' => $sortByOption,
            'orderBy' => $sortByOrder,
            'searchProductKeyword' => $searchProductName,
            'searchProductFromDate' => $this->convertDateForSQL($searchProductFromDate, $settingsDateFormat),
            'searchProductToDate' => $this->convertDateForSQL($searchProductToDate, $settingsDateFormat),
            'searchProductStatus' => $productStatus,
            'searchProductCategories' => $searchProductCategories,
            'searchPriceFrom' => $searchPriceFrom,
            'searchPriceUpto' => $searchPriceUpto,
            'searchDiscountFrom' => $searchDiscountFrom,
            'searchDiscountTo' => $searchDiscountTo,
            'searchGlobalKeyword' => $searchGlobalKeyword,
            'searchQuantityBelow' => $searchQuantityBelow,
            'businessKey' => $businessKey,
            'brandKey' => $brandKey,
            'searchInventory' => $searchInventory,
            'searchCloneIds' => $cloneProductIDs,
            'brandIDs' => ($brandIDs != '') ? explode(":", $brandIDs) : array(),
            'businessIDs' => ($businessIDs != '') ? explode(":", $businessIDs) : array(),
            'businessID' => $businessID,
            'searchAttrSet' => $searchAttrSet,
            'searchDeal' => $searchDeal,
            'searchBuybox' => $searchBuybox,
            'status' => 'Review',
            'searchFrom' => 'admin' 
        );
        
        $resProducts   = $ObjProductList->listProducts($params);
      
        $resPagesCount = $this->setPagesCount($key = 'page');
        if (count($resProducts) > 0) {
            foreach ($resProducts as $key => $products) {
                if ($products['productStatus'] == 'Buybox') {
                    $resPdtID      =$ObjProduct->getProductIDs($products['productID']);
                    $resProducts[$key]['price']=$resPdtID['price'];
               }
                if ($products['InventoryTrackLevel'] == 'No') {
                    $outOfStock = 'No';
                } else {
                    $products['productQuantityNotifyAt'] = isset($products['productQuantityNotifyAt']) ? $products['productQuantityNotifyAt'] : '';
                    $outOfStock                          = $ObjProductList->checkProductOutOfStock($products['productID'], $products['productQuantityNotifyAt'], $products['InventoryTrackLevel']);
                }
                $resProducts[$key]['outOfStock'] = $outOfStock;
                $resProducts[$key]['options']    = $ObjProduct->listProductOptions($languageIDs, $products['productID'], Null, Null, 'list', "", "", "basic","Yes");
                $params                          = array(
                    'productID' => $products['productID'],
                    'view' => 'No',
                    'status' => 'A',
                    'languageIDs' => $languageIDs,
                    'purpose' => "basic"
                );
                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']);
                            if (count($comboArray) > 0) {
                                foreach ($comboArray as $combostr) {
                                    if ($Combination)
                                        $Combination .= ",";
                                    $Combination .= $combostr['customOptionName'] . ":" . $combostr['variantName'];
                                }
                            }
                            $resProducts[$key]['combination'][$count]['ProductCombo'] = $Combination;
                            $getBusinessComb        =   $ObjCustomOption->getProductBusinessCombination($languageIDs,$comboID);
                            $resProducts[$key]['combination'][$count]['businessCombinations'] = $getBusinessComb;
                            $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 : '';
                }
            }
            
            
        }
        //echo "<pre>";print_r($resProducts);exit;
        $siteUrl        = $this->getSettingValue('site_settings', 'global_http_url');
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listBrands     = array();
        $listBusinesses = array();
        $listBrand      = $ObjBrand->listBrand($params,'All');
        foreach ($listBrand as $brand) {
            $listBrands[] = $brand['brandName'];
        }
       // echo"<pre>";print_r($resProducts);exit;
        $this->ObjView->assign('listBrands', $listBrands);
        $this->ObjView->assign('brandIDs', implode("~*", explode(":", $brandIDs)));
        $this->ObjView->assign('businessIDs', implode("~*", explode(":", $businessIDs)));
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('businessKey', $businessKey);
        $this->ObjView->assign('brandKey', $brandKey);
        $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('searchStatus', $searchStatus);
        $this->ObjView->assign('productStatus', $productStatus);
        $this->ObjView->assign('searchProductID', $searchProductID);
        $this->ObjView->assign('searchProductName', $searchProductName);
        $this->ObjView->assign('searchAttrSet', $searchAttrSet);
        if (isset($searchProductType))
            $this->ObjView->assign('searchProductType', $searchProductType);
        $this->ObjView->assign('searchQuantityBelow', $searchQuantityBelow);
        if ($searchProductToDate == $searchProductFromDate) {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate);
        } else {
            $this->ObjView->assign('searchProductDate', $searchProductFromDate . " - " . $searchProductToDate);
        }
        $this->ObjView->assign('searchProductBusinessType', $searchProductBusinessType);
        $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("resAttrSet", $resAttrSet);
        $this->ObjView->assign('searchProductCategorySel', $searchProductCategory);
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->assign("fromDate", $searchProductFromDate);
        $this->ObjView->assign("toDate", $searchProductToDate);
		$this->ObjView->assign("searchDeal", $searchDeal);
        $this->ObjView->assign("searchBuybox", $searchBuybox);
        if ($searchType) {
            $this->ObjView->assign('searchOption', $searchType);
        } else {
            $this->ObjView->assign('searchOption', 'basic');
        }
        //Privilege
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('product/edit/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('product/delete/'));
        $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('product/show/'));
        $this->ObjView->assign("newPrivilege", $this->ObjCommon->hasPrivilege('product/new/'));
        $this->ObjView->assign('clonePrivilege', $this->ObjCommon->hasPrivilege('product/clone/'));
        //Privilege
        $rand = rand(10, 300);
        $this->ObjView->assign('sortByOrder', $sortByOrder);
        $this->ObjView->assign('selectOption', 'List');
        $this->ObjView->assign('rand', $rand);
        $this->ObjView->display('ProductUnderReviewList.tpl');
    }
    //END OF FUNCTION  
	public function downloadProductInfoAction()    {
       
        $ObjCart                    = new CartModel();
        $ObjBrand               =       new BrandModel();         
		$languageIDs        		= $this->ObjView->languageIDs;
        $languageIDs['Current'] 	= $languageIDs['Content'];
        
        //search
        if (isset($_POST['submitSearch'])) {
            $productKey      = $this->encodeUrlString(trim($_POST['productKey']));
            
            $link            = "/product/downloadProductInfo/";
            
            $link .= (($productKey != "") ? "productid/" . $productKey . "/" : "");
			if ($_POST['brandID']>0) {
						$link .= "frID/" . $_POST['brandID'] . "/";
			}
            $this->setRedirect($link);
        }
        //search parameters 
		$brandID = '';
		if ($this->getRequestValue('frID')) {
			$brandID = $this->getRequestValue('frID');
		}		
        $productKey          = $this->decodeUrlString($this->getRequestValue('productid'));
        
        $orderParam = array(
            'languageIDs' => $languageIDs,
            'limitFrom' => 0,
            'limitTo' => '',            
            'productKey' => $productKey,                                        
            'export' => 'Export'       
        );
        
		if (isset($_POST['export'])) {
                $resOrdersCsv         = $ObjCart->listDownloadProductInfo($orderParam);
                $ObjCsv               = new Csv();
                $csvOutputHeader      = array(
                    $this->getLanguageValue("lblCustomerName"),
                    $this->getLanguageValue("lblEmail"),
                    $this->getLanguageValue("lblPhone"),
                    $this->getLanguageValue("lblProductName"),
                    $this->getLanguageValue("lblCreatedDate"));
                $csvOutputFileName    = "donwload__product_info_list_" . date('d_m_Y_h_i_s_A');
                $count                = $resOrdersCsv->num_rows;
                if ($count > 0) {
                    for ($i = 0; $i < $count; $i++) {
                        $orders                                  = $resOrdersCsv->fetch_array(MYSQLI_ASSOC);
						$arrExtraData  							 = unserialize($orders['extra']);
                        $resOrdersCsvOut[$i]['name']      		 = $this->encryptDecrypt("decrypt",$arrExtraData['informationDownload']['userFirstName']).' '.$this->encryptDecrypt("decrypt",$arrExtraData['informationDownload']['userLastName']);
                                     
                        $resOrdersCsvOut[$i]['userEmail']     	 = $this->encryptDecrypt("decrypt",$arrExtraData['informationDownload']['userEmail']); 
						$resOrdersCsvOut[$i]['userPhone']     	 = $this->encryptDecrypt("decrypt",$arrExtraData['informationDownload']['userPhone']);
                        $resOrdersCsvOut[$i]['productName']  	 = $orders['productOptionName']; 
                        $resOrdersCsvOut[$i]['createdDate']  	 = $orders['createdDate'];
                        unset($orders);
                    }
                }
                $csvOutputData = $ObjCsv->output($csvOutputFileName . '.csv', $resOrdersCsvOut, $csvOutputHeader);
                exit;
        }
           
        $this->ObjView->assign("productKey", $productKey);

        // pagination settings		
        if (!isset($_POST['export'])) {
            list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
            $orderParam['limitFrom']          = $limitFrom;
            $orderParam['limitTo']            = $limitTo;
            $orderParam['export']             = '';
            $orderParam['brandID']            = $brandID;
            
            $resRequests                        = $ObjCart->listDownloadProductInfo($orderParam);
        }
		foreach($resRequests as $key=> $array) {
			$arrExtraData  = unserialize($array['extra']);
			$resRequests[$key]['userFirstName'] = $arrExtraData['informationDownload']['userFirstName'];
			$resRequests[$key]['userLastName'] 	= $arrExtraData['informationDownload']['userLastName'];
			$resRequests[$key]['userEmail'] 	= $arrExtraData['informationDownload']['userEmail'];
			$resRequests[$key]['userPhone'] 	= $arrExtraData['informationDownload']['userPhone'];
			
		}
		//print_r($arrExtraData);print_r($resRequests);
        $resPagesCount = $this->setPagesCount($key = 'page');
		$this->ObjView->assign("brandID", isset($brandID) ? $brandID : '');
		$brandParams         = array(
			'languageIDs' => $languageIDs
		);       
		$listBrand      = $ObjBrand->listBrand($brandParams);  
		$this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign("resRequests", $resRequests);       
		$this->ObjView->display('DownloadProductInfoList.tpl');
     }	
	 public function missingProductsAction() { 
        $ObjProduct             = new ProductModel();
        $ObjProductList         = new ProductListModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
       
        $missingDashtype        = $this->getRequestValue("type");

        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        
        $params        = array(
            'requestedBy' => 'admin',
            'languageIDs' => $languageIDs,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'status' => array('Active', 'Inactive', 'Review'),
            'searchFrom' => 'admin', 
            'missingDashtype' => $missingDashtype
        );
        
        $resProducts   = $ObjProductList->listProducts($params);
        $resPagesCount = $this->setPagesCount($key = 'page');
       // echo"<pre>";print_r($resProducts);exit;
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->display('ProductDashboardMissingList.tpl');
    }
}
