<?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: PromotionsController.php, mvs v1.0 2013/09/12 11:35:11
//
class PromotionsController extends Controller {
    //Catalog Rule Listing
    public function indexAction() {
        $ObjPromotions          = new PromotionsModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $settingsDateFormat     = $date_format = $this->getSettingValue('site_settings', 'date_format');
        $link                   = 'promotions/index/';
        if (isset($_POST['submitSearch'])) {
            if ($_POST['ruleName'] != '') {
                $link .= 'sname/' . $this->encodeUrlString($_POST['ruleName']) . '/';
            }
            if ($_POST['dateRangeSearch'] != '') {
                $searchDates = explode(' - ', $_POST['dateRangeSearch']);
                $fromDate    = $searchDates[0];
                $toDate      = '';
                if (isset($searchDates[1])) {
                    $toDate = $searchDates[1];
                }
                $link .= 'sfromdate/' . $this->urlDate(trim($fromDate), 'set', $settingsDateFormat) . '/';
                if ($toDate != '') {
                    $link .= 'stodate/' . $this->urlDate(trim($toDate), 'set', $settingsDateFormat) . '/';
                }
            }
            if ($_POST['status'] != '') {
                $link .= 'sstatus/' . $this->encodeUrlString($_POST['status']) . '/';
            }
            $this->setRedirect($link);
        }
        // bulk status change			
        if (isset($_POST['changeStatus']) && $_POST['changeStatus'] != '') {
            $statusUpdate = $ObjPromotions->updateCatalogPromotionStatus();
            if ($_POST['changeStatus'] == "D") {
                $this->setMessage("language.msgPromotionDeleted", 3);
            } else {
                $this->setMessage("language.msgPromotionStatus", 3);
            }
            $this->setRedirect($this->ObjCommon->selfURL(), "No");
            exit;
        }
        $searchRuleName = $this->decodeUrlString($this->getRequestValue("sname"));
        $searchFromDate = $this->urlDate($this->getRequestValue("sfromdate"), 'get', $settingsDateFormat);
        $searchToDate   = $this->urlDate($this->getRequestValue("stodate"), 'get', $settingsDateFormat);
        $searchStatus   = $this->getRequestValue("sstatus");
        $searchDod      = $this->getRequestValue("dod");
        $sortBy         = $this->getRequestValue("sortby");
        $orderBy        = $this->getRequestValue("orderby");
        if ($searchRuleName != '') {
            $link .= "sname/" . $this->encodeUrlString($searchRuleName) . "/";
        }
        if ($searchFromDate) {
            $link .= "sfromdate/" . $this->urlDate($searchFromDate, 'set', $settingsDateFormat) . "/";
        }
        if ($searchToDate) {
            $link .= "stodate/" . $this->urlDate($searchToDate, 'set', $settingsDateFormat) . "/";
        }
        if ($searchStatus) {
            $link .= "sstatus/" . $searchStatus . "/";
        }
        if ($searchDod) {
            $link .= "dod/" . $searchDod . "/";
        }
        if ($sortBy != '' && $orderBy != '') {
            if (($sortBy == "rulename") && ($orderBy == "asc")) {
                $sortByRuleName = "desc";
            } elseif (($sortBy == "rulename") && ($orderBy == "desc")) {
                $sortByRuleName = "asc";
            }
            if (($sortBy == "fromdate") && ($orderBy == "asc")) {
                $sortByFromDate = "desc";
            } elseif (($sortBy == "fromdate") && ($orderBy == "desc")) {
                $sortByFromDate = "asc";
            }
            if (($sortBy == "todate") && ($orderBy == "asc")) {
                $sortByToDate = "desc";
            } elseif (($sortBy == "todate") && ($orderBy == "desc")) {
                $sortByToDate = "asc";
            }
            if (($sortBy == "priority") && ($orderBy == "asc")) {
                $sortByPriority = "desc";
            } elseif (($sortBy == "priority") && ($orderBy == "desc")) {
                $sortByPriority = "asc";
            }
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $searchStatus    = strtoupper($searchStatus);
        $params          = array(
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'ruleName' => $searchRuleName,
            'fromDate' => $this->convertDateForSQL($searchFromDate, $settingsDateFormat),
            'toDate' => $this->convertDateForSQL($searchToDate, $settingsDateFormat),
            'status' => $searchStatus,
            'productOfTheDay' => $searchDod,
            'sortBy' => $sortBy,
            'orderBy' => $orderBy
        );
        $resCatalogRules = $ObjPromotions->listCatalogRules($languageIDs, $params);
        $resPagesCount   = $this->setPagesCount($key = 'page');
        $this->ObjView->assign("resCatalogRules", $resCatalogRules);
        //Privilege
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('promotions/editcatalogrule/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('promotions/destroycatalogrule/'));
        $this->ObjView->assign("applyRulePrivilege", $this->ObjCommon->hasPrivilege('promotions/applyrules/'));
        //Privilege
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('ruleName', $searchRuleName);
        if ($searchFromDate && $searchToDate == '') {
            $this->ObjView->assign('dateRangeSearch', $searchFromDate);
        } else if ($searchFromDate && $searchToDate) {
            $this->ObjView->assign('dateRangeSearch', $searchFromDate . ' - ' . $searchToDate);
        } else {
            $this->ObjView->assign('dateRangeSearch', '');
        }
        $this->ObjView->assign('status', $searchStatus);
        $this->ObjView->assign('productOfTheDay', strtoupper($searchDod));
        $this->ObjView->assign('sortByRuleName', isset($sortByRuleName) ? $sortByRuleName : '');
        $this->ObjView->assign('sortByFromDate', isset($sortByFromDate) ? $sortByFromDate : '');
        $this->ObjView->assign('sortByToDate', isset($sortByToDate) ? $sortByToDate : '');
        $this->ObjView->assign('sortByPriority', isset($sortByPriority) ? $sortByPriority : '');
        $this->ObjView->display('CatalogPromotionList.tpl');
    }
    // Add Catalog Promotion
    public function addCatalogPromotionsAction() {
        $ObjPromotions          = new PromotionsModel();
        $ObjUsergroup           = new UsergroupModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($this->ObjForm->isValid('catalogPromotions', 'submitCatalogPromotions')) {
            $catalogRuleID          = $ObjPromotions->saveCatalogPromotions($languageIDs);
            $_POST['catalogRuleID'] = isset($_POST['catalogRuleID']) ? $_POST['catalogRuleID'] : '';
            if ($catalogRuleID && $_POST['catalogRuleID'] == "") {
                $this->setMessage("language.msgCatalogPromotionAdd", 3);
                $this->setRedirect('promotions/index/');
                exit;
            } elseif ($catalogRuleID && $_POST['catalogRuleID'] > 0) {
                $this->setMessage("language.msgCatalogPromotionUpdate", 3);
                $this->setRedirect();
                exit;
            }
        } elseif (isset($_POST['promotion_data']['conditions']['conditions'])) {
            $params                          = array(
                'languageIDs' => $languageIDs,
                'type' => "promoCatalog",
                'languageXml' => $this->ObjView->_languageXML,
                'conditionArray' => (isset($_POST['promotion_data']['conditions']['conditions'])) ? $_POST['promotion_data']['conditions']['conditions'] : array()
            );
            $rewriteConditions               = $ObjPromotions->rewriteConditions($params);
            $resDataConditions['conditions'] = $rewriteConditions['conditionOrigArray'];
            $this->ObjView->assign("resDataConditions", $resDataConditions);
            if (!empty($rewriteConditions['attrData'])) {
                $this->ObjView->assign("attrData", json_encode($rewriteConditions['attrData']));
            }
            
            $this->ObjView->assign("resPromo", $_POST);
            $this->ObjView->assign('postCallback', '1');
        }
       
        $this->ObjView->assign("schemaData", $ObjPromotions->getCatalogSchema($this->ObjView->_languageXML));
        $params = array(
            'languageIDs' => $languageIDs
        );
        $this->ObjView->assign("userGroup", $ObjUsergroup->listUsergroups($params));
        $this->ObjView->assign("today", date("Y-m-d"));
        $this->ObjView->display('CatalogPromotionsAdd.tpl');
    }
    //Load Attributes
    public function ajaxLoadAttributesAction() {
        echo json_encode($this->listAttributesForOption());
    }
    //Generate Attribute Array
    public function listAttributesForOption() {
        $ObjPromotions  = new PromotionsModel();
        $languageIDs    = $this->ObjView->languageIDs;
        $resAttributes  = $ObjPromotions->listAttributes($languageIDs);
        //echo "<pre>";print_r($resAttributes);exit;
        $i              = 0;
        $attrCheckArray = array();
        foreach ($resAttributes as $attributes) {
            if ($attributes['attrOptionID'] > 0)
                $attrOptionArray[$attributes['attributeID']][$attributes['attrOptionID']] = $attributes['attrOptName'];
            if (in_array($attributes['attributeID'], $attrCheckArray))
                continue;
            $attrCheckArray[]                    = $attributes['attributeID'];
            $attributeArray[$i]['attributeID']   = $attributes['attributeID'];
            $attributeArray[$i]['attrName']      = $attributes['attrName'] . "[ " . $attributes['attributeKey'] . " ]";
            $attributeArray[$i]['attrInputType'] = $attributes['attrInputType'];
            $i++;
        }
        $attrData['attributeArray']  = $attributeArray;
        $attrData['attrOptionArray'] = $attrOptionArray;
        return $attrData;
    }
    //Load Products
    public function ajaxLoadProductsAction() {
        $ObjPromotions      = new PromotionsModel();
        $ObjProductCategory = new ProductCategoryModel();
        $ObjBusiness        = new BusinessModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $additionalLink     = '';
        $combination        = $this->decodeUrlString($this->getRequestValue("combinations"));
        if ($combination != "yes") {
            $enableCombination = '';
        } else {
            $enableCombination = "Yes";
            $additionalLink .= 'combinations/yes/';
        }
        $quantityEnable = $this->decodeUrlString($this->getRequestValue("quantity"));
        if ($quantityEnable != "yes") {
            $enableQuantity = 'No';
        } else {
            $enableQuantity = "Yes";
            $additionalLink .= 'quantity/yes/';
        }
        $callbackFunction = $this->decodeUrlString($this->getRequestValue("callback"));
        if ($callbackFunction != "") {
            $additionalLink .= 'callback/' . $callbackFunction . '/';
        }
        $objectid = $this->decodeUrlString($this->getRequestValue("objectid"));
        if ($objectid != "") {
            $additionalLink .= 'objectid/' . $objectid . '/';
        }
        $alloptions = $this->decodeUrlString($this->getRequestValue("alloptions"));
        if ($alloptions != "" && $alloptions == "yes") {
            $additionalLink .= 'alloptions/' . $alloptions . '/';
            $alloptions = "Yes";
        }
        if (isset($_POST['submitProductSearch'])) {
            $searchProductName     = $this->encodeUrlString(strtolower(trim($_POST['searchProductName'])));
            $searchProductCategory = $this->encodeUrlString(strtolower(trim($_POST['searchProductCategory'])));
            $searchBusiness        = $this->encodeUrlString(strtolower(trim($_POST['searchBusiness'])));
            $searchMargin          = $this->encodeUrlString(strtolower(trim($_POST['searchMargin'])));
            $searchMarginType      = $this->encodeUrlString(strtolower(trim($_POST['searchMarginType'])));
            $link                  = '';
            if ($searchProductName != '') {
                $link .= "name/" . $searchProductName . "/";
            }
            if ($searchProductCategory != '') {
                $link .= "category/" . $searchProductCategory . "/";
            }
            if ($searchBusiness != '') {
                $link .= "business/" . $searchBusiness . "/";
            }
            if ($searchMargin != '') {
                $link .= "margin/" . $searchMargin . "/mtype/" . $searchMarginType . "/";
            }
            $this->setRedirect("promotions/ajaxLoadProducts/" . $additionalLink . $link);
        } else {
            $searchProductName     = $this->decodeUrlString($this->getRequestValue("name"));
            $searchProductCategory = $this->decodeUrlString($this->getRequestValue("category"));
            $searchBusiness        = $this->decodeUrlString($this->getRequestValue("business"));
            $searchMargin          = $this->decodeUrlString($this->getRequestValue("margin"));
            $searchMarginType      = $this->decodeUrlString($this->getRequestValue("mtype"));
        }
        $resCategories = $ObjProductCategory->listProductCategoryItems($languageIDs, 0, '', '', 'user');
        if (is_array($resCategories)) {
            array_shift($resCategories);
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'languageIDs' => $languageIDs,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'categoryID' => $searchProductCategory,
            'businessID' => $searchBusiness,
            'searchProductKeyword' => $searchProductName,
            'combination' => $enableCombination,
            'alloptions' => $alloptions,
            'searchMargin' => $searchMargin,
            'searchMarginType' => $searchMarginType
        );
        $resProducts   = $ObjPromotions->listProducts($params);
        $resPagesCount = $this->setPagesCount($key = 'page');
        if ($alloptions == "Yes") {
            $i           = 0;
            $productData = array();
            foreach ($resProducts as $productArray) {
                $productID                        = $productArray['productID'];
                $productData[$i]['productID']     = $productID;
                $productData[$i]['productTitle']  = $productArray['productTitle'];
                $params                           = array(
                    'languageIDs' => $languageIDs,
                    'productID' => $productID
                );
                $productData[$i]['customOptions'] = $ObjPromotions->getCustomOptionDetails($params);
                if ($productArray['multiOptionsAvailable'] == "Yes") {
                    $params                         = array(
                        'languageIDs' => $languageIDs,
                        'productID' => $productID
                    );
                    $productData[$i]['options']     = $ObjPromotions->getProductOptionDetails($params);
                    $productData[$i]['optionsType'] = 'variants';
                } else {
                    $params                         = array(
                        'languageIDs' => $languageIDs,
                        'productID' => $productID,
                        'optiontype' => 'combinations'
                    );
                    $productData[$i]['options']     = $ObjPromotions->listProductCombinations($params);
                    $productData[$i]['optionsType'] = 'combinations';
                }
                $i++;
            }
            $resProducts = $productData;
        }
        //print_r($resProducts);exit;		
        $this->ObjView->assign("resBusiness", $ObjBusiness->listBusinessInOptions($languageIDs));
        $this->ObjView->assign('callbackFunction', $callbackFunction);
        $this->ObjView->assign('objectid', $objectid);
        $this->ObjView->assign('alloptions', $alloptions);
        $this->ObjView->assign('additionalLink', $additionalLink);
        $this->ObjView->assign('enableQuantity', $enableQuantity);
        $this->ObjView->assign('searchProductName', $searchProductName);
        $this->ObjView->assign('searchProductCategory', $searchProductCategory);
        $this->ObjView->assign('searchBusiness', $searchBusiness);
        $this->ObjView->assign('searchMargin', $searchMargin);
        $this->ObjView->assign('searchMarginType', $searchMarginType);
        $this->ObjView->assign("resCategories", $resCategories);
        $this->ObjView->assign("resProducts", $resProducts);
        $this->ObjView->display('AjaxProductList.tpl');
    }
    //Load Categories
    public function ajaxLoadBrandsAction() {
        $ObjBrand    = new BrandModel();
        $languageIDs = $this->ObjView->languageIDs;
        $link        = "";
        if (isset($_POST['submitBrandSearch'])) {
            $brandKey  = $this->encodeUrlString(strtolower(trim($_POST['brandKey'])));
            $brandName = $this->encodeUrlString(strtolower(trim($_POST['brandName'])));
            if ($brandKey != '') {
                $link .= "brandKey/" . $brandKey . "/";
            }
            if ($brandName != '') {
                $link .= "brandName/" . $brandName . "/";
            }
            $this->setRedirect("promotions/ajaxLoadBrands/" . $link);
        } else {
            $brandKey  = $this->decodeUrlString($this->getRequestValue("brandKey"));
            $brandName = $this->decodeUrlString($this->getRequestValue("brandName"));
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'languageIDs' => $languageIDs,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'brandKey' => $brandKey,
            'brandName' => $brandName
        );
        $listBrands    = $ObjBrand->listBrand($params);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign("listBrands", $listBrands);
        $this->ObjView->display('AjaxBrandList.tpl');
    }
    //Load Categories
    public function ajaxLoadCategoriesAction() {
        $ObjProductCategory = new ProductCategoryModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $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);
        $this->ObjView->display('AjaxCategoryList.tpl');
    }
    //Edit catalog Rule
    public function editCatalogRuleAction() {
        $catalogRuleID          = $this->getRequestValue('id');
        $ObjPromotions          = new PromotionsModel();
        $ObjImage               = new ImageModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $params                 = array(
            'languageIDs' => $languageIDs,
            'catalogRuleID' => $catalogRuleID
        );
        $resPromo               = $ObjPromotions->getCatalogPromotionDetails($params);
        
        if (!empty($resPromo)) {            
            if (empty($_POST['submitCatalogPromotions'])) {
                $this->ObjView->assign("resPromo", $resPromo);
                $resDataConditions               = unserialize($resPromo['conditions']);
                //print_r($resDataConditions['conditions']);
                $params                          = array(
                    'languageIDs' => $languageIDs,
                    'type' => "promoCatalog",
                    'languageXml' => $this->ObjView->_languageXML,
                    'conditionArray' => $resDataConditions['conditions']
                );
                $rewriteConditions               = $ObjPromotions->rewriteConditions($params);
                //print_r($rewriteConditions['conditionOrigArray']);exit;
                $resDataConditions['conditions'] = $rewriteConditions['conditionOrigArray'];
                $this->ObjView->assign("resDataConditions", $resDataConditions);
                $this->ObjView->assign("resDataBonus", unserialize($resPromo['bonus']));
                $this->ObjView->assign("catalogRuleID", $catalogRuleID);
                if (!empty($rewriteConditions['attrData']))
                    $this->ObjView->assign("attrData", json_encode($rewriteConditions['attrData']));
            } else {
                $_POST['catalogRuleID'] = $catalogRuleID;
                /*unlink old image*/
                if (!empty($_POST["promoImage_temp"])) {
                    $imagePath = __UPLOADS_FOLDER . 'promotions/catalog/' . trim($resPromo['promoImage']);
                    $ObjImage->unlinkImage($imagePath);
                }
                /*unlink old image*/
            }
            $this->addCatalogPromotionsAction();
        } else {
            $this->setRedirect('promotions/index/');
            exit;
        }
    }
    //Change Catalog Promotion Status
    public function ajaxChangeCatalogPromoStatusAction() {
        $ObjPromotions         = new PromotionsModel();
        $_POST['id']           = $_POST['promoID'];
        $_POST['changeStatus'] = $_POST['promoStatus'];
        $statusUpdate          = $ObjPromotions->updateCatalogPromotionStatus();
        //$this->ObjCommon->calculateOfferPrice();
        $this->setMessage("language.msgPromotionStatus", 3);
    }
    //Delete Catalog Promotion
    public function ajaxDestroyCatalogPromoAction() {
        $ObjPromotions = new PromotionsModel();
        $catalogRuleID = $this->getRequestValue('id');
        if ($catalogRuleID > 0) {
            $_POST['id']           = $catalogRuleID;
            $_POST['changeStatus'] = 'D';
            if ($ObjPromotions->updateCatalogPromotionStatus()) {
                //$this->ObjCommon->calculateOfferPrice();
                $this->setMessage("language.msgPromotionDeleted", 3);
            }
        }
        $this->setRedirect('promotions/index/');
        exit;
    }
    //Get Product Combination List
    public function ajaxGetProductCombinationListAction() {
        $ObjPromotions = new PromotionsModel();
        $languageIDs   = $this->ObjView->languageIDs;
        $params        = array(
            'languageIDs' => $languageIDs,
            'productID' => $_POST['id']
        );
        echo json_encode($ObjPromotions->listProductCombinations($params));
    }
    // Add Cart Promotion
    public function addCartPromotionsAction($id='') {
        
        $ObjPromotions          = new PromotionsModel();
        $ObjUsergroup           = new UsergroupModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($this->ObjForm->isValid('cartPromotionsAddForm', 'submitCartPromotions')) {
            $_POST['promoWebAppEnabled'] = (count($_POST['promoWebAppEnabled'])>1 || empty($_POST['promoWebAppEnabled'])) ? 'Both':$_POST['promoWebAppEnabled'][0]; 
            $ruleID          = $ObjPromotions->saveCartPromotions($languageIDs);
            $_POST['ruleID'] = isset($_POST['ruleID']) ? $_POST['ruleID'] : '';
            if ($ruleID && $_POST['ruleID'] == "") {
                $this->setMessage("language.msgCartPromotionAdd", 3);
                $this->setRedirect('promotions/cartpromotions/');
                exit;
            } elseif ($ruleID && $_POST['ruleID'] > 0) {
                $this->setMessage("language.msgCartPromotionUpdate", 3);
                $this->setRedirect('promotions/editcartrule/id/' . $ruleID . '/');
                exit;
            }
        } elseif (isset($_POST['submitCartPromotions'])) {
            $params                          = array(
                'languageIDs' => $languageIDs,
                'type' => "promoCart",
                'languageXml' => $this->ObjView->_languageXML,
                'conditionArray' => (isset($_POST['promotion_data']['conditions']['conditions'])) ? $_POST['promotion_data']['conditions']['conditions'] : array()
            );
            $rewriteConditions               = $ObjPromotions->rewriteConditions($params);
            $resDataConditions['conditions'] = $rewriteConditions['conditionOrigArray'];
            //Bonus		
            $params                          = array(
                'languageIDs' => $languageIDs,
                'languageXml' => $this->ObjView->_languageXML,
                'bonusArray' => (isset($_POST['promotion_data']['bonuses']['bonuses'])) ? $_POST['promotion_data']['bonuses']['bonuses'] : array()
            );
            $rewriteBonus                    = $ObjPromotions->rewriteBonus($params);
            $resDataBonus                    = '';
            if ($rewriteBonus['bonusOrigArray']) {
                $resDataBonus['bonus'] = $rewriteBonus['bonusOrigArray'];
            }
           
            $this->ObjView->assign("resDataConditions", $resDataConditions);
            $this->ObjView->assign("resDataBonus", $resDataBonus);
            if (!empty($rewriteConditions['attrData'])) {
                $this->ObjView->assign("attrData", json_encode($rewriteConditions['attrData']));
            }
            if ($rewriteConditions['userGrpData']) {
                $this->ObjView->assign("userGrpData", $rewriteConditions['userGrpData']);
            } elseif (isset($rewriteBonus['userGrpData'])) {
                $this->ObjView->assign("userGrpData", $rewriteBonus['userGrpData']);
            }
            $this->ObjView->assign("countryData", $rewriteConditions['countryData']);
            $this->ObjView->assign("paymentMethodData", $rewriteConditions['paymentMethodData']);
            //Free Products			
            $params           = array(
                'languageIDs' => $languageIDs,
                'freeProducts' => (isset($_POST['promoBonusFreeProducts'])) ? $_POST['promoBonusFreeProducts'] : '',
                'language' => $this->ObjView->_languageXML
            );
            $freeProductsData = $ObjPromotions->getFreeProductsData($params);
            //print_r($freeProductsData);
            //print_r($_POST['promoBonusFreeProducts']);exit;
            $this->ObjView->assign("freeProductsData", $freeProductsData);
            if (isset($_POST['promoBonusFreeProductsQuantity'])) {
                unset($_POST['promoBonusFreeProductsQuantity']);
            }
            if (isset($_POST['freeProdfreeShipping'])) {
                unset($_POST['freeProdfreeShipping']);
            }
            $this->ObjView->assign("resPromo", $_POST);
            $this->ObjView->assign('postCallback', '1');
        }
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign("listUsergroups", $listUsergroups);
        if($id=='') {
           
            $promoWebAppEnabled = array("Web","App");
            $this->ObjView->assign("promoWebAppEnabled",$promoWebAppEnabled);
        }
        $this->ObjView->assign("schemaData", $ObjPromotions->getCartSchema($this->ObjView->_languageXML));
        $this->ObjView->assign("today", date("Y-m-d"));
        $tabSection = $this->getRequestValue('section');
        if ($tabSection == '' || !in_array($tabSection, array(
            'general',
            'conditions',
            'bonus',
            'coupons'
        )))
        $tabSection = 'general';        
        $this->ObjView->assign("tabSection", $tabSection);
        $this->ObjView->display('CartPromotionsAdd.tpl');
    }
    //Load users
    public function ajaxLoadUsersAction() {
        $ObjPromotions      = new PromotionsModel();
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        //search variables			
        if (isset($_POST['submitSearch'])) {
            $userFullName      = $this->encodeUrlString(trim($_POST['userFullName']));
            $userRegistredDate = $_POST['userRegistredDate'];
            if ($userRegistredDate) {
                $searchDates = explode(' - ', $userRegistredDate);
                $fromDate    = $searchDates[0];
                if (isset($searchDates[1])) {
                    $toDate = $searchDates[1];
                }
            }
            $userEmailID = $this->encodeUrlString(trim($_POST['userEmailID']));
            $usertype    = trim($_POST['userType']);
            $link        = '';
            $link .= (($userFullName != "") ? "name/" . $userFullName . "/" : "");
            $link .= (($fromDate != "") ? "from/" . $this->urlDate($fromDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($toDate != "") ? "to/" . $this->urlDate($toDate, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($userEmailID != "") ? "email/" . $userEmailID . "/" : "");
            $link .= (($usertype != "") ? "usertype/" . $usertype . "/" : "");
            $this->setRedirect("promotions/ajaxLoadUsers/" . $link);
        }
        $userFullName   = $this->decodeUrlString($this->getRequestValue('name'));
        $userEmailID    = $this->decodeUrlString($this->getRequestValue('email'));
        $usertype       = $this->getRequestValue('usertype');
        $fromDate       = $this->urlDate($this->getRequestValue('from'), 'get', $settingsDateFormat);
        $toDate         = $this->urlDate($this->getRequestValue('to'), 'get', $settingsDateFormat);
        /*assigning from and to values for search*/
        $assignFromDate = $fromDate;
        $assignToDate   = $toDate;
        if (!$toDate && $fromDate) {
            $toDate = $fromDate;
        }
        /*assigning from and to values for search*/
        $this->ObjView->assign("userFullName", $userFullName);
        if ($assignFromDate && $assignToDate == '') {
            $this->ObjView->assign('userRegistredDate', $assignFromDate);
        } else if ($assignFromDate && $assignToDate) {
            $this->ObjView->assign('userRegistredDate', $assignFromDate . ' - ' . $assignToDate);
        } else {
            $this->ObjView->assign('userRegistredDate', '');
        }
        $this->ObjView->assign("userEmailID", $userEmailID);
        $this->ObjView->assign("userType", $usertype);
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'fromDate' => $this->convertDateForSQL($fromDate, $settingsDateFormat),
            'toDate' => $this->convertDateForSQL($toDate, $settingsDateFormat),
            'userEmailID' => $userEmailID,
            'userType' => $usertype,
            'userFullName' => $userFullName
        );
        $resUsers      = $ObjPromotions->listUsers($params);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign("resUsers", $resUsers);
        $this->ObjView->display('AjaxUserList.tpl');
    }
    //Load User Group
    public function ajaxLoadUserGroupAction() {
        $ObjPromotions = new PromotionsModel();
        $fields        = array(
            'ID' => 'userGroupID',
            'value' => 'userGroupName'
        );
        echo json_encode(array(
            'resData' => $ObjPromotions->listCustomerGroups(),
            'fields' => $fields
        ));
    }
    //Load User Group
    public function ajaxLoadCountryAction() {
        $ObjPromotions          = new PromotionsModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $params                 = array(
            'languageIDs' => $languageIDs
        );
        $fields                 = array(
            'ID' => 'countryID',
            'value' => 'countryName'
        );
        echo json_encode(array(
            'resData' => $ObjPromotions->listCountries($params),
            'fields' => $fields
        ));
    }
    //Load User Group
    public function ajaxLoadStateAction() {
        $ObjPromotions          = new PromotionsModel();
        $ObjLanguage            = new LanguageModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $ObjLanguage->getContentlanguageID();
        $params                 = array(
            'languageIDs' => $languageIDs
        );
        $fields                 = array(
            'ID' => 'stateID',
            'value' => 'stateName'
        );
        echo json_encode(array(
            'resData' => $ObjPromotions->listStates($params),
            'fields' => $fields
        ));
    }
    //Load Payment Methods
    public function ajaxLoadPaymentMethodAction() {
        $ObjPromotions = new PromotionsModel();
        $fields        = array(
            'ID' => 'paySetGroupKey',
            'value' => 'paySetGroupLabel'
        );
        echo json_encode(array(
            'resData' => $ObjPromotions->listPaymentMethods(),
            'fields' => $fields
        ));
    }
    //Load Payment Methods
    public function ajaxLoadMerchantsAction() {
        $ObjPromotions = new PromotionsModel();
        $languageIDs   = $this->ObjView->languageIDs;
        $params        = array(
            'languageIDs' => $languageIDs
        );
        $fields        = array(
            'ID' => 'businessID',
            'value' => 'businessName'
        );
        echo json_encode(array(
            'resData' => $ObjPromotions->listBusiness($params),
            'fields' => $fields
        ));
    }
    //Load Shipping Methods
    public function ajaxLoadShippingMethodsAction() {
        $ObjPromotions = new PromotionsModel();
        $fields        = array(
            'ID' => 'settingsGroupID',
            'value' => 'settingsGroupXmlLabel'
        );
        echo json_encode(array(
            'resData' => $ObjPromotions->listShippingMethods(),
            'fields' => $fields
        ));
    }
    //Cart Rule Listing
    public function cartPromotionsAction() {
        $ObjPromotions          = new PromotionsModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $settingsDateFormat     = $date_format = $this->getSettingValue('site_settings', 'date_format');
        $link                   = 'promotions/cartpromotions/';
        if (isset($_POST['submitSearch'])) {
            if ($_POST['ruleName'] != '') {
                $link .= 'sname/' . $this->encodeUrlString($_POST['ruleName']) . '/';
            }
            if ($_POST['dateRangeSearch'] != '') {
                $searchDates = explode(' - ', $_POST['dateRangeSearch']);
                $fromDate    = $searchDates[0];
                $toDate      = '';
                if (isset($searchDates[1])) {
                    $toDate = $searchDates[1];
                }
                $link .= 'sfromdate/' . $this->urlDate(trim($fromDate), 'set', $settingsDateFormat) . '/';
                if ($toDate != '') {
                    $link .= 'stodate/' . $this->urlDate(trim($toDate), 'set', $settingsDateFormat) . '/';
                }
            }
            if ($_POST['status'] != '') {
                $link .= 'sstatus/' . $this->encodeUrlString($_POST['status']) . '/';
            }
            $this->setRedirect($link);
        }
        // bulk status change			
        if (isset($_POST['changeStatus']) && $_POST['changeStatus'] != '') {
            $statusUpdate = $ObjPromotions->updateCartPromotionStatus();
            if ($_POST['changeStatus'] == "D") {
                $this->setMessage("language.msgPromotionDeleted", 3);
            } else {
                $this->setMessage("language.msgPromotionStatus", 3);
            }
            $this->setRedirect($this->ObjCommon->selfURL(), "No");
            exit;
        }
        $searchRuleName = $this->decodeUrlString($this->getRequestValue("sname"));
        $searchFromDate = $this->urlDate($this->getRequestValue("sfromdate"), 'get', $settingsDateFormat);
        $searchToDate   = $this->urlDate($this->getRequestValue("stodate"), 'get', $settingsDateFormat);
        $searchStatus   = $this->getRequestValue("sstatus");
        $sortBy         = $this->getRequestValue("sortby");
        $orderBy        = $this->getRequestValue("orderby");
        if ($searchRuleName != '') {
            $link .= "sname/" . $this->encodeUrlString($searchRuleName) . "/";
        }
        if ($searchFromDate) {
            $link .= "sfromdate/" . $this->urlDate($searchFromDate, 'set', $settingsDateFormat) . "/";
        }
        if ($searchToDate) {
            $link .= "stodate/" . $this->urlDate($searchToDate, 'set', $settingsDateFormat) . "/";
        }
        if ($searchStatus) {
            $link .= "sstatus/" . $searchStatus . "/";
        }
        if ($sortBy != '' && $orderBy != '') {
            if (($sortBy == "rulename") && ($orderBy == "asc")) {
                $sortByRuleName = "desc";
            } elseif (($sortBy == "rulename") && ($orderBy == "desc")) {
                $sortByRuleName = "asc";
            }
            if (($sortBy == "fromdate") && ($orderBy == "asc")) {
                $sortByFromDate = "desc";
            } elseif (($sortBy == "fromdate") && ($orderBy == "desc")) {
                $sortByFromDate = "asc";
            }
            if (($sortBy == "todate") && ($orderBy == "asc")) {
                $sortByToDate = "desc";
            } elseif (($sortBy == "todate") && ($orderBy == "desc")) {
                $sortByToDate = "asc";
            }
            if (($sortBy == "priority") && ($orderBy == "asc")) {
                $sortByPriority = "desc";
            } elseif (($sortBy == "priority") && ($orderBy == "desc")) {
                $sortByPriority = "asc";
            }
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $searchStatus  = strtoupper($searchStatus);
        $params        = array(
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo,
            'ruleName' => $searchRuleName,
            'fromDate' => $this->convertDateForSQL($searchFromDate, $settingsDateFormat),
            'toDate' => $this->convertDateForSQL($searchToDate, $settingsDateFormat),
            'status' => $searchStatus,
            'sortBy' => $sortBy,
            'orderBy' => $orderBy
        );
        $resCartRules  = $ObjPromotions->listCartRules($languageIDs, $params);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign("resCartRules", $resCartRules);
        //Privilege
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('promotions/editcartrule/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('promotions/destroycartrule/'));
        //Privilege
        $this->ObjView->assign('link', $link);
        $this->ObjView->assign('ruleName', $searchRuleName);
        if ($searchFromDate && $searchToDate == '') {
            $this->ObjView->assign('dateRangeSearch', $searchFromDate);
        } else if ($searchFromDate && $searchToDate) {
            $this->ObjView->assign('dateRangeSearch', $searchFromDate . ' - ' . $searchToDate);
        } else {
            $this->ObjView->assign('dateRangeSearch', '');
        }
        $this->ObjView->assign('status', $searchStatus);
        $this->ObjView->assign('sortByRuleName', isset($sortByRuleName) ? $sortByRuleName : '');
        $this->ObjView->assign('sortByFromDate', isset($sortByFromDate) ? $sortByFromDate : '');
        $this->ObjView->assign('sortByToDate', isset($sortByToDate) ? $sortByToDate : '');
        $this->ObjView->assign('sortByPriority', isset($sortByPriority) ? $sortByPriority : '');
        $this->ObjView->display('CartPromotionList.tpl');
    }
    //Call Back Function For coupon code Existence checking
    public function checkPromoCouponExists() {
        $ObjPromotions = new PromotionsModel();
        if ($_POST['couponCode'] != '' && $_POST['couponType'] == "2") {
            $ruleID = (isset($_POST['ruleID'])) ? trim($_POST['ruleID']) : "";
            $params = array(
                'ruleID' => $ruleID,
                'couponCode' => trim($_POST['couponCode'])
            );
            if ($ObjPromotions->checkExistingCoupon($params)) {
                return false;
            }
        }
        return true;
    }
    //Edit Cart Rule
    public function editCartRuleAction() {
        $ruleID = $this->getRequestValue('id');
        if (empty($ruleID) || $ruleID < 1) {
            $this->setRedirect('promotions/cartpromotions/');
            exit;
        }
        $ObjImage      = new ImageModel();
        $ObjPromotions = new PromotionsModel();
        $languageIDs   = $this->ObjView->languageIDs;
        //Auto Generate Coupon Codes
        if (isset($_POST['generateCoupons']) && $this->ObjForm->isValid('generateCouponCodes', 'generateCoupons')) {
            //Auto generate Only
            if ($_POST['currentCouponType'] == "3") {
                $params = array(
                    'promoNoOfCode' => $_POST['promoNoOfCode'],
                    'promoCodeLength' => $_POST['promoCodeLength'],
                    'ruleID' => $ruleID,
                    'dbCouponType' => $_POST['dbCouponType'],
                    'currentCouponType' => $_POST['currentCouponType']
                );
                if ($ObjPromotions->generateCouponCodes($params)) {
                    $this->setMessage("language.msgPromoCouponGenerate", 3);
                    $this->setRedirect('promotions/editcartrule/id/' . $ruleID . '/section/coupons/');
                    exit;
                } else {
                    $this->setMessage("language.errPromoCouponGenerate", 4);
                    $this->setRedirect('promotions/editcartrule/id/' . $ruleID . '/section/coupons/');
                    exit;
                }
            }
        }
        //Delete Coupons
        if (isset($_POST['deleteCouponCode']) && !empty($_POST['checkCouponIDs'])) {
            if ($ObjPromotions->deletePromoCoupons($ruleID)) {
                $this->setMessage("language.msgCouponDeleted", 3);
            }
        }
        //Export Coupons
        if (isset($_POST['exportCoupons'])) {
            $params             = array(
                'ruleID' => $ruleID,
                'export' => 'Yes'
            );
            $resPromoCouponsCsv = $ObjPromotions->getCartPromoCoupons($params);
            $ObjCsv             = new Csv();
            $csvOutputHeader    = array(
                $this->getLanguageValue("lblPromoCouponCode"),
                $this->getLanguageValue("lblPromoTimesUsed")
            );
            $csvOutputFileName  = "promo_coupon_list_" . date('d_m_Y_h_i_s_A') . '.csv';
            $csvOutputData      = $ObjCsv->output($csvOutputFileName, $resPromoCouponsCsv, $csvOutputHeader);
            exit;
        }
        $languageIDs['Current'] = $languageIDs['Content'];
        $params                 = array(
            'languageIDs' => $languageIDs,
            'ruleID' => $ruleID
        );
        $resPromo               = $ObjPromotions->getCartPromotionDetails($params);
        //print_r($resPromo);		
        if (!empty($resPromo)) {
            if (empty($_POST['submitCartPromotions'])) {
                list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
                $params          = array(
                    'limitFrom' => $limitFrom,
                    'limitTo' => $limitTo,
                    'ruleID' => $ruleID
                );
                $resPromoCoupons = $ObjPromotions->getCartPromoCoupons($params);
                $resPagesCount   = $this->setPagesCount($key = 'page');
                if ($resPromo['couponType'] == "2") {
                    $resPromo['couponCode'] = $resPromoCoupons[0]['couponCode'];
                    $_POST['dbCouponCode']  = $resPromo['couponCode'];
                    //$resPromoCoupons        = '';
                }
                $this->ObjView->assign("resPromo", $resPromo);
                $this->ObjView->assign("resPromoCoupons", $resPromoCoupons);
                //Conditions
                $resDataConditions               = unserialize($resPromo['conditions']);
                $params                          = array(
                    'languageIDs' => $languageIDs,
                    'type' => "promoCart",
                    'languageXml' => $this->ObjView->_languageXML,
                    'conditionArray' => $resDataConditions['conditions']
                );
                $rewriteConditions               = $ObjPromotions->rewriteConditions($params);
                $resDataConditions['conditions'] = $rewriteConditions['conditionOrigArray'];
                //Bonus
                $resDataBonus                    = unserialize($resPromo['bonusConditions']);
                //print_r($resDataBonus);				
                $params                          = array(
                    'languageIDs' => $languageIDs,
                    'languageXml' => $this->ObjView->_languageXML,
                    'bonusArray' => $resDataBonus['bonuses']
                );
                $rewriteBonus                    = $ObjPromotions->rewriteBonus($params);
                //print_r($rewriteBonus);	
                if ($rewriteBonus['bonusOrigArray']) {
                    $resDataBonus['bonus'] = $rewriteBonus['bonusOrigArray'];
                }
                //print_r($resDataBonus);			
                //Free Products			
                $params           = array(
                    'languageIDs' => $languageIDs,
                    'freeProducts' => $resPromo['freeProducts'],
                    'language' => $this->ObjView->_languageXML
                );
                $freeProductsData = $ObjPromotions->getFreeProductsData($params);
                //print_r($freeProductsData);
                $this->ObjView->assign("freeProductsData", $freeProductsData);
                $this->ObjView->assign("resDataConditions", $resDataConditions);
                $this->ObjView->assign("resDataBonus", $resDataBonus);
                if (!empty($rewriteConditions['attrData'])) {
                    $this->ObjView->assign("attrData", json_encode($rewriteConditions['attrData']));
                } elseif (!empty($rewriteBonus['attrData'])) {
                    $this->ObjView->assign("attrData", json_encode($rewriteBonus['attrData']));
                }
                if ($rewriteConditions['userGrpData']) {
                    $this->ObjView->assign("userGrpData", $rewriteConditions['userGrpData']);
                } elseif (isset($rewriteBonus['userGrpData'])) {
                    $this->ObjView->assign("userGrpData", $rewriteBonus['userGrpData']);
                }
                $this->ObjView->assign("countryData", $rewriteConditions['countryData']);
                $this->ObjView->assign("paymentMethodData", $rewriteConditions['paymentMethodData']);
            } else {
                /*unlink old image*/
                if (!empty($_POST["promoImage_temp"])) {
                    $imagePath = __UPLOADS_FOLDER . 'promotions/cart/' . trim($resPromo['promoImage']);
                    $ObjImage->unlinkImage($imagePath);
                }
                /*unlink old image*/
                $_POST['ruleID'] = $ruleID;
            }
            $this->ObjView->assign("ruleID", $ruleID);
            $promoWebAppEnabled = array();
            if($resPromo['promoWebAppEnabled']=='Both') {
                $promoWebAppEnabled[0] = 'Web';
                $promoWebAppEnabled[1] = 'App';

            } else {
                $promoWebAppEnabled[0] = $resPromo['promoWebAppEnabled'];
            }                 
            $this->ObjView->assign("promoWebAppEnabled",$promoWebAppEnabled);
            $this->addCartPromotionsAction($ruleID);
        } else {
            $this->setRedirect('promotions/cartpromotions/');
            exit;
        }
    }
    //Change Cart Promotion Status
    public function ajaxChangeCartPromoStatusAction() {
        $ObjPromotions         = new PromotionsModel();
        $_POST['id']           = $_POST['promoID'];
        $_POST['changeStatus'] = $_POST['promoStatus'];
        $statusUpdate          = $ObjPromotions->updateCartPromotionStatus();
        $this->setMessage("language.msgPromotionStatus", 3);
    }
    //Delete Cart Promotion
    public function ajaxDestroyCartPromoAction() {
        $ObjPromotions = new PromotionsModel();
        $ruleID        = $this->getRequestValue('id');
        if ($ruleID > 0) {
            $_POST['id']           = $ruleID;
            $_POST['changeStatus'] = 'D';
            if ($ObjPromotions->updateCartPromotionStatus()) {
                $this->setMessage("language.msgPromotionDeleted", 3);
            }
        }
        $this->setRedirect('promotions/cartpromotions/');
        exit;
    }
    //Apply Rules
    public function ajaxApplyRulesAction() {
        $debugRules = $this->getRequestValue("debug");
        $debug      = ($debugRules == "1") ? true : false;
        $this->ObjCommon->askPrivilege('promotions/applyrules/');
        $params       = array(
            'debug' => $debug
        );
        $updateStatus = $this->ObjCommon->calculateOfferPrice($params);
        if (!$params['debug']) {
            if ($updateStatus) {
                $this->setMessage("language.msgPromoRuleApply", 3);
            } else {
                $this->setMessage("language.errPromoRuleApply", 4);
            }
            $this->setRedirect('promotions/index/');
            exit;
        }
    }
    //Callback for empty conditions
    public function checkConditionFields() {
        if ($_POST['validateConditionValues'] == "1") {
            return false;
        }
        return true;
    }
    //Callback for empty bonus
    public function checkBonusFields() {
        if ($_POST['validateBonusValues'] == "1") {
            return false;
        }
        return true;
    }
    //List Merchants
    public function ajaxListMerchantAction() {
        $ObjPromotions          = new PromotionsModel();
        $ObjBusinessType        = new BusinessTypeModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $link                   = 'promotions/ajaxlistmerchant/';
        if (isset($_POST['submitSearch'])) {
            if ($_POST['businessTypeID'] != '') {
                $link .= 'type/' . $_POST['businessTypeID'] . '/';
            }
            if ($_POST['businessName'] != '') {
                $link .= 'name/' . $this->encodeUrlString($_POST['businessName']) . '/';
            }
            $this->setRedirect($link);
        }
        $businessTypeID = $this->getRequestValue('type');
        $businessName   = $this->decodeUrlString($this->getRequestValue('name'));
        $this->ObjView->assign('resBusinessTypes', $ObjBusinessType->getParentBusinessType($languageIDs));
        $this->ObjView->assign('businessTypeID', $businessTypeID);
        $this->ObjView->assign('businessName', $businessName);
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params        = array(
            'languageIDs' => $languageIDs,
            'businessTypeID' => $businessTypeID,
            'businessName' => $businessName,
            'limitFrom' => $limitFrom,
            'limitTo' => $limitTo
        );
        $resBusiness   = $ObjPromotions->listBusiness($params);
        $resPagesCount = $this->setPagesCount($key = 'page');
        $this->ObjView->assign('resBusiness', $resBusiness);
        $this->ObjView->display('AjaxMerchantList.tpl');
    }
    //Custom Options File Upload
    public function ajaxUploadAction() {
        $ObjCart = new CartModel();
        if (count($_FILES) > 0) {
            foreach ($_FILES as $key => $error) {
                $fileElementArray                            = explode('_', $key);
                $productID                                   = $fileElementArray[1];
                $customAttributeID                           = $fileElementArray[2];
                $fileNameArray['customOptions']['id']        = $customAttributeID;
                $fileNameArray['customOptions']['productID'] = $productID;
                $paramsArray                                 = array(
                    'tableName' => 'product_custom_option',
                    'fieldName' => 'validateRule',
                    'conditionField' => 'customOptionID',
                    'condition' => '=',
                    'conditionValue' => $customAttributeID,
                    'conditionFieldType' => 'int'
                );
                $resValidateRule                             = $ObjCart->getFieldValue($paramsArray);
                $validateRule                                = $resValidateRule['validateRule'];
                $validateRuleArray                           = explode('~*', $validateRule);
                if ($validateRule != '') {
                    $currentValue = $_FILES[$key]["name"];
                    foreach ($validateRuleArray as $key1 => $items1) {
                        $validate = $this->ObjForm->isValidField('option_' . $productID . '_' . $customAttributeID, $items1, $currentValue, 'Error');
                        if ($validate == 'Error') {
                            $validateFields = 1;
                            $errorType      = $items1;
                            break;
                        }
                    }
                }
                if ($validateFields == 1) {
                    $errorTypeArray             = explode('->', $errorType);
                    $errorType                  = $errorTypeArray[0];
                    $fileNameArray['isError']   = 'Yes';
                    $fileNameArray['errorType'] = $errorType;
                    if ($errorType == 'checkFileSize') {
                        $fileNameArray['errorMessage'] = $this->getLanguageValue("lblCartInvalidFileSizeErrorMsg");
                    } else if ($errorType == 'isValidFileExtension') {
                        $fileNameArray['errorMessage'] = $this->getLanguageValue("lblCartInvalidFileTypeErrorMsg");
                    }
                    break;
                } else {
                    $filename = $key . "--" . $_POST['currentTime'];
                    $ext      = substr($_FILES[$key]["name"], strpos($_FILES[$key]["name"], "."));
                    $tmp_name = $_FILES[$key]["tmp_name"];
                    $filename = $filename . $ext;
                    move_uploaded_file($tmp_name, __CORE_PUBLIC_PATH . "/uploads/user-upload/custom-option/" . $filename);
                    $fileNameArray['customOptions']['filename'] = $filename;
                }
            }
        } else {
            $fileNameArray['isError']      = 'Yes';
            $fileNameArray['noFile']       = 'Yes';
            $fileNameArray['errorMessage'] = $this->getLanguageValue("lblSelectAfile");
        }
        echo json_encode($fileNameArray);
    }
    //Callback for empty bonus
    public function checkBonusEntered() {
        if ($_POST['validateBonusEnteredValues'] == "1") {
            return false;
        }
        return true;
    }
    //Callback : Check Gift coupon Amount
    public function checkGiftCoupon() {
        if (!empty($_POST['promoDiscountGiftCoupon']) && $_POST['promoDiscountGiftCoupon'] <= 0) {
            return false;
        }
        return true;
    }
    //test Url for checking promotions
    public function promoProductsAction() {
        $ObjPromotions = new PromotionsModel();
        $total_pages   = $ObjPromotions->offerProductsCount();
        $limit         = 50; //how many items to show per page
        $page          = '';
        if (isset($_GET['page'])) {
            $page = $_GET['page'];
        }
        if ($page != '')
            $start = ($page - 1) * $limit; //first item to display on this page
        else
            $start = 0;
        $listParams = array(
            'start' => $start,
            'end' => $limit
        );
        $result     = $ObjPromotions->listOfferProducts($listParams);
        /* Setup page vars for display. */
        if ($page == 0)
            $page = 1; //if no page var is given, default to 1.
        $prev       = $page - 1; //previous page is page - 1
        $next       = $page + 1; //next page is page + 1
        $lastpage   = ceil($total_pages / $limit); //lastpage is = total pages / items per page, rounded up.
        $lpm1       = $lastpage - 1; //last page minus 1
        $pagination = "";
        if ($lastpage > 1) {
            $pagination .= "<div class=\"pagination\">";
            //previous button
            if ($page > 1)
                $pagination .= "<a href=\"?page=$prev\">« previous&nbsp;&nbsp;</a>";
            else
                $pagination .= "<span class=\"disabled\">« previous&nbsp;&nbsp;</span>";
            //next button
            if ($page < $lastpage)
                $pagination .= "<a href=\"?page=$next\">next »&nbsp;&nbsp;</a>";
            else
                $pagination .= "<span class=\"disabled\">next »&nbsp;&nbsp;</span>";
            $pagination .= "</div>\n";
        }
        echo '<p> Total : ' . $total_pages . '</p>';
        echo $pagination;
        echo '
		<table border="1" width="60%">
		<tr align="left">
		<th>Title</th>
		<th>SKU</th>
		<th>Price</th>
		</tr>';
        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
            echo '
			<tr>
			<td>' . $row["productTitle"] . '</td>
			<td>' . $row["optionSKU"] . '</td>
			<td>' . $row["offerPrice"] . '</td>
			</tr>';
        }
        echo '
		</table>';
        echo $pagination;
    }
	    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;
    }	
}
