<?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: CartController.php, v 1.0 2011/06/14 20:52:11 
//@Updated for v1.2 31-01-2013 02:30 PM
class CartController extends Controller {
    public function __construct() {
        parent::__construct();
        //shipping calculation parameters
        $this->_shippingCalculationParam['shippingFreeEnable']    = $this->getSettingValue('shipping_settings', 'shipping_free_enable');
        $this->_shippingCalculationParam['freeShippingAmount']    = $this->getSettingValue('shipping_settings', 'free_shipping_amount');
        $this->_shippingCalculationParam['freeShippingQty']       = $this->getSettingValue('shipping_settings', 'free_shipping_qty');
        $this->_shippingCalculationParam['defaultCurrency']       = $this->ObjView->_defaultCurrency;
        $this->_shippingCalculationParam['shippingTaxable']       = $this->getSettingValue('product_cart_settings', 'shipping_taxable');
        $this->_shippingCalculationParam['group_shipping_cost']   = $this->getSettingValue('product_cart_settings', 'group_shipping_cost');
        $this->_shippingCalculationParam['shipping_cost_global']  = $this->getSettingValue('product_cart_settings', 'shipping_cost_global');
        $this->_taxCalculationParam['applyAfterDiscount']         = $this->getSettingValue('product_cart_settings', 'apply_after_discount');
        $this->_taxCalculationParam['taxApplicable']              = $this->getSettingValue('product_cart_settings', 'tax_applicable');
        $this->_taxCalculationParam['inclusive_tax']              = $this->getSettingValue('product_cart_settings', 'inclusive_tax');
        // Address type for tax calculation
        $this->_taxCalculationParam['addressType']                = $this->getSettingValue('product_cart_settings', 'tax_calculation_based_on');
        $this->_shippingCalculationParam['globalShippingCity']    = $this->getSettingValue('shipping_settings', 'global_shipping_city');
        $this->_shippingCalculationParam['globalShippingCountry'] = $this->getSettingValue('shipping_settings', 'global_shipping_country');
        $this->_shippingCalculationParam['globalShippingState']   = $this->getSettingValue('shipping_settings', 'global_shipping_state');
        $this->_shippingCalculationParam['globalShippingZipcode'] = $this->getSettingValue('shipping_settings', 'global_shipping_zipcode');
        $this->_shippingParam['global_shipping_baseCharge'] 	  = $this->getSettingValue('shipping_settings', 'global_shipping_baseCharge');
        
        
		$campaignID                                               = $this->ObjCookie->getCookie("EMAIL_CAMPAIGN_ID");
        //Cart recovery camaign 
        //@case user reched site by clicking the mail camaign
        //@usage Abandoned / Live carts
        $campaignID                                               = $this->ObjCookie->getCookie("EMAIL_CAMPAIGN_ID");
        //Cart recovery notification 
        //@case user reched site by clicking the notification mail
        //@usage Abandoned / Live carts
        $notificationID                                           = $this->ObjCookie->getCookie("EMAIL_NOTIFICATION_ID");
        if ($campaignID > 0 || $notificationID > 0)
            $this->ObjView->assign('cart_noti_camp_class', "special");
        //Page name 
        //@usage Analytics
		if($this->getRequestValue(1) == 'popup'){
			$this->ObjView->assign('isCartpopup', true);
		}
        
        $this->ObjView->assign('statPageName', 'cart');
    }
    //index action
    //@Usage :- For Cart item listing	
    //Start Function
//    public function showAction() {
//        $ObjCart                    = new CartModel();
//        $cartID                     = $this->decodeString($this->ObjSession->getSession("CARTID"));
//        $cartData                   = array();
//        $cartData['items']          = array();
//        
//        $resCart                    = $ObjCart->getCartDetails($cartID);  
//        if(empty($resCart['items'])) {            
//            $this->ObjView->assign('cartData',$cartData);
//            $this->ObjView->assign('userID', $this->ObjSession->getSession("REGISTERED_USER_ID"));        
//            $this->ObjView->assign('showCartNotification', 'Yes');
//            $this->ObjView->display('cart/Cart.tpl');
//        } else {
//            $this->setRedirect("/cart/");
//            exit;
//        }
//    }
//    public function indexAction() {
//        
//        $ObjCart        = new CartModel();
//        $ObjContent     = new ContentModel();
//        $ObjProductList = new ProductListModel();
//        $ObjProduct     = new ProductModel();
//        $userID         = $this->ObjSession->getSession("REGISTERED_USER_ID");
//        $cartID         = $this->decodeString($this->ObjSession->getSession("CARTID"));
//        //If the user reched payment gateway and then he close the payment page then return back to application
//        //Will make the order as error/Denied
//        $holdOrderID    = $this->ObjSession->getSession("HOLD_ORDERID");
//        if ($holdOrderID > 0) {
//            $ObjCart->changeMasterOrderStatus(0, 'Error', 'Denied', $holdOrderID);
//            $this->ObjSession->unsetSession("HOLD_ORDERID");
//        }
//        //Ends
//        
//        if ($cartID < 1) {
//             $this->setRedirect("/cart/show/n");
//        } else {
//            $freeProductGifts = 0;
//            $reset_tier_price = $ObjCart->resetCartItemsTierPrice($cartID, $this->ObjCommon->REGISTERED_USER_GROUP_ID);
//            $resShippingCalc  = $ObjCart->calculateShippingRate($cartID, $this->_shippingCalculationParam);
//            $promoResult      = $this->setPromoCodeDiscount('', '', 'reset');
//            $this->setCODFee();
//            $resTaxUpdate     = $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
//            $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
//            $resCart          = $ObjCart->getCartDetails($cartID);
//            
//            $validatedCart    = $this->validateCart($resCart, 'No', 'listing','checkFreeGift'); //Server side validation of cart items
//            if(empty($resCart)) {               
//               $this->setRedirect("/cart/show/n");
//            }
//            //Proceed to checkout button click
//            if (isset($_POST['complete']) && count($_POST['complete'])) {   
//                
//                if (count($validatedCart['error']) < 1 && count($validatedCart['errorFreeGift']) < 1) {                    
//                    $this->setRedirect("/cart/checkout/");
//                } else {                     
//                    $this->ObjSession->setSession("submitProceed",'Yes');                    
//                    $this->setRedirect("/cart/");
//                }
//            } else {
//                if($this->ObjSession->getSession("submitProceed")!='Yes') {
//                    $submitProceed = '';
//                } else {
//                    $submitProceed = $this->ObjSession->getSession("submitProceed");
//                }
//                $this->ObjSession->setSession("submitProceed",'');
//                if (empty($resCart['items'])) {
//                    $this->setRedirect("/cart/show/n");
//                } else {
//                    if (empty($validatedCart['items'])) {
//                        $this->setRedirect("/cart/show/n");
//                    } else {
//                        $languageIDs                = $this->ObjView->languageIDs;
//                        $paymentFaq                 = $ObjContent->getContentDetails($languageIDs, $contentID = "", '', $contentUrlKey = "payment-faqs");
//                        $settingsEnablePromoCode    = $this->getSettingValue('product_cart_settings', 'enable_promo_codes');
//                        $settingsApplyAfterDiscount = $this->getSettingValue('product_cart_settings', 'apply_after_discount');
//                        $settingsTaxApplicable      = $this->getSettingValue('product_cart_settings', 'tax_applicable');
//                        $prevProductID              = '';
//                        foreach ($validatedCart['items'] as $key => $items) {
//                            
//                            //check free gifts available
//                            if($items['freeProductsCount']>0 && $items['freeBaseProductID']<=0) {                                
//                                //get free products
//                                $argsFreeProducts                 = array(
//                                    'requestedBy' => 'customer',
//                                    'requestPage' => 'product_detail',
//                                    'limitFrom' => 0,
//                                    'limitTo' => '',
//                                    'languageIDs' => $languageIDs,
//                                    'previewOnly' => '',
//                                    'currDateTime' => '',                                    
//                                    'selectedProductID' => $items['productID'],
//                                    'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
//                                    
//                                );
//                                $freeProducts   = $ObjProduct->getActiveFreeProducts($argsFreeProducts);  
//                                if(!empty($freeProducts)) {
//                                    $freeProductGifts = ($items['freeProductsCount']>count($freeProducts)) ? $freeProductGifts + count($freeProducts):$freeProductGifts + $items['freeProductsCount'];
//                                }
//                                
//                            }
//                            $validatedCart['items'][$key]['unserialize'] = unserialize($items['itemDetails']);
//                            $resProductOptions                           = $ObjCart->listCartItemOptions($languageIDs, $items['productID'], 'Active');
//                            if (count($resProductOptions) == 1) {
//                                $validatedCart['items'][$key]['unserialize'] = unserialize($items['itemDetails']);
//                                if (count($resProductOptions) == 1) {
//                                    $validatedCart['items'][$key]['hasOption'] = 'No';
//                                } else {
//                                    $validatedCart['items'][$key]['hasOption'] = 'Yes';
//                                    $validatedCart['items'][$key]['options']   = $resProductOptions;
//                                }
//                                unset($resProductOptions);
//                            } else {
//                                $validatedCart['items'][$key]['hasOption'] = 'Yes';
//                                $validatedCart['items'][$key]['options']   = $resProductOptions;
//                            }
//                            unset($resProductOptions);
//                            if ($items['productDispatchTime'] > 0)
//                                $validatedCart['items'][$key]['productDispatchTime'] = $ObjProduct->getDispatchTimeByID($items['productDispatchTime']);
//
//                            //if user is logged in check, he have any saved shipping address, if available 
//                             //show shipping methods and calculate charge
//                            if($userID > 0){
//                                $shippingAddress = $ObjCart->getUserDefaultShippingAddress($userID);
//                                //echo count($shippingAddress);exit;
//                                if(count($shippingAddress) > 0){
//                                    //checking available shipping methods match with saved address
////                                                                $validatedCart['items'][$key]['shippingMethods'] = $this->isShippingAvailable($cartID,$items['productID'],$shippingAddress);
//                                     list($shippingMethods, $shippingReason) = $this->isShippingAvailable($cartID,$items['productID'],$shippingAddress);
//                                     $validatedCart['items'][$key]['shippingMethods'] = $shippingMethods;
//                                     $validatedCart['items'][$key]['shippingReason'] = $shippingReason;
//                                }else{
//                                    //$validatedCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']);
//                                    $validatedCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
//                                    $validatedCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
//
//                                }
//                            }else{
//                                 //get all assigned shipping methods for a product, user not logged on or 
//                                 //$validatedCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']);
//                                 $validatedCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
//                                 $validatedCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
//                                $resCartextra                   = unserialize($resCart['extra']);
//                                if( $resCartextra['userCheckoutEmail']!='') {
//                                    $resCartUpdate = $ObjCart->updateCartUserEmail($cartID,'');
//                                }	
//                            }
//
//                            $prevProductID = $items['productID'];
//                            //Product Regular Price
//                            $regularPrice                                       = $items['productOptionRegularPrice'];
//                            $qnty                                               = $items['orderItemQuantity'];
//                            $currentRegularPrice                                = ($regularPrice * $qnty);
//                            $validatedCart['items'][$key]['productOptionRegularPrice']  = number_format($currentRegularPrice, 2, '.', '');
//                        }
//                        //echo "<pre>";print_r($validatedCart);exit;
//                        
//                        $this->ObjView->assign('enablePromoCode', $settingsEnablePromoCode);
//                        $this->ObjView->assign('enableApplyAfterDiscount', $settingsApplyAfterDiscount);
//                        $this->ObjView->assign('taxApplicable', $settingsTaxApplicable);
//                        $this->ObjView->assign('paymentFaq', $paymentFaq);
//                        $this->ObjView->assign('cartData', $validatedCart);
//                        $this->ObjView->assign('userID', $userID);
//                        $this->ObjView->assign('blockQtyUpdate', "No");
//                        $this->ObjView->assign('showCartNotification', 'Yes');
//                        $this->ObjView->assign('submitProceed', $submitProceed);
//                        $this->ObjView->assign('freeProductGifts', $freeProductGifts);
//                        $this->ObjView->display('cart/Cart.tpl'); 
//                        
//                    }
//                }
//            }
//        }
//    }
    //End of function
//    public function processcheckoutAction() {
//        $ObjCart        = new CartModel();
//        $resCart        = $ObjCart->getCartDetails($cartID);
//        $cartID         = $this->decodeString($this->ObjSession->getSession("CARTID"));
//        $validatedCart  = $this->validateCart($resCart, 'No', 'listing');
//        if (count($validatedCart['error']) < 1) {
//            $this->setRedirect("/cart/checkout/");
//        } else {
//            $this->setRedirect("/cart/");
//        }
//    }
    //Action which specified in return urls of payment gateways
    //Start Function
    public function expresscheckoutAction() {
        
        $ObjPayment        = new PaymentModel();
        $ObjPaymentgateway = new PaymentgatewayModel();
        $ObjCart           = new CartModel();
        $orderProcess      = 1;
        $languageIDs       = $this->ObjView->languageIDs;    
		$refNGenius        = '';
        if ($this->getRequestValue("source") == 'networkonline' || $this->getRequestValue("source") == 'ngeniusonline') {
            $order_id = $this->getRequestValue("orderID");
            $order_id = $this->decodeString($order_id);
			if($this->getRequestValue("source") == 'ngeniusonline') 
            {
                $refNGenius = $_REQUEST["ref"];
               
            }
        } else {
            $order_id = $this->decodeString($this->getRequestValue("orderID"));
        }
        $order_id               = (int)(trim($order_id));
        //get order array
        $getOrderDetails        = $ObjCart->getOrderMasterDetailsByParentOrderID($order_id);
        $getOrderedItems        = $ObjCart->getOrderItemDetailsByParentOrderID($order_id, array());
        $paymentSettingsGroupID = $getOrderDetails['paymentSettingsGroupID'];
        $currency               = $getOrderDetails['purchasedCurrency'];
        $payAmount              = $getOrderDetails['orderTotalAmount'];
        if ($getOrderDetails['paymentSettingsGroupID'] > 0) {
            $paymentGateWayDetails = $ObjPaymentgateway->getPaymentSettingGroupDetails($getOrderDetails['paymentSettingsGroupID']);
            $paymentSettingsValues = $ObjPayment->listPaymentSettingsValues($paymentSettingsGroupID);
        }
        
        //=====================================================================================
        $resTransactionType = $ObjPaymentgateway->listPaymentSettingsByGroupId($getOrderDetails['paymentSettingsGroupID'], '', 'transaction_type');
        if ($resTransactionType[0]['paySetValue'] == 'AUTH_ONLY') {
            $getOrderDetails['authValue'] = 'Authorization';
            $authOnly                     = 'AUTH_ONLY';
        } else {
            $authOnly                     = 'AUTH_CAPTURE';
            $getOrderDetails['authValue'] = 'Sale';
        }
        $getOrderDetails['orderStatus']     = 'Process';
        //=====================================================================================
        $getOrderDetails['siteDesc']        = substr($this->getSettingValue('site_settings', 'site_name'), 0, 90);
        $getOrderDetails['billingAddress']  = unserialize($getOrderDetails['billingAddress']);
        $getOrderDetails['shippingAddress'] = unserialize($getOrderDetails['shippingAddress']);
        $paySetGroupKey                     = $paymentGateWayDetails['paySetGroupKey'];
        $paymentMethodName                  = $getOrderDetails['orderPaymentMethodName'];
        switch ($paySetGroupKey) {
            case 'NetworkOnline':
                $className = 'NetworkOnlineModel';
                break;
			 case 'Ngeniusonline':
                $className = 'NgeniusonlineModel';
                break;
        }
        if ($className != '') {
                    $ObjPaymentLib = new Payment($className);
                    $Objgateway    = $ObjPaymentLib->getPaymentObject();
                    if (!is_object($Objgateway)) {
                        $this->setMessage("Gateway not configured", "error");
                        $this->setRedirect('/index/');
                        exit;
                    }
                }
        if ($paySetGroupKey == 'NetworkOnline') {
            if(!empty($_REQUEST)) {
                unset($_REQUEST['q']);
                $filterRequest = array();
                foreach( $_REQUEST as $key => $value) {
                    if($key == 'responseParameter' || $key == 'merchantId')
                            $filterRequest[$key] = $value;
                }
                $paymentResponse = $Objgateway->getResponse($getOrderDetails, $filterRequest);
                // FieldBitmap|StatusFlag|ErrorCode|ErrorMessage
                if($paymentResponse['Transaction_related_information']!=NULL){
                    $Transaction_related_information    =   $paymentResponse['Transaction_related_information'];
                     $txnResponse    =   explode('|',$paymentResponse['Transaction_related_information']);
                }
                else{
                    $Transaction_related_information =   '';
                    $txnResponse=   '';
                }
                $txnID  =   $txnResponse[1];
                if($paymentResponse['Transaction_Status_information']!=NULL){
                    $Transaction_Status_information    =   $paymentResponse['Transaction_Status_information'];
                     $txnStatusResponse    =   explode('|',$paymentResponse['Transaction_Status_information']);
                }
                else{
                    $Transaction_related_information =   '';
                    $txnStatusResponse=   '';
                }
                $txnStatus  =   $txnStatusResponse[1];
                $errorCode  =   $txnStatusResponse[2];
                $errorMessage  =   $txnStatusResponse[3];
                if($txnStatus == 'SUCCESS' && $errorCode==00000){
                    $paymentResponse = 'Pending';
                }else{
                    $paymentResponse = 'Failure';
                }
                
                if($paymentResponse=='Pending') {
                    $rescurrency     = $ObjPayment->getSupportingCurrencyDetails($currency, $paymentSettingsGroupID);            
                    if ($rescurrency['currencyID'] > 0) {
                        $amount = $this->ObjView->convertValueCustom($payAmount, $currency, $rescurrency['currencyID']);
                    }
                    $ObjPayment->createTransaction($getOrderDetails, $txnID, $Transaction_related_information."||".$Transaction_Status_information, $Transaction_related_information."||".$Transaction_Status_information, "AUTH_CAPTURE", 0, $paymentMethodName, $rescurrency['currencyID'], $amount);
                } else {
                    $ObjPayment->createTransactionError($getOrderDetails, $txnID, $Transaction_related_information."||".$Transaction_Status_information, $Transaction_related_information."||".$Transaction_Status_information, "AUTH_CAPTURE", 0, $paymentMethodName);
                }
            } else {
                $paymentResponse = '';
            }
        } elseif ($paySetGroupKey == 'Ngeniusonline') {
            if(!empty($_REQUEST)) {
                unset($_REQUEST['q']);                
                $Transaction_related_information =   '';
                $txnResponse=   '';                
                $txnID  =   $refNGenius;                
                $rescurrency     = $ObjPayment->getSupportingCurrencyDetails($currency, $paymentSettingsGroupID);            
                if ($rescurrency['currencyID'] > 0) {
                    $amount = $this->ObjView->convertValueCustom($payAmount, $currency, $rescurrency['currencyID']);
                }
                $paymentResponse = $Objgateway->getResponse($getOrderDetails, $txnID,$amount,$rescurrency['currencyID']);                
            } else {
                $paymentResponse = '';
            }
        }       
       
        $this->ObjSession->setSession("CART_REDIRECT_PAYMENT", "");
        //For managing the payment express dual processing issue
        if ($orderProcess == 1) {
            $orderSuccess = ($paymentResponse == 'Pending') ? 'Success' : 'Failure';
            if ($orderSuccess == 'Success') {
				
				if($paySetGroupKey=='NetworkOnline' || $paySetGroupKey=='Ngeniusonline'){
					$method = 'credit-card';
				}
				else{
					$method = 'pay-at-showroom';
				}
				
                $order_id = $this->paymentSuccess($order_id);
                $orderID    =   $this->encryptDecrypt("encrypt",$order_id);
                $this->ObjSession->setSession("CART_REDIRECT", "Yes");
                //$ObjCart->changeMasterOrderStatus(0, 'Pending', '', $order_id,'update');
                $_SESSION['CART_REDIRECT'] = 'Yes';    
                $this->setRedirect('/payment/index/type/'.$method.'/id/' . $orderID . '/');
                exit;
            } else {
                $ObjCart->changeMasterOrderStatus(0, 'Error', 'Denied', $order_id);
                if($errorMessage!='') {
                    $Objgateway->isError        = true;
                    $Objgateway->errorMessage   = $errorMessage;
                }
                if ($orderSuccess == 'Failure' && $Objgateway->isError) {
                    $this->ObjSession->setSession("CART_REDIRECT_PAYMENT", "Yes");
                    $this->setMessage($Objgateway->errorMessage,"error",'CheckoutSection','checkout_message');
                }
                $orderitem  =   $ObjCart->getOrderItemDetails($order_id);
                $productID  =   $orderitem[0]['productID'];
                $ObjUrl                     =   new UrlrewriteModel();
                $requestUrlDetails  =   $ObjUrl->getRequestPathByIdPath($languageIDs['Current'], 'product/'.$productID."/");
                $this->setRedirect($requestUrlDetails['requestPath']."?checkout=error");
                exit;
            }
        }
    }
    //End of function
    //This will be the cancel url action for the payment gateways
    public function unholdCartAction() {
        $ObjCart = new CartModel();
        $orderID = $this->decodeString($this->getRequestValue("orderID"));
        $ObjCart->changeMasterOrderStatus(0, 'Error', 'Denied', $orderID);
        $this->reupdateCartPromoUsage();
        $this->setRedirect("/cart/checkout/");
        exit;
    }
    //For MIGS Gateway
    public function unlockAction() {
        $ObjCart    = new CartModel();
        $orderParam = $this->getRequestValue("id");
        $orderID    = $this->decode($orderParam);
        //Unhold the order
        if ($orderID != '') {
            $ObjCart->changeMasterOrderStatus(0, 'Error', 'Denied', $orderID);
            $this->reupdateCartPromoUsage();
            $this->setMessage($Objgateway->errorMessage, 'error', 'message_error_small', 'AjaxpaymentErrorMessage');
            $this->setRedirect('/cart/');
            exit();
        }
        $this->setRedirect("/index/");
        exit();
    }
    //For MIGS
    function decode($value) {
        if (!$value) {
            return false;
        }
        $crypttext   = $this->safe_b64decode($value);
        $iv_size     = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv          = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, "DEAL_SYSTEM", $crypttext, MCRYPT_MODE_ECB, $iv);
        return trim($decrypttext);
    }
    //For MIGS
    function safe_b64decode($string) {
        $data = str_replace(array(
            '-',
            '_'
        ), array(
            '+',
            '/'
        ), $string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }
    //For tracking order placed in analytics
    //@usage Analytics
    //@usage Cart Recovery Report
//    function paymentTracking($orderAmount) {
//        $ObjLog             = new AnalyticsModel();
//        $visitorID          = $this->ObjCookie->getCookie("GT_VISITORID");
//        //FOR TRACKING LOG DETAILS
//        $actionName         = "order";
//        $visitorDetailsArr  = $ObjLog->getDetails($visitorID);
//        $currentOrderTotal  = $orderAmount;
//        $previousOrderAmt   = $visitorDetailsArr['orderAmount'];
//        $visitorTotOrderAmt = $previousOrderAmt + $currentOrderTotal;
//        $updateAction       = $ObjLog->updateVisitorActions($visitorID, $actionName, $visitorTotOrderAmt); //UPDATING VISITOR ORDER DETAILS
//        $campaignID         = $this->ObjCookie->getCookie("EMAIL_CAMPAIGN_ID");
//        if ($campaignID > 0) {
//            $updateCampaignDetails = $ObjLog->updateCampaignDetails($campaignID, 'purchase', $orderAmount);
//        }
//    }
    //Save affiliate Commission
    public function setAffiliateCommission($orderID = 0) {
        $ObjAffiliate         = new AffiliateModel();
        $ObjUser              = new UserModel();
        $ObjCart              = new CartModel();
        $affOrders            = 0;
        $commissionAmount     = 0;
        $commissionPercentage = 0;
        $affVisitorID         = '';
        $affUserStat          = '';
        $updateCommission     = 1;
        //Commission Status
        $commissionStatus     = 'New';
        //Mode
        $commissionMode       = "Direct"; //Direct/Tier
        //Level
        $commissionLevel      = '';
        if (__AFFILIATE_ENABLE) {
            $affCookieUserID    = $this->ObjCookie->getCookie("affiliateUserID");
            $orderDetails       = $ObjCart->getOrderMasterDetails($orderID);
            $masterOrderDetails = $ObjCart->getOrderMasterDetailsByOrderNumber($orderDetails['orderNumber']);
            $defaultCurrencyId  = $this->ObjView->_defaultCurrency;
            $cartcurrencyId     = $orderDetails['purchasedCurrency'];
            $orderSubTotal      = $orderDetails['orderSubtotal'];
            $masterSubTotal     = $masterOrderDetails['orderSubtotal'];
            //Set Commission Status
            if ($orderDetails['orderStatus'] == "Completed" && $orderDetails['paymentStatus'] == "Received") {
                $commissionStatus = 'Active';
            }
            //If Cookie is Available : Direct Sales Mode			
            if (isset($affCookieUserID) && $affCookieUserID != '') {
                $settingsEnableSalesCommission = $this->getSettingValue('affiliate_settings', 'affiliate_enable_sales_commission');
                $affiliateUserID               = $affCookieUserID;
                $affiliateCommissionSettings   = $ObjAffiliate->getAffCommissionSettings($affiliateUserID, 'cart');
                //Check Sales Commission Enabled in Settings and For Affiliate
                if ($settingsEnableSalesCommission == "Yes" && $affiliateCommissionSettings['enableSalesCommission'] == "Yes") {
                    //Get Active Orders
                    $activeOrders = $ObjAffiliate->getActiveOrders($affiliateUserID, 'F', 'IncludeNew');
                    //Recurring Purchase Commission
                    if ($activeOrders > 0) {
                        //Check Commission Type
                        if ($affiliateCommissionSettings['recurringPurchaseCommissionType'] == 'Value') {
                            $commissionAmount = $affiliateCommissionSettings['recurringPurchaseCommissionValue'];
                            $commissionAmount = $commissionAmount * ($orderSubTotal / $masterSubTotal);
                            $commissionAmount = number_format($commissionAmount, 5, '.', '');
                        } elseif ($affiliateCommissionSettings['recurringPurchaseCommissionType'] == 'Percentage') {
                            $commissionAmount     = ($orderSubTotal * $affiliateCommissionSettings['recurringPurchaseCommissionValue']) / 100;
                            $commissionPercentage = $affiliateCommissionSettings['recurringPurchaseCommissionValue'];
                        }
                        //Next
                        $commissionLevel = 'N';
                    } else {
                        //Check rollBack Orders
                        $rollBackOrders = $ObjAffiliate->listRollbackOrdersForAff($affiliateUserID, 'checkLevel');
                        if (count($rollBackOrders) > 0) //Recurring Purchase Commission
                            {
                            //Check Commission Type
                            if ($affiliateCommissionSettings['recurringPurchaseCommissionType'] == 'Value') {
                                $commissionAmount = $affiliateCommissionSettings['recurringPurchaseCommissionValue'];
                                $commissionAmount = $commissionAmount * ($orderSubTotal / $masterSubTotal);
                                $commissionAmount = number_format($commissionAmount, 5, '.', '');
                            } elseif ($affiliateCommissionSettings['recurringPurchaseCommissionType'] == 'Percentage') {
                                $commissionAmount     = ($orderSubTotal * $affiliateCommissionSettings['recurringPurchaseCommissionValue']) / 100;
                                $commissionPercentage = $affiliateCommissionSettings['recurringPurchaseCommissionValue'];
                            }
                            //Next
                            $commissionLevel = 'N';
                        } else //First Purchase Commission Value
                            {
                            //Check Commission Type
                            if ($affiliateCommissionSettings['firstPurchaseCommissionType'] == 'Value') {
                                $commissionAmount = $affiliateCommissionSettings['firstPurchaseCommissionValue'];
                                $commissionAmount = $commissionAmount * ($orderSubTotal / $masterSubTotal);
                                $commissionAmount = number_format($commissionAmount, 5, '.', '');
                            } elseif ($affiliateCommissionSettings['firstPurchaseCommissionType'] == 'Percentage') {
                                $commissionAmount     = ($orderSubTotal * $affiliateCommissionSettings['firstPurchaseCommissionValue']) / 100;
                                $commissionPercentage = $affiliateCommissionSettings['firstPurchaseCommissionValue'];
                            }
                            //First
                            $commissionLevel = 'F';
                        }
                    }
                } else {
                    $updateCommission = 0;
                }
            } else //If Cookie is Unavailable : Tier Mode
                {
                $userID = $orderDetails['userID'];
                if ($userID > 0) {
                    $resUserDetails               = $ObjUser->getUserDetails($userID);
                    $userEmail                    = $resUserDetails['userEmail'];
                    $commissionMode               = "Tier";
                    $settingsEnableTierCommission = $this->getSettingValue('affiliate_settings', 'affiliate_enable_tier_commission');
                    //Get Affiliate User Mapping
                    $affUserMapping               = $ObjAffiliate->checkAffMapping('', $userID, 'Registration');
                    //Get User mapping From Affiliate Import
                    $affIDFromImport              = $ObjAffiliate->getAffIDFromImport($userEmail, 'Yes');
                    //Get AffuserID From User Mapping
                    if ($affUserMapping['affiliateUserID'] > 0) {
                        $affiliateUserID = $affUserMapping['affiliateUserID'];
                    } elseif ($affIDFromImport > 0) //Get AffuserID From Import Mapping
                        {
                        $affiliateUserID = $affIDFromImport;
                    }
                    if (isset($affiliateUserID) && $affiliateUserID > 0) {
                        //Get Active Orders/Tier Level
                        $affActiveTierLevel          = $ObjAffiliate->getActiveOrders($affiliateUserID, 'T');
                        $affiliateCommissionSettings = $ObjAffiliate->getAffCommissionSettings($affiliateUserID, 'cart');
                        $tierCommisionSettingsLevel  = $affiliateCommissionSettings['tierCommissionLevel'];
                        //Check Tier Commission Enabled in Settings and For Affiliate, Also check Tier level
                        if ($settingsEnableTierCommission == "Yes" && $affiliateCommissionSettings['enableTierCommission'] == "Yes" && $tierCommisionSettingsLevel > $affActiveTierLevel) {
                            //Check Commission Type
                            if ($affiliateCommissionSettings['tierCommissionType'] == 'Value') {
                                $commissionAmount = $affiliateCommissionSettings['tierCommissionValue'];
                                $commissionAmount = $commissionAmount * ($orderSubTotal / $masterSubTotal);
                                $commissionAmount = number_format($commissionAmount, 5, '.', '');
                            } elseif ($affiliateCommissionSettings['tierCommissionType'] == 'Percentage') {
                                $commissionAmount     = ($orderSubTotal * $affiliateCommissionSettings['tierCommissionValue']) / 100;
                                $commissionPercentage = $affiliateCommissionSettings['tierCommissionValue'];
                            }
                            //Tier
                            $commissionLevel = 'T';
                        } else {
                            $updateCommission = 0;
                        }
                    }
                }
            }
            if (isset($affiliateUserID) && $affiliateUserID > 0) {
                $affUserStat = $ObjAffiliate->getStatusOfAffiliate($affiliateUserID);
                $visitorID   = $this->ObjCookie->getCookie("GT_VISITORID");
                if ($affUserStat == 1 && $commissionAmount > 0 && $updateCommission == 1 && $commissionLevel != '') {
                    //Get Affiliate Visitor ID
                    $affVisitorID = $ObjAffiliate->getAffVisitorID($visitorID);
                    $affVisitorID = $affVisitorID['affVisitorID'];
                    if ($commissionMode == "Tier") {
                        $affVisitorID = 0;
                    }
                    if ($affVisitorID >= 0) {
                        //save Commission
                        $commissionAmount       = $this->ObjView->convertValueCustom($commissionAmount, $cartcurrencyId, $defaultCurrencyId);
                        $convertedOrderSubtotal = $this->ObjView->convertValueCustom($orderSubTotal, $cartcurrencyId, $defaultCurrencyId);
                        $ObjAffiliate->saveCommissionDetails($affVisitorID, $affiliateUserID, $commissionAmount, 'Order', $orderID, $commissionStatus, $commissionPercentage, $commissionLevel, $convertedOrderSubtotal);
                    }
                }
                //save Aff Performance
                $ObjAffiliate->saveAffiliatePerformance($visitorID, $orderID, 'Order');
            }
        }
    }
    //Check For Already Completed Order
    public function checkOrderAction($orderID) {
        $ObjCart      = new CartModel();
        $orderDetails = $ObjCart->getOrderMasterDetails($orderID);
        if ((isset($orderDetails['orderNumber']) && $orderDetails['orderNumber'] > 0) && ($orderDetails['orderStatus'] == "Process" || $orderDetails['orderStatus'] == "Completed") && ($orderDetails['paymentStatus'] == "Pending" || $orderDetails['paymentStatus'] == "Received")) {
            $this->setRedirect("/index/");
        }
    }
    //to get template details between given comments
    function getTemplateDetails($comments, $string) {
        $beginTxt      = '<!--' . $comments . ' BEGIN-->';
        $endTxt        = '<!--' . $comments . ' END-->';
        $otherTemplate = substr($string, strlen($beginTxt) + strpos($string, $beginTxt), (strlen($string) - strpos($string, $endTxt)) * (-1));
        return $otherTemplate;
    }
    //Function for getting custom option details from server as per the user selection on add to cart
    //@usage add to cart
    private function getCustomOptionStringAndPriceDiff($custom_option_values = array(), $params = array()) {
        $ObjCart              = new CartModel();
        $custom_option_string = '';
        $custComb = '';
		$optionInactive = '';
        foreach ($custom_option_values as $item) {
            $sub_array = explode('~:', $item);
            if (count($sub_array) > 0) {
                $custom_option              = explode('~*', $sub_array[0]);
                $params['custom_option_id'] = isset($custom_option[1]) ? $custom_option[1] : '';
                $custom_option_details      = $ObjCart->getCustomOptionDeatils($params);
                if (isset($sub_array[2]) && $sub_array[2] != '')
                    $custom_option_variant = explode('~*', $sub_array[2]);
                if (isset($custom_option_variant[1]) && $custom_option_variant[1] > 0) {
                    $params['custom_option_variant_id'] = $custom_option_variant[1];
                    $custom_option_variant_details      = $ObjCart->getCustomOptionVariantDeatils($params);
					if(empty($custom_option_variant_details) || $custom_option_variant_details['status']!='A') {
						$optionInactive = 'Yes';
					}
                }
                foreach ($sub_array as $key => $sub_item) {
                    $custom_option_array = explode('~*', $sub_item);
                    if ($custom_option_array[0] == 'customOptionID')
                        $custom_option_string .= '->customOptionID~*' . $custom_option_array[1];
                    if ($custom_option_array[0] == 'customOptionName')
                        $custom_option_string .= '~:customOptionName~*' . $custom_option_details['customOptionName'];
                    if ($custom_option_array[0] == 'customOptionVariantID')
                        $custom_option_string .= '~:customOptionVariantID~*' . $custom_option_array[1];
                    if ($custom_option_array[0] == 'variantValueText') {
                        $custom_option_string .= '~:variantValueText~*' . $custom_option_array[1];
                        $variantValueText = $custom_option_array[1];
                    }
                    if(($custom_option_details['customOptionName']=='Color' || $custom_option_details['customOptionName']=='Upholstery' || $custom_option_details['customOptionName']=='Stripe' || $custom_option_details['customOptionName']=='Roof') && $custom_option_array[0] == 'customOptionVariantID') {
                        $custComb = ($custComb=='') ? $custom_option_array[1] : $custComb."_".$custom_option_array[1];
                    }
                    if ($custom_option_array[0] == 'inputType')
                        $custom_option_string .= '~:inputType~*' . $custom_option_array[1];
                    if ($custom_option_array[0] == 'priceDiff') {
                        if ($custom_option_variant[1] > 0) {
                            $custom_option_string .= '~:priceDiff~*' . $custom_option_variant_details['priceDiff'];
                        } else {
                            $custom_option_string .= '~:priceDiff~*' . $custom_option_details['priceDiff'];
                        }
                    }
                    if ($custom_option_array[0] == 'priceDiffType') {
                        if ($custom_option_variant[1] > 0) {
                            $custom_option_string .= '~:priceDiffType~*' . $custom_option_variant_details['priceDiffType'];
                        } else {
                            $custom_option_string .= '~:priceDiffType~*' . $custom_option_details['priceDiffType'];
                        }
                    }
                    if ($custom_option_array[0] == 'variantValue') {
                        if ($custom_option_variant[1] > 0) {
                            if ($custom_option_variant_details['priceDiffType'] == 'I') {
                                $str = $custom_option_variant_details['value'] . ' ( + ' . $this->ObjView->getFormattedCurrency($custom_option_variant_details['priceDiff']) . ')';
                                $custom_option_string .= '~:variantValue~*' . $str;
                                $price_change = (isset($price_change) ? $price_change : 0) + $custom_option_variant_details['priceDiff'];
                            } else if ($custom_option_variant_details['priceDiffType'] == 'D') {
                                $str = $custom_option_variant_details['value'] . ' ( - ' . $this->ObjView->getFormattedCurrency($custom_option_variant_details['priceDiff']) . ')';
                                $custom_option_string .= '~:variantValue~*' . $str;
                                $price_change = (isset($price_change) ? $price_change : 0) - $custom_option_variant_details['priceDiff'];
                            } else {
                                $custom_option_string .= '~:variantValue~*' . $custom_option_variant_details['value'];
                            }
                        } else {
                            if ($custom_option_details['priceDiffType'] == 'I') {
                                $str = $variantValueText . ' ( + ' . $this->ObjView->getFormattedCurrency($custom_option_details['priceDiff']) . ')';
                                $custom_option_string .= '~:variantValue~*' . $str;
                                $price_change = (isset($price_change) ? $price_change : 0) + $custom_option_details['priceDiff'];
                            } else if ($custom_option_details['priceDiffType'] == 'D') {
                                $str = $variantValueText . ' ( - ' . $this->ObjView->getFormattedCurrency($custom_option_details['priceDiff']) . ')';
                                $custom_option_string .= '~:variantValue~*' . $str;
                                $price_change = (isset($price_change) ? $price_change : 0) - $custom_option_details['priceDiff'];
                            } else {
                                $custom_option_string .= '~:variantValue~*' . $variantValueText;
                            }
                        }
                    }
                }
            }
        }
        $return['custom_option_string'] = $custom_option_string;
        $return['price_change']         = isset($price_change) ? $price_change : 0;
        $return['custComb']             = $custComb;
		$return['optionInactive'] = $optionInactive;
        return $return;
    }
    //Function for getting combintaion details from server as per the user selection on add to cart
    //@usage add to cart
    private function getCombinationStringAndPriceDiff($combination_values = array(), $params = array()) {
        $ObjCart             = new CartModel();
        $combination_string  = '';
		$optionInactive = '';
        $combination_deatils = $ObjCart->getCombinationDeatils($params);
        if ($combination_deatils['combinationPriceDiffType'] == 'I') {
            $combination_string .= '->combinationSKU~*' . $combination_deatils['combinationSKU'] . ' ( +' . $this->ObjView->getFormattedCurrency($combination_deatils['combinationPrice']) . ' )';
            $price_change = (isset($price_change) ? $price_change + $combination_deatils['combinationPrice'] : $combination_deatils['combinationPrice']);
        } else if ($combination_deatils['combinationPriceDiffType'] == 'D') {
            $combination_string .= '->combinationSKU~*' . $combination_deatils['combinationSKU'] . ' ( -' . $this->ObjView->getFormattedCurrency($combination_deatils['combinationPrice']) . ' )';
            $price_change = (isset($price_change) ? $price_change - $combination_deatils['combinationPrice'] : $combination_deatils['combinationPrice']);
        } else {
            $combination_string .= '->combinationSKU~*' . $combination_deatils['combinationSKU'];
        }
        $combination_string .= '->combinationPrice~*' . $combination_deatils['combinationPrice'];
        $combination_string .= '->combinationPriceDiffType~*' . $combination_deatils['combinationPriceDiffType'];
        unset($combination_values[0]);
        unset($combination_values[1]);
        unset($combination_values[2]);
        foreach ($combination_values as $item) {
            $sub_array = explode('~:', $item);
            if (count($sub_array) > 0) {
                $custom_option              = explode('~*', $sub_array[0]);
                $params['custom_option_id'] = $custom_option[1];
                $custom_option_details      = $ObjCart->getCustomOptionDeatils($params);
                $custom_option_variant      = explode('~*', $sub_array[2]);
                if ($custom_option_variant[1] > 0) {
                    $params['custom_option_variant_id'] = $custom_option_variant[1];
                    $custom_option_variant_details      = $ObjCart->getCustomOptionVariantDeatils($params);
					if(empty($custom_option_variant_details) || $custom_option_variant_details['status']!='A') {
						$optionInactive = 'Yes';
					}
                }
				
                foreach ($sub_array as $key => $sub_item) {
                    $custom_option_array = explode('~*', $sub_item);
                    if ($custom_option_array[0] == 'customOptionID')
                        $combination_string .= '->customOptionID~*' . $custom_option_array[1];
                    if ($custom_option_array[0] == 'customOptionName')
                        $combination_string .= '~:customOptionName~*' . $custom_option_details['customOptionName'];
                    if ($custom_option_array[0] == 'customOptionVariantID')
                        $combination_string .= '~:customOptionVariantID~*' . $custom_option_array[1];
                    if ($custom_option_array[0] == 'inputType')
                        $combination_string .= '~:inputType~*' . $custom_option_array[1];
                    if ($custom_option_array[0] == 'variantValue')
                        $combination_string .= '~:variantValue~*' . $custom_option_variant_details['value'];
                }
            }
        }
        $return['combination_string'] = $combination_string;
		$return['optionInactive'] = $optionInactive;
        $return['price_change']       = isset($price_change) ? $price_change : 0;
        return $return;
    }
    //Add to cart action
    //@usage from quick view and product details page
    //@usage for product promotions with free products
    public function ajaxAddItemAction($post = array()) {
        $ObjCart                            = new CartModel();
        $ObjProductList                     = new ProductListModel();
		$ObjCustomOption    				= new CustomOptionModel();
        $cartID                             = $this->ObjSession->getSession("CARTID");
        $ObjProduct                         = new ProductModel();
        $post_data                          = (count($post) > 0 ? $post : $_POST);
        $bundleProd                         = isset($post_data['bundleProduct']) ? $post_data['bundleProduct'] : "";
        $params['cart_id']                  = $this->decodeString($this->ObjSession->getSession("CARTID"));
		//print_r($post_data);
        /*if($post_data['freeProduct']!='' && $params['cart_id']>0) {                 
            $deleteItemFromCart             = $ObjCart->deleteItemFromCart($params['cart_id'], 0, '', '','','Yes',$post_data['productID'],$post_data['freeBaseProductID']);
        }     */ 
        $post_data['userID']                = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $post_data['languageIDs']           = $this->ObjView->languageIDs;
		$showAllProducts = $this->getSettingValue('product_cart_settings', 'outof_stock_products_display');
        $result                             = $itemDetails = $ObjCart->getCartProductDetails($post_data['productID'], $post_data['productOptionID'],$post_data['languageIDs'],0,0,$showAllProducts);
        $inactiveProduct = 0;
		if($result['productStatus']=='Inactive') {
			$inactiveProduct = 1;
		} 
		/*if(empty($result)) {
			 $strError = array();
			 $strError['isInactive'] = 'Yes';
			 $strError['isError'] 	 = 'Yes';
			 $inactiveProduct = 1;
			 echo json_encode($strError);
			 exit;
		}*/
		$post_data['productImage']          = $result['productImage'];
        $post_data['productOptionName']     = $result['productOptionName'];
        $post_data['productTitle']          = $result['productTitle'];
        $post_data['productCommissionRate'] = $result['productCommissionRate'];        
        $post_data['businessKey']           = $result['businessKey'];   
        $post_data['productServiceFee']     = (isset($post_data['freeProduct']) && $post_data['freeProduct'] == 'Yes') ? 0 : $result['productServiceFee'];
        //dispatch		
        $productDispatchString              = $ObjProduct->getDispatchTimeByID($result['productDispatchTime']);
        $productDispatchPeriod              = explode("-", $productDispatchString);
        $post_data['productDispatchTime']   = isset($productDispatchPeriod[1]) ? $productDispatchPeriod[1] : '';
        //Tier price starts
        $combination_hash                   = isset($post_data['combinationHash']) ?$post_data['combinationHash']:'';
        $product_option_id                  = $post_data['productOptionID'];
        $user_group_id                      = (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID;
        $current_quantity                   = $post_data['quantity'];
        
        $params['combination_hash']         = $combination_hash;
        $params['product_option_id']        = $product_option_id;
        $params['user_group_id']            = $user_group_id;
        $params['current_quantity']         = $current_quantity;
        $params['language_id']              = $this->ObjView->languageIDs['Current'];
        if(empty($post_data['currbusinessid'])) {
            $post_data['currbusinessid'] = $result['businessID'];
        }
        $params['curr_business_id']         = $post_data['currbusinessid'];
        $brandID                            = $this->ObjCommon->brandID;//$post_data['brandID'];
       
        $result                             = $ObjCart->getCartItemPrice($params);
        $tier_price                         = $ObjCart->getVariantTiePrice($params);
        $customOptionValues                 = isset($post_data['customOptionValues']) ?$post_data['customOptionValues']:'';		
        $extra_string                       = substr(trim($this->decodeSplChar($customOptionValues)), 2);
        $custom_option_values               = explode('->', $extra_string);
        
        $price_change                       = 0;
        $vsbID                              = 0;
        if (count($custom_option_values) > 0) {
            
            $custom_option_details = $this->getCustomOptionStringAndPriceDiff($custom_option_values, $params);
            $custom_option_string  = $custom_option_details['custom_option_string'];
            $price_change += $custom_option_details['price_change'];            
            if($custom_option_details['custComb']!='') {
                //get vsbID
                $vsbID = $ObjProduct->getVSBFromComb($post_data['productID'],$custom_option_details['custComb']);
            }
        }
		$strcombinationValues                 = isset($post_data['strcombinationValues']) ?$post_data['strcombinationValues']:'';
        $extra_string       = substr(trim($this->decodeSplChar($strcombinationValues)), 2);
        $combination_values = explode('->', $extra_string);
        if (count($combination_values) > 0) {
            $combination_details = $this->getCombinationStringAndPriceDiff($combination_values, $params);
            $combination_string  = $combination_details['combination_string'];
            $price_change += $combination_details['price_change'];
        }
        $base_price                        = $result['actualPrice'];

        if($bundleProd=="Yes"){
            $post_data['actualPrice']          = $base_price;
            $offer_price                       = $result['productOptionProductPrice'];
        }else{
            $extra_price                       = $price_change;
            $post_data['actualPrice']          = $base_price + $extra_price;
            if($result['isProductDeal']!="Yes") {
                $offer_price                   = $result['offerPrice'];
            }
            else {
                $offer_price                   = $result['dealPrice'];   
                //$offer_price                   = $result['productOptionProductPrice'] - $result['productOptionProductPrice']*$result['dealDiscount']/100;            
            }
        }
       
        $post_data['offerPrice']           = $offer_price;
        $post_data['tierPrice']            = $tier_price;
        $post_data['strcombinationValues'] = $combination_string;
        $post_data['customOptionValues']   = $custom_option_string;
        $post_data['measurementLength']    = $itemDetails['measurementLength'];
        $post_data['measurementWeight']    = $itemDetails['measurementWeight'];
        $post_data['packageWeight']        = $itemDetails['packageWeight'];
        $post_data['packageLength']        = $itemDetails['packageLength'];
        $post_data['packageWidth']         = $itemDetails['packageWidth'];
        $post_data['vsbID']                = $vsbID;
        $post_data['packageHeight']        = $itemDetails['packageHeight'];
        $offer_price                       = ($tier_price > 0 && $tier_price < $offer_price) ? $tier_price : $offer_price;
        
        $post_data['price']                = $offer_price + $extra_price;
        $post_data['price']                = (isset($post_data['freeProduct']) && $post_data['freeProduct'] == 'Yes') ? 0 : $post_data['price'];
        $post_data['userCurrencyID']            = $this->ObjCommon->_currentCurrencyID;
        $post_data['userCurrencyExcRate']            = $this->ObjCommon->_currentCurrencyValue;
        //echo "<pre>"; print_r($post_data); exit;
//Tier price ends
        //If the user cliking on add to cart at first time
        if ($cartID == '') {
            $cartID = $ObjCart->createCart($post_data);	
            if ($cartID > 0) {
                $this->ObjSession->setSession("CARTID", $this->encodeString($cartID));
            }
        } else //If user have alredy added some items to cart
            {
            
            $cartID        = $this->decodeString($cartID);
            $addItemToCart = $ObjCart->addITemToCart($post_data, $cartID); 
        }
	$result             = $ObjCart->getCartDetails($cartID, 0);
        /* =======================================================================*/
        $ObjProductList->updateProductPopularity($post_data['productID'], 'add');
        /* =======================================================================*/
        $resCart['cartID']                   = $result['cartID'];
        $resCart['productType']              = $result['productType'];
        $resCart['orderSubtotal']            = $result['orderSubtotal'];
        $resCart['promoID']                  = $result['promoID'];
        $resCart['orderPromoCode']           = $result['orderPromoCode'];
        $resCart['orderQty']                 = $result['orderQty'];
        $resCart['orderTotalAmount']         = $result['orderTotalAmount'];
        $resCart['proceedCheckout']          = $result['proceedCheckout'];
        $resCart['currencyID']               = $result['currencyID'];
        $resCart['extra']                    = $result['extra'];
        $resCart['orderCharityID']           = $result['orderCharityID'];
        $resCart['shippingAmount']           = $result['shippingAmount'];
        $resCart['orderTaxAmount']           = $result['orderTaxAmount'];
        $resCart['userFirstName']            = $result['userFirstName']; 
        $resCart['userLastName']             = $result['userLastName'];
        $resCart['userEmail']                = $result['userEmail'];
        $resCart['brandID']                  = $result['brandID'];
        $resCart['items']                    = $result['items'];
        $resCart['orderOtherServiceCharge']  = $result['orderOtherServiceCharge'];
        $resCart['orderPromoDiscountAmount'] = $result['orderPromoDiscountAmount'];
        $resCart['orderUserCreditAmount']    = $result['orderUserCreditAmount'];
        $resCart['selectedProduct']          = $post_data['productTitle'];
		if($inactiveProduct>0) {
			// $strError = array();
			 $resCart['isInactive'] = 'Yes';
			 $resCart['isError'] 	 = 'Yes';
			
		}
        if (count($resCart['items']) > 0) {
            foreach ($resCart['items'] as $key => $items) {
                $str                                   = $items['itemDetails'];
             //   $str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
               // $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
            }
        }
        if (($post_data['freeProduct'] != 'Yes' && $post_data['bundleProduct'] != 'Yes') || ($post_data['freeProduct'] == 'Yes' && $post_data['freeBaseProductID'])) {
            echo json_encode($resCart);
        }
    }
    //Update quantity
    //@clicking on add to cart button which item is alredy added to the cart
    //While updating quantity 1) will remove the existing item from the cart and then add the new item with the updated quantity
//    public function ajaxUpdateQuantityAction() {
//        $ObjCart                            = new CartModel();
//        $ObjProduct                         = new ProductModel();
//        $cartID                             = $this->ObjSession->getSession("CARTID");
//        $post_data                          = $_POST;
//        $post_data['userID']                = $this->ObjSession->getSession("REGISTERED_USER_ID");
//        $cartID                             = $this->decodeString($cartID);
//        $post_data['languageIDs']           = $this->ObjView->languageIDs;
//        $post_data['productID']             =(int)$post_data['productID'];
//        $post_data['productOptionID']       =(int)$post_data['productOptionID'];
//        $bundleProd                         = isset($post_data['bundleProduct']) ? $post_data['bundleProduct'] : "";
//
//        $result                             = $ObjCart->getCartProductDetails($post_data['productID'], $post_data['productOptionID'],$post_data['languageIDs']);
//	
//        $post_data['productImage']          = $result['productImage'];        
//        $post_data['productOptionName']     = $result['productOptionName'];
//        $post_data['productTitle']          = $result['productTitle'];        
//        $post_data['businessKey']           = $result['businessKey'];
//
//        $post_data['productCommissionRate'] = $result['productCommissionRate'];
//        $post_data['productServiceFee']     = (isset($post_data['freeProduct']) && $post_data['freeProduct'] == 'Yes') ? 0 : $result['productServiceFee'];       
//        
//	$post_data['optionsHash']	    = isset($post_data['optionsHash'])? $post_data['optionsHash']:'';
//        if(!empty($post_data['existItemID']) && $post_data['existItemID']>0 && !empty($post_data['bundleProduct']) && $post_data['bundleProduct']=='Yes') {
//            //echo "kkkk".$post_data['existItemID'];exit;
//            $deleteItemFromCart                 = $ObjCart->deleteItemFromCart($cartID, $post_data['existItemID'], $post_data['productOptionID'], $post_data['optionsHash'],'',$post_data['freeProduct'],'',$post_data['freeBaseProductID'],'',$post_data['currbusinessid']);        
//        } else {
//            //echo "ttttttttttttt".$post_data['existItemID'];exit;
//        $deleteItemFromCart                 = $ObjCart->deleteItemFromCart($cartID, 0, $post_data['productOptionID'], $post_data['optionsHash'],'',$post_data['freeProduct'],'',$post_data['freeBaseProductID'],'',$post_data['currbusinessid']);        
//        }
//        $productDispatchString              = $ObjProduct->getDispatchTimeByID($result['productDispatchTime']);
//        $productDispatchPeriod              = explode("-", $productDispatchString);
//        $post_data['productDispatchTime']   = isset($productDispatchPeriod[1]) ? $productDispatchPeriod[1] : '';
//        //Tier price starts
//        $combination_hash                   = isset($post_data['combinationHash'])?$post_data['combinationHash']:'';
//        $product_option_id                  = $post_data['productOptionID'];
//        $user_group_id                      = (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID;
//        $current_quantity                   = (int)$post_data['quantity'];
//        $params['cart_id']                  = $cartID;
//        $params['combination_hash']         = $combination_hash;
//        $params['product_option_id']        = $product_option_id;
//        $params['user_group_id']            = $user_group_id;
//        $params['current_quantity']         = $current_quantity;
//        $params['language_id']              = $this->ObjView->languageIDs['Current'];
//        $params['curr_business_id']         = $post_data['currbusinessid'];
//        $post_data['measurementLength']     = $itemDetails['measurementLength'];
//        $post_data['measurementWeight']     = $itemDetails['measurementWeight'];
//        $post_data['packageWeight']         = $itemDetails['packageWeight'];
//        $post_data['packageLength']         = $itemDetails['packageLength'];
//        $post_data['packageWidth']          = $itemDetails['packageWidth'];
//        $post_data['packageHeight']         = $itemDetails['packageHeight'];
//        $result                             = $ObjCart->getCartItemPrice($params);
//        $tier_price                         = $ObjCart->getVariantTiePrice($params);
//	$post_data['customOptionValues']    = isset($post_data['customOptionValues'])?$post_data['customOptionValues']:'';
//        $extra_string                       = substr(trim($this->decodeSplChar($post_data['customOptionValues'])), 2);
//        $custom_option_values               = explode('->', $extra_string);
//        $price_change                       = 0;
//        if (count($custom_option_values) > 0) {
//            $custom_option_details = $this->getCustomOptionStringAndPriceDiff($custom_option_values, $params);
//            $custom_option_string  = $custom_option_details['custom_option_string'];
//            $price_change += $custom_option_details['price_change'];
//        }
//	$post_data['strcombinationValues']    = isset($post_data['strcombinationValues'])?$post_data['strcombinationValues']:'';
//        $extra_string       = substr(trim($this->decodeSplChar($post_data['strcombinationValues'])), 2);
//        $combination_values = explode('->', $extra_string);
//        if (count($combination_values) > 0) {
//            $combination_details = $this->getCombinationStringAndPriceDiff($combination_values, $params);
//            $combination_string  = $combination_details['combination_string'];
//            $price_change += $combination_details['price_change'];
//        }
//        if($bundleProd=="Yes"){
//            $base_price                          = $result['actualPrice'];
//            $offer_price                         = $result['productOptionProductPrice'];
//        }else{
//            $base_price                          = $result['actualPrice'];
//            $offer_price                         = $result['offerPrice'];
//        }
//        $extra_price                         = $price_change;
//        $post_data['actualPrice']            = $base_price + $extra_price;
//        $post_data['offerPrice']             = $offer_price;
//        $post_data['tierPrice']              = $tier_price;
//        $post_data['strcombinationValues']   = $combination_string;
//        $post_data['customOptionValues']     = $custom_option_string;
//        $offer_price                         = ($tier_price > 0 && $tier_price < $offer_price) ? $tier_price : $offer_price;
//        $post_data['price']                  = $offer_price + $extra_price;
//        $post_data['price']                  = (isset($post_data['freeProduct']) && $post_data['freeProduct'] == 'Yes') ? 0 : $post_data['price'];
//        //Tier price ends
//        $addItemToCart                       = $ObjCart->addITemToCart($post_data, $cartID);
//        //Reseting tier price and shipping charge calculation with the currently added product quantity
//        $reset_tier_price                    = $ObjCart->resetCartItemsTierPrice($cartID, $this->ObjCommon->REGISTERED_USER_GROUP_ID);
//        $resShippingCalc                     = $ObjCart->calculateShippingRate($cartID, $this->_shippingCalculationParam);
//        $resTaxUpdate                        = $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
//        $resResetCartTotals                  = $ObjCart->resetCartTotals($cartID);
//        $result                              = $ObjCart->getCartDetails($cartID, 0);
//        $resCart['cartID']                   = $result['cartID'];
//        $resCart['productType']              = $result['productType'];
//        $resCart['orderSubtotal']            = $result['orderSubtotal'];
//        $resCart['promoID']                  = $result['promoID'];
//        $resCart['orderPromoCode']           = $result['orderPromoCode'];
//        $resCart['orderQty']                 = $result['orderQty'];
//        $resCart['orderTotalAmount']         = $result['orderTotalAmount'];
//        $resCart['proceedCheckout']          = $result['proceedCheckout'];
//        $resCart['currencyID']               = $result['currencyID'];
//        $resCart['extra']                    = $result['extra'];
//        $resCart['orderCharityID']           = $result['orderCharityID'];
//        $resCart['shippingAmount']           = $result['shippingAmount'];
//        $resCart['orderTaxAmount']           = $result['orderTaxAmount'];
//        $resCart['userFirstName']            = $result['userFirstName'];
//        $resCart['userLastName']             = $result['userLastName'];
//        $resCart['userEmail']                = $result['userEmail'];
//        $resCart['items']                    = $result['items'];
//        $resCart['orderOtherServiceCharge']  = $result['orderOtherServiceCharge'];
//        $resCart['orderPromoDiscountAmount'] = $result['orderPromoDiscountAmount'];
//        $resCart['orderUserCreditAmount']    = $result['orderUserCreditAmount'];
//        $resCart['selectedProduct']          = $post_data['productTitle'];
//        if (count($resCart['items']) > 0) {
//            foreach ($resCart['items'] as $key => $items) {
//                $str                                   = $items['itemDetails'];
//                //$str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
//               // $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
//            }
//        }
//        $post_data['freeProduct'] = isset($post_data['freeProduct']) ? $post_data['freeProduct'] : '';    
//		$post_data['bundleProduct'] = isset($post_data['bundleProduct']) ? $post_data['bundleProduct'] : '';
//        if (($post_data['freeProduct'] != 'Yes' && $post_data['bundleProduct'] != 'Yes') || ($post_data['freeProduct'] == 'Yes' && $post_data['freeBaseProductID']>0)) {
//            echo json_encode($resCart);
//        }
//    }
    //Deletes item from cart
    //@usage quick view cart popup
    public function ajaxDeleteItemAction() {
        $ObjCart        = new CartModel();
        $ObjProductList = new ProductListModel();
        if (!isset($_POST['cartID']) || !isset($_POST['cartItemID']))
            exit;
        $paramsArray = array(
            'tableName' => 'cart_items',
            'fieldName' => 'productID',
            'conditionField' => 'cartItemID',
            'condition' => '=',
            'conditionValue' => (isset($_POST['cartItemID']) ? (int)$_POST['cartItemID'] : 0),
            'conditionFieldType' => 'int'
        );
        $resProduct  = $ObjCart->getFieldValue($paramsArray);
        $productID   = isset($resProduct['productID']) ? $resProduct['productID'] : 0;
        /* =======================================================================*/
        $ObjProductList->updateProductPopularity($productID, 'delete');
        /* =======================================================================*/
        $_POST['cartID']                     = isset($_POST['cartID']) ? (int)$_POST['cartID'] : 0;
        $_POST['cartItemID']                 = isset($_POST['cartItemID']) ? (int)$_POST['cartItemID'] : 0;
        $deleteItemFromCart                  = $ObjCart->deleteItemFromCart($_POST['cartID'], $_POST['cartItemID'], 0, '', 'popup');
        $reset_tier_price                    = $ObjCart->resetCartItemsTierPrice($_POST['cartID'], $this->ObjCommon->REGISTERED_USER_GROUP_ID);
        $resShippingCalc                     = $ObjCart->calculateShippingRate($_POST['cartID'], $this->_shippingCalculationParam);
        $promoData                           = $this->setPromoCodeDiscount();
        $resTaxUpdate                        = $ObjCart->updateCartItemsTax($_POST['cartID'], $this->_taxCalculationParam);
        $resResetCartTotals                  = $ObjCart->resetCartTotals($_POST['cartID']);
        $result                              = $ObjCart->getCartDetails($_POST['cartID'], 0);
        $resCart['cartID']                   = $result['cartID'];
        $resCart['productType']              = $result['productType'];
        $resCart['orderSubtotal']            = $result['orderSubtotal'];
        $resCart['promoID']                  = $result['promoID'];
        $resCart['orderPromoCode']           = $result['orderPromoCode'];
        $resCart['orderQty']                 = $result['orderQty'];
        $resCart['orderTotalAmount']         = $result['orderTotalAmount'];
        $resCart['proceedCheckout']          = $result['proceedCheckout'];
        $resCart['currencyID']               = $result['currencyID'];
        $resCart['extra']                    = $result['extra'];
        $resCart['orderCharityID']           = $result['orderCharityID'];
        $resCart['shippingAmount']           = $result['shippingAmount'];
        $resCart['orderTaxAmount']           = $result['orderTaxAmount'];
        $resCart['userFirstName']            = $result['userFirstName'];
        $resCart['userLastName']             = $result['userLastName'];
        $resCart['userEmail']                = $result['userEmail'];
        $resCart['items']                    = $result['items'];
        $resCart['orderOtherServiceCharge']  = $result['orderOtherServiceCharge'];
        $resCart['orderPromoDiscountAmount'] = isset($result['orderPromoDiscountAmount']) ? $result['orderPromoDiscountAmount'] : '';
        $resCart['orderUserCreditAmount']    = isset($result['orderUserCreditAmount']) ? $result['orderUserCreditAmount'] : '';
        if (count($resCart['items']) > 0) {
            foreach ($resCart['items'] as $key => $items) {
                $str                                   = $items['itemDetails'];
                //$str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
               // $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
            }
        }
        echo json_encode($resCart);
    }
    //Update cart from cart page
    //@Update quantity
    //@Delete item
    //@Apply promo
    //@Remove promo
    public function ajaxUpdateCartAction() {
        $ObjCart    = new CartModel();
        $ObjProduct = new ProductModel();
        $languageIDs= $this->ObjView->languageIDs;
        $mode    = $_POST['mode'];
        $cartID  = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $userID  = $this->ObjSession->getSession("REGISTERED_USER_ID");
        switch ($mode) {
            case 'update_quantity':
                //$ObjCart->setRedeemPointDiscount(array(),$cartID,'remove');
                $cartItemID = (int)$_POST['cartItemID'];
                $quantity   = (int)$_POST['quantity'];
                $result     = $ObjCart->getCartItemDetails($cartItemID);
                if (isset($result['cartItemID']) && $result['cartItemID'] < 1) {
                    $resCartItemDetails['isError'] = 'Yes';
                    $resCartItemDetails['error']   = $this->getLanguageValue("lblCartStockNotAvailable");
                    echo json_encode($resCartItemDetails);
                    return true;
                }   
                if($result['freeBaseProductID']<=0 && $quantity<$result['orderItemQuantity']) {
                    //check free products exists added in cart
                    $totFreeCnt           = $ObjCart->getTotalFreeCntByID($cartID,$result['productID']);                    
                    if($totFreeCnt>0 && $totFreeCnt>$quantity) {
                        //delete all gifts
                        $resDeleteCartItem  = $ObjCart->deleteCartItemFreeGif($cartID,$result['productID']);                        
                        /*$getAddedFreeProducts = $ObjCart->getCartFreeProductsByID($cartID,$result['productID']);
                        if(count($getAddedFreeProducts)==1) {
                            //update quantity
                        } else {
                            
                        }*/
                    }
                    
                }
                $productCommissionRate                           = $result['productCommissionRate'];
                $resCartItemDetails['cartItemID']                = $result['cartItemID'];
                $resCartItemDetails['isProductDeal']             = $result['isProductDeal'];
                $resCartItemDetails['dealMaxBuyLimit']           = $result['dealMaxBuyLimit'];
                $resCartItemDetails['cartID']                    = $result['cartID'];
                $resCartItemDetails['productID']                 = $result['productID'];
                $resCartItemDetails['productOptionID']           = $result['productOptionID'];
                $resCartItemDetails['orderItemPrice']            = $result['orderItemPrice'];
                $resCartItemDetails['orderItemQuantity']         = $result['orderItemQuantity'];
                $resCartItemDetails['orderItemSubtotal']         = $result['orderItemSubtotal'];
                $resCartItemDetails['orderGiveAsGift']           = $result['orderGiveAsGift'];
                $resCartItemDetails['certificateName']           = isset($result['certificateName']) ? $result['certificateName'] : '';
                $resCartItemDetails['certificateEmail']          = isset($result['certificateEmail']) ? $result['certificateEmail'] : '';
                $resCartItemDetails['redeemSlotID']              = $result['redeemSlotID'];
                $resCartItemDetails['itemDetails']               = $result['itemDetails'];
                $resCartItemDetails['addedTime']                 = $result['addedTime'];
                $resCartItemDetails['productMinBuyLimit']        = $result['productMinBuyLimit'];
                $resCartItemDetails['productMaxBuyLimit']        = $result['productMaxBuyLimit'];
                $resCartItemDetails['productMaxGiftBuy']         = $result['productMaxGiftBuy'];
                $resCartItemDetails['productTypeKey']            = $result['productTypeKey'];
                $resCartItemDetails['productServiceFee']         = $result['productServiceFee'];
                $resCartItemDetails['productOptionQuantity']     = $result['productOptionQuantity'];
                $resCartItemDetails['productQuantityUnlimited']  = $result['productQuantityUnlimited'];
                $resCartItemDetails['productOptionProductPrice'] = $result['productOptionProductPrice'];
                $resCartItemDetails['userID']                    = $result['userID'];
                $resCartItemDetails['selfPurchase']              = (isset($result['selfPurchase']) ? $result['selfPurchase'] : 0);
                $resCartItemDetails['giftPurchase']              = isset($result['giftPurchase']) ? $result['giftPurchase'] : '';
                $resCartItemDetails['currentCartGiftPurchase']   = isset($result['currentCartGiftPurchase']) ? $result['currentCartGiftPurchase'] : '';
                $resCartItemDetails['currentCartSelfPurchase']   = isset($result['currentCartSelfPurchase']) ? $result['currentCartSelfPurchase'] : '';
                $str                                             = $resCartItemDetails['itemDetails'];
               // $str                                             = str_replace('orderCommissionAmount', '---------------------', $str);
               // $resCartItemDetails['itemDetails']               = str_replace('productCommissionRate', '------------------', $str);
                $serializedData                                  = unserialize($resCartItemDetails['itemDetails']);
                //If updating quantity is not avilable in stock
                if ($resCartItemDetails['productQuantityUnlimited'] < 1 && $resCartItemDetails['productOptionQuantity'] < ($quantity + $resCartItemDetails['currentCartSelfPurchase'])) {
                    $resCartItemDetails['isError'] = 'Yes';
                    $resCartItemDetails['error']   = $this->getLanguageValue("lblCartStockNotAvailable");
                    echo json_encode($resCartItemDetails);
                    return true;
                }
                //If product min buy limit is grater than teh updating quantity
                if ($quantity < $resCartItemDetails['productMinBuyLimit']) {
                    $resCartItemDetails['isError'] = 'Yes';
                    $resCartItemDetails['error']   = $this->getLanguageValue("lblCartMinBuyLimitIs") . ' ' . $resCartItemDetails['productMinBuyLimit'] . ' ' . $this->getLanguageValue("lblCartFor") . " " . substr($serializedData['productOptionName'], 0, 50) . " " . $this->getLanguageValue("lblCartPleaseUpdateQuantity");
                    echo json_encode($resCartItemDetails);
                    return true;
                }
				
                //echo $resCartItemDetails['isProductDeal']." ".$quantity." ".$resCartItemDetails['dealMaxBuyLimit'];exit;
				//If product min buy limit is grater than teh updating quantity
                if (isset($resCartItemDetails['isProductDeal']) &&  $resCartItemDetails['isProductDeal']=='Yes') {
                    $balanceQty = $resCartItemDetails['dealMaxBuyLimit'];
                    if($userID>0) {
                        $balanceQty = $resCartItemDetails['dealMaxBuyLimit'] - $resCartItemDetails['selfPurchase'];
                    }
                    if($quantity > $resCartItemDetails['dealMaxBuyLimit'] && $resCartItemDetails['dealMaxBuyLimit']>0) {
                        $resCartItemDetails['isError'] = 'Yes';
                        $resCartItemDetails['error']   = $this->getLanguageValue("lblCartMaxBuyLimitIs") . ' ' . $resCartItemDetails['dealMaxBuyLimit'] . ' ' . $this->getLanguageValue("lblCartFor") . " " . substr($serializedData['productOptionName'], 0, 50) . " " . $this->getLanguageValue("lblCartPleaseUpdateQuantity");
                        echo json_encode($resCartItemDetails);                        
                        return true;
                    } 
                    if($userID>0 && $resCartItemDetails['selfPurchase']>0 && $quantity > $balanceQty && $resCartItemDetails['dealMaxBuyLimit']>0) {
                        $resCartItemDetails['isError'] = 'Yes';                       
                        $resCartItemDetails['error']   = ($balanceQty<=0)?$this->getLanguageValue("lblCartYouHaveExceededLimit") .' '.$this->getLanguageValue("lblCartMaxBuyLimitIs") . ' ' .$resCartItemDetails['dealMaxBuyLimit'] . ' ' . $this->getLanguageValue("lblCartFor") . " " . substr($serializedData['productOptionName'], 0, 50):$this->getLanguageValue("lblCartMaxBuyLimitIs") . ' ' .$balanceQty . ' ' . $this->getLanguageValue("lblCartFor") . " " . substr($serializedData['productOptionName'], 0, 50);
                        echo json_encode($resCartItemDetails);                        
                        return true;
                    }
                   
                }
                //If updating quantity is grater than teh max buy limit
                if ($quantity > $resCartItemDetails['productMaxBuyLimit'] && $resCartItemDetails['productMaxBuyLimit'] > 0) {
                    $resCartItemDetails['isError'] = 'Yes';
                    $resCartItemDetails['error']   = $this->getLanguageValue("lblCartYouHaveExceededLimit");
                    echo json_encode($resCartItemDetails);
                    return true;
                }
                //If teh user alredy exceeded teh max buy limit
                if (($quantity + $resCartItemDetails['selfPurchase']) > $resCartItemDetails['productMaxBuyLimit'] && $resCartItemDetails['productMaxBuyLimit'] > 0) {
                    $resCartItemDetails['isError'] = 'Yes';
                    $resCartItemDetails['error']   = $this->getLanguageValue("lblCartYouHaveExceededLimitOwn");
                    echo json_encode($resCartItemDetails);
                    return true;
                }
                $returnData['isError']                     = 'No';
                $returnData['error']                       = $this->getLanguageValue("lblCartQuantityUpdatedSuccessfully");
                $currentAdminCommision                     = $resCartItemDetails['productOptionProductPrice'] * ($productCommissionRate / 100) * $quantity;
                $currentServiceFee                         = $resCartItemDetails['productServiceFee'] * $quantity;
                $currentSubTotalAmount                     = ($resCartItemDetails['orderItemPrice'] * $quantity);
                $currentTotalAmount                        = ($resCartItemDetails['orderItemPrice'] * $quantity) + $currentAdminCommision + $currentServiceFee;
                $serializedData['orderCommissionAmount']   = number_format($currentAdminCommision, 2, '.', '');
                $serializedData['orderOtherServiceCharge'] = number_format($currentServiceFee, 2, '.', '');
                $serializedData['orderItemQuantity']       = $quantity;
                $serializedData['orderItemSubtotal']       = number_format($currentSubTotalAmount, 2, '.', '');
                $serializedData['orderItemTotal']          = number_format($currentTotalAmount, 2, '.', '');
                $serializedData['unitPrice']               = number_format($resCartItemDetails['orderItemPrice'], 2, '.', '');
                $serializedData['productCommissionRate']   = number_format($productCommissionRate, 2, '.', '');
                $serializedData                            = $this->escape(serialize($serializedData), false, false);
				
                $postData['orderItemPrice']                = $resCartItemDetails['orderItemPrice'];
                $postData['orderItemQuantity']             = $quantity;
                $postData['orderItemSubtotal']             = $currentSubTotalAmount;
                $postData['itemDetails']                   = $serializedData;
                $postData['offerPrice']                    = $result['offerPrice'];
                $postData['tierPrice']                     = $result['tierPrice'];

                $dealDiscount				= 	isset($item['dealDiscount'])?$item['dealDiscount']:'';
                $isProductDeal				= 	isset($item['isProductDeal'])?$item['isProductDeal']:'';
                $productOptionRegularPrice		= 	isset($item['productOptionRegularPrice'])?$item['productOptionRegularPrice']:'';
                $postData['isProductDeal']		=	$isProductDeal;
                $postData['dealDiscount']		=	$dealDiscount;
                if($isProductDeal=='Yes'){
                        //$postData['offerPrice']         =       $productOptionRegularPrice*(100-$dealDiscount)/100;
                        $postData['offerPrice']         =       isset($item['dealPrice'])?$item['dealPrice']:'';
                }
                $resUpdateCartItem                         = $ObjCart->updateCartItem($resCartItemDetails['cartID'], $cartItemID, $postData);
                $reset_tier_price                          = $ObjCart->resetCartItemsTierPrice($cartID, $this->ObjCommon->REGISTERED_USER_GROUP_ID);
                $resShippingCalc                           = $ObjCart->calculateShippingRate($cartID, $this->_shippingCalculationParam);
                $resResetCartTotals                        = $ObjCart->resetCartTotals($cartID);
                $promoData                                 = $this->setPromoCodeDiscount();
                $resTaxUpdate                              = $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
                $resResetCartTotals                        = $ObjCart->resetCartTotals($cartID);
                $html                                      = $this->getCartHtml($cartID);
                $returnData['cartHtml']                    = $html;
                $cartleftsummaryhtml                       = $this->getCartPageSummary($cartID);
                $returnData['cartLeftBlockHtml']           = $cartleftsummaryhtml;
                $returnData['cartCharityPromoBlock']       = $this->setPromoCharityBlock();
                $returnData['promoData']                   = $promoData;
                $result                                    = $ObjCart->getCartDetails($cartID, 0);
                $resCart['cartID']                         = $result['cartID'];
                $resCart['productType']                    = $result['productType'];
                $resCart['orderSubtotal']                  = $result['orderSubtotal'];
                $resCart['promoID']                        = $result['promoID'];
                $resCart['orderPromoCode']                 = $result['orderPromoCode'];
                $resCart['orderQty']                       = $result['orderQty'];
                $resCart['orderTotalAmount']               = $result['orderTotalAmount'];
                $resCart['proceedCheckout']                = $result['proceedCheckout'];
                $resCart['currencyID']                     = $result['currencyID'];
                $resCart['extra']                          = $result['extra'];
                $resCart['orderCharityID']                 = $result['orderCharityID'];
                $resCart['shippingAmount']                 = $result['shippingAmount'];
                $resCart['orderTaxAmount']                 = $result['orderTaxAmount'];
                $resCart['userFirstName']                  = $result['userFirstName'];
                $resCart['userLastName']                   = $result['userLastName'];
                $resCart['userEmail']                      = $result['userEmail'];
                $resCart['items']                          = $result['items'];
                $resCart['orderOtherServiceCharge']        = $result['orderOtherServiceCharge'];
                $resCart['orderPromoDiscountAmount']       = $result['orderPromoDiscountAmount'];
                $resCart['orderUserCreditAmount']          = $result['orderUserCreditAmount'];
                if (count($resCart['items']) > 0) {
                    foreach ($resCart['items'] as $key => $items) {
                        $str                                   = $items['itemDetails'];
                       // $str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
                       // $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
                    }
                }
                $returnData['cartData'] = json_encode($resCart);
                echo json_encode($returnData);
                return true;
                break;
            case 'update_cartdata':             
                
                $result                                    = $ObjCart->getCartDetails($cartID, 0);
                $resCart['cartID']                         = $result['cartID'];
                $resCart['productType']                    = $result['productType'];
                $resCart['orderSubtotal']                  = $result['orderSubtotal'];
                $resCart['promoID']                        = $result['promoID'];
                $resCart['orderPromoCode']                 = $result['orderPromoCode'];
                $resCart['orderQty']                       = $result['orderQty'];
                $resCart['orderTotalAmount']               = $result['orderTotalAmount'];
                $resCart['proceedCheckout']                = $result['proceedCheckout'];
                $resCart['currencyID']                     = $result['currencyID'];
                $resCart['extra']                          = $result['extra'];
                $resCart['orderCharityID']                 = $result['orderCharityID'];
                $resCart['shippingAmount']                 = $result['shippingAmount'];
                $resCart['orderTaxAmount']                 = $result['orderTaxAmount'];
                $resCart['userFirstName']                  = $result['userFirstName'];
                $resCart['userLastName']                   = $result['userLastName'];
                $resCart['userEmail']                      = $result['userEmail'];
                $resCart['items']                          = $result['items'];
                $resCart['orderOtherServiceCharge']        = $result['orderOtherServiceCharge'];
                $resCart['orderPromoDiscountAmount']       = $result['orderPromoDiscountAmount'];
                $resCart['orderUserCreditAmount']          = $result['orderUserCreditAmount'];
                if (count($resCart['items']) > 0) {
                    foreach ($resCart['items'] as $key => $items) {
                        $str                                   = $items['itemDetails'];
                       // $str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
                       // $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
                    }
                }                
                echo json_encode($resCart);
                return true;
                break;
            case 'delete_item':
				//$ObjCart->setRedeemPointDiscount(array(),$cartID,'remove');
                $ObjProductList          = new ProductListModel();
                $cartItemID              = (int)$_POST['cartItemID'];
                $returnData['isError']   = 'No';
                $returnData['cartEmpty'] = 'No';
                $returnData['error']     = $this->getLanguageValue("lblCartItemRemovedSuccessfully");
                $paramsArray             = array(
                    'tableName' => 'cart_items',
                    'fieldName' => 'productID',
                    'conditionField' => 'cartItemID',
                    'condition' => '=',
                    'conditionValue' => $cartItemID,
                    'conditionFieldType' => 'int'
                );
                $resProduct              = $ObjCart->getFieldValue($paramsArray);
                $productID               = $resProduct['productID'];
                /* =======================================================================*/
                $ObjProductList->updateProductPopularity($productID, 'delete');
                /* =======================================================================*/  
                //delete free products if available with the product
                $resDeleteCartItem  = $ObjCart->deleteCartItem($cartID, $cartItemID,'delete',$productID);
                $reset_tier_price   = $ObjCart->resetCartItemsTierPrice($cartID, $this->ObjCommon->REGISTERED_USER_GROUP_ID);
                $resShippingCalc    = $ObjCart->calculateShippingRate($cartID, $this->_shippingCalculationParam);
                $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
                $promoData          = $this->setPromoCodeDiscount();
                $resTaxUpdate       = $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
                $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
                $html               = $this->getCartHtml($cartID);
                if ($html == 'empty') {
                    $returnData['cartEmpty'] = 'Yes';
                }
                $returnData['cartHtml']              = $html;
                $cartleftsummaryhtml                       = $this->getCartPageSummary($cartID);
                $returnData['cartLeftBlockHtml']           = $cartleftsummaryhtml;
                $returnData['cartCharityPromoBlock'] = $this->setPromoCharityBlock();
                $returnData['promoData']             = $promoData;
                $result                              = $ObjCart->getCartDetails($cartID, 0);
                $resCart['cartID']                   = $result['cartID'];
                $resCart['productType']              = $result['productType'];
                $resCart['orderSubtotal']            = $result['orderSubtotal'];
                $resCart['promoID']                  = $result['promoID'];
                $resCart['orderPromoCode']           = $result['orderPromoCode'];
                $resCart['orderQty']                 = $result['orderQty'];
                $resCart['orderTotalAmount']         = $result['orderTotalAmount'];
                $resCart['proceedCheckout']          = $result['proceedCheckout'];
                $resCart['currencyID']               = $result['currencyID'];
                $resCart['extra']                    = $result['extra'];
                $resCart['orderCharityID']           = $result['orderCharityID'];
                $resCart['shippingAmount']           = $result['shippingAmount'];
                $resCart['orderTaxAmount']           = $result['orderTaxAmount'];
                $resCart['userFirstName']            = $result['userFirstName'];
                $resCart['userLastName']             = $result['userLastName'];
                $resCart['userEmail']                = $result['userEmail'];
                $resCart['items']                    = $result['items'];
                $resCart['orderOtherServiceCharge']  = $result['orderOtherServiceCharge'];
                $resCart['orderPromoDiscountAmount'] = $result['orderPromoDiscountAmount'];
                $resCart['orderUserCreditAmount']    = $result['orderUserCreditAmount'];
                $freeProductGifts                    = 0;
                if (count($resCart['items']) > 0) {
                    foreach ($resCart['items'] as $key => $items) {
                        $str                                   = $items['itemDetails'];
                        //check free gifts available
                        if($items['freeProductsCount']>0 && $items['freeBaseProductID']<=0) {
                            //get free products
                            $argsFreeProducts                 = array(
                                'requestedBy' => 'customer',
                                'requestPage' => 'product_detail',
                                'limitFrom' => 0,
                                'limitTo' => '',
                                'languageIDs' => $languageIDs,
                                'previewOnly' => '',
                                'currDateTime' => '',                                    
                                'selectedProductID' => $items['productID'],
                                'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID

                            );
                            $freeProducts   = $ObjProduct->getActiveFreeProducts($argsFreeProducts);  
                            if(!empty($freeProducts)) {
                                $freeProductGifts = ($items['freeProductsCount']>count($freeProducts)) ? $freeProductGifts + count($freeProducts):$freeProductGifts + $items['freeProductsCount'];
                            }
                            
                        }
                       // $str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
                      //  $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
                    }
                }                
                $returnData['cartData']      = json_encode($resCart);
                $returnData['freeGiftCount'] = $freeProductGifts;
                echo json_encode($returnData);
                return true;
                break;
            case 'apply_promo':
				//$ObjCart->setRedeemPointDiscount(array(),$cartID,'remove');
                $promoCode             = $_POST['promoCode'];
                $promoCode             = trim($promoCode);
                $returnData            = array();
                $returnData['isError'] = 'No';
                $returnData['error']   = $this->getLanguageValue("lblPromoCodeApplied");
                if ($promoCode == '') {
                    $promoErrMsg = $this->getLanguageValue("lblPromoCodeNull");
                } else {
                    $promoDiscount = 0;
                    $promoData     = $this->setPromoCodeDiscount($promoCode);
                    $resTaxUpdate  = $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
                    $ObjCart->resetCartTotals($cartID);
                    if (isset($promoData['promoErrorCode']) && $promoData['promoErrorCode'] > 0) {
                        $promoErrMsg = $promoData['error'];
                    }
                }
                if (isset($promoErrMsg) && $promoErrMsg != '') {
                    $returnData['isError'] = 'Yes';
                    $returnData['error']   = $promoErrMsg;
                    echo json_encode($returnData);
                    return true;
                }
                $html                                = $this->getCartHtml($cartID);
                $returnData['cartHtml']              = $html;
                $cartleftsummaryhtml                       = $this->getCartPageSummary($cartID);
                $returnData['cartLeftBlockHtml']           = $cartleftsummaryhtml;
                $result                              = $ObjCart->getCartDetails($cartID, 0);
                $resCart['cartID']                   = $result['cartID'];
                $resCart['productType']              = $result['productType'];
                $resCart['orderSubtotal']            = $result['orderSubtotal'];
                $resCart['promoID']                  = $result['promoID'];
                $resCart['orderPromoCode']           = $result['orderPromoCode'];
                $resCart['orderQty']                 = $result['orderQty'];
                $resCart['orderTotalAmount']         = $result['orderTotalAmount'];
                $resCart['proceedCheckout']          = $result['proceedCheckout'];
                $resCart['currencyID']               = $result['currencyID'];
                $resCart['extra']                    = $result['extra'];
                $resCart['orderCharityID']           = $result['orderCharityID'];
                $resCart['shippingAmount']           = $result['shippingAmount'];
                $resCart['orderTaxAmount']           = $result['orderTaxAmount'];
                $resCart['userFirstName']            = $result['userFirstName'];
                $resCart['userLastName']             = $result['userLastName'];
                $resCart['userEmail']                = $result['userEmail'];
                $resCart['items']                    = $result['items'];
                $resCart['orderOtherServiceCharge']  = $result['orderOtherServiceCharge'];
                $resCart['orderPromoDiscountAmount'] = $result['orderPromoDiscountAmount'];
                $resCart['orderUserCreditAmount']    = $result['orderUserCreditAmount'];
                if (count($resCart['items']) > 0) {
                    foreach ($resCart['items'] as $key => $items) {
                        $str                                   = $items['itemDetails'];
                       // $str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
                       // $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
                    }
                }
                $returnData['cartData']              = json_encode($resCart);
                $returnData['cartCharityPromoBlock'] = $this->setPromoCharityBlock();
                echo json_encode($returnData);
                return true;
                break;
            case 'remove_promo':
                $returnData['isError']               = 'No';
                $returnData['error']                 = $this->getLanguageValue("lblPromoCodeRemoved");
                $promoCode                           = '';
                $promoData                           = $this->setPromoCodeDiscount($promoCode, 'remove');
                $resTaxUpdate                        = $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
                $resResetCartTotals                  = $ObjCart->resetCartTotals($cartID);
                $html                                = $this->getCartHtml($cartID);
                $cartleftsummaryhtml                       = $this->getCartPageSummary($cartID);
                $returnData['cartLeftBlockHtml']           = $cartleftsummaryhtml;
                $returnData['cartHtml']              = $html;
                $result                              = $ObjCart->getCartDetails($cartID, 0);
                $resCart['cartID']                   = $result['cartID'];
                $resCart['productType']              = $result['productType'];
                $resCart['orderSubtotal']            = $result['orderSubtotal'];
                $resCart['promoID']                  = $result['promoID'];
                $resCart['orderPromoCode']           = $result['orderPromoCode'];
                $resCart['orderQty']                 = $result['orderQty'];
                $resCart['orderTotalAmount']         = $result['orderTotalAmount'];
                $resCart['proceedCheckout']          = $result['proceedCheckout'];
                $resCart['currencyID']               = $result['currencyID'];
                $resCart['extra']                    = $result['extra'];
                $resCart['orderCharityID']           = $result['orderCharityID'];
                $resCart['shippingAmount']           = $result['shippingAmount'];
                $resCart['orderTaxAmount']           = $result['orderTaxAmount'];
                $resCart['userFirstName']            = $result['userFirstName'];
                $resCart['userLastName']             = $result['userLastName'];
                $resCart['userEmail']                = $result['userEmail'];
                $resCart['items']                    = $result['items'];
                $resCart['orderOtherServiceCharge']  = $result['orderOtherServiceCharge'];
                $resCart['orderPromoDiscountAmount'] = $result['orderPromoDiscountAmount'];
                $resCart['orderUserCreditAmount']    = $result['orderUserCreditAmount'];
                if (count($resCart['items']) > 0) {
                    foreach ($resCart['items'] as $key => $items) {
                        $str                                   = $items['itemDetails'];
                        //$str                                   = str_replace('orderCommissionAmount', '---------------------', $str);
                     //   $resCart['items'][$key]['itemDetails'] = str_replace('productCommissionRate', '------------------', $str);
                    }
                }
                $returnData['cartData']              = json_encode($resCart);
                $returnData['cartCharityPromoBlock'] = $this->setPromoCharityBlock();
                echo json_encode($returnData);
                return true;
                break;
        }
    }
    //Set Promocode Charity Block
    private function setPromoCharityBlock($section = 'cartEdit', $params = '') {
        $ObjCart                 = new CartModel();
        $languageIDs             = $this->ObjView->languageIDs;
        $cartID                  = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $settingsEnablePromoCode = $this->getSettingValue('product_cart_settings', 'enable_promo_codes');
        $this->ObjView->assign('enablePromoCode', $settingsEnablePromoCode);
        if ($section == 'cartEdit') {
            $resCart = $ObjCart->getCartSummary($cartID);
            $this->ObjView->assign('cartData', $resCart);
            return $this->ObjView->fetch('cart/CartCharityPromoBlock.tpl');
        } elseif ($section == 'cartCheckout') {
            $promoArray['promoError']  = 'No';
            $promoArray['promoErrMsg'] = '';
            $params['applyPromo']      = (isset($params['applyPromo']) ? $params['applyPromo'] : '');
            $params['removePromo']     = (isset($params['removePromo']) ? $params['removePromo'] : '');
            $params['promoCode']       = (isset($params['promoCode']) ? $params['promoCode'] : '');
            if ((isset($params['applyPromo']) && $params['applyPromo'] == 'Yes') || (isset($params['removePromo']) && $params['removePromo'] == 'Yes')) {
                if (isset($params['applyPromo']) && $params['applyPromo'] == 'Yes' && trim($params['promoCode']) == '') {
                    $promoArray['promoError']  = 'Yes';
                    $promoArray['promoErrMsg'] = $this->getLanguageValue("lblPromoCodeNull");
                    return $promoArray;
                }
                if (isset($params['removePromo']) && $params['removePromo'] == 'Yes') {
                    $params['promoCode']       = '';
                    $promoArray['promoErrMsg'] = $this->getLanguageValue("lblPromoCodeRemoved");
                    $promoData                 = $this->setPromoCodeDiscount('', 'remove');
                } else if ($params['applyPromo'] == 'Yes') {
                    $promoData = $this->setPromoCodeDiscount($params['promoCode']);
                }
                $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
                if (isset($promoData['promoErrorCode']) && $promoData['promoErrorCode'] > 0) {
                    $promoArray['promoErrMsg'] = $promoData['error'];
                    $promoArray['promoError']  = 'Yes';
                } else {
                    if ($params['applyPromo'] == 'Yes') {
                        $promoArray['promoErrMsg'] = $this->getLanguageValue("lblPromoCodeApplied");
                    }
                }
                return $promoArray;
            }
        }
    }
    public function ajaxApplyCouponAction() {
        $ObjGiftcoupn = new GiftcouponModel();
        $ObjCart      = new CartModel();
        $succMsg      = '';
        $errorMsg     = '';
        $couponCode   = $_REQUEST['couponCode'] = $_POST['couponCode'] = trim($_POST['couponCode']);
        $userID       = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $cartID       = $this->ObjSession->getSession("CARTID");
        $cartID       = $this->decodeString($cartID);
        $resRedeem    = $ObjGiftcoupn->redeemCoupon($couponCode, $userID);
        $giftSuccMsg  = '';
        if ($resRedeem == 'Inactive') {
            $giftErrMsg = $this->getLanguageValue("errCouponRedeemInactive");
        } elseif ($resRedeem == 'Redeemed') {
            $giftErrMsg = $this->getLanguageValue("errCouponRedeemUsed");
            $couponCode = '';
        } elseif ($resRedeem == 'Invalid') {
            $giftErrMsg = $this->getLanguageValue("errCouponRedeemInvalid");
            $couponCode = '';
        } elseif ($resRedeem == 'Expired') {
            $giftErrMsg = $this->getLanguageValue("errCouponRedeemExpired");
            $couponCode = '';
        } elseif ($resRedeem == 'Cancelled') {
            $giftErrMsg = $this->getLanguageValue("errCouponRedeemCancelled");
            $couponCode = '';
        } else {
            $updateCartItems = $ObjCart->resetCartTotals($cartID);
            $resRedeemAmt    = $this->ObjView->getFormattedCurrency($resRedeem);
            $giftSuccMsg     = $this->getLanguageValue('msgGiftCouponRedeemSuccess');
            $giftSuccMsg     = str_replace('{$amount}', $resRedeemAmt, $giftSuccMsg);
        }
        $html                   = $this->getCartHtml($cartID, 0);
        $returnData['cartHtml'] = $html;
        $resCart                = $ObjCart->getCartDetails($cartID, 0);
        $returnData['cartData'] = json_encode($resCart);
        $returnData['isError']  = ($giftSuccMsg == '') ? "Yes" : "No";
        $returnData['error']    = ($giftSuccMsg == '') ? $giftErrMsg : $giftSuccMsg;
        echo json_encode($returnData);
    }
    public function getCartHtml($cartID = 0) {
        if ($cartID > 0) {
            $ObjCart                    = new CartModel();
            $languageIDs                = $this->ObjView->languageIDs;
            $resCart                    = $ObjCart->getCartDetails($cartID, 0);
            $returnData['cartSummary']  = json_encode($resCart);
			$userID         			= $this->ObjSession->getSession("REGISTERED_USER_ID");
            $settingsApplyAfterDiscount = $this->getSettingValue('product_cart_settings', 'apply_after_discount');
            $settingsTaxApplicable      = $this->getSettingValue('product_cart_settings', 'tax_applicable');
            $languageIDs                = $this->ObjView->languageIDs;
            if (count($resCart['items']) > 0) {
                foreach ($resCart['items'] as $key => $items) {
                    $resCart['items'][$key]['unserialize'] = unserialize($items['itemDetails']);
                    $resProductOptions                     = $ObjCart->listCartItemOptions($languageIDs, $items['productID'], 'Active');
                    if (count($resProductOptions) == 1) {
                        $resCart['items'][$key]['hasOption'] = 'No';
                    } else {
                        $resCart['items'][$key]['hasOption'] = 'Yes';
                        $resCart['items'][$key]['options']   = $resProductOptions;
                    }
                    //show shipping methods and calculate charge
                    if($userID > 0){
                        $shippingAddress = $ObjCart->getUserDefaultShippingAddress($userID);
                        if(count($shippingAddress) > 0){
                            //checking available shipping methods match with saved address
//                                                $resCart['items'][$key]['shippingMethods'] = $this->isShippingAvailable($cartID,$items['productID'],$shippingAddress);
                            list($shippingMethods, $shippingReason) = $this->isShippingAvailable($cartID,$items['productID'],$shippingAddress);
                            $resCart['items'][$key]['shippingMethods'] = $shippingMethods;
                            $resCart['items'][$key]['shippingReason'] = $shippingReason;
                        }else{
                            //$resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']);
                            $resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
                            $resCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
                        }
                    }else{
                         //get all assigned shipping methods for a product, user not logged on or 
                         //$resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']);
                         $resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
                         $resCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
                    } 
                    unset($resProductOptions);
                    
                    $regularPrice                                           = $items['productOptionRegularPrice'];
                    $qnty                                                   = $items['orderItemQuantity'];
                    $currentRegularPrice                                    = ($regularPrice * $qnty);
                    $resCart['items'][$key]['productOptionRegularPrice']    = number_format($currentRegularPrice, 2, '.', '');
                }
                $blockQtyUpdate = "No";
                $this->ObjView->assign('enableApplyAfterDiscount', $settingsApplyAfterDiscount);
                $this->ObjView->assign('taxApplicable', $settingsTaxApplicable);
                $this->ObjView->assign('cartData', $resCart);
                $this->ObjView->assign('blockQtyUpdate', $blockQtyUpdate);
                return $html = $this->ObjView->fetch('cart/CartItems.tpl');
            } else {
                return 'empty';
            }
        }
    }
    public function setCODFee($paymentKey='') {
        $ObjCart            = new CartModel();
        $ObjPaymentObject   = new PaymentModel();
        $cartID      = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $bussIDChk = 0;
        $prevBusinessID = '';
        $conVenientFee      = 0;  
        if($paymentKey=='CashOnDeliveryRedemption') {               
            $conVenientFee      = $ObjPaymentObject->getPaymentSettingByKey(18,'convenientFee');
        } else {
            $conVenientFee      = 0;                
        }
        $conVenientFee      = ($conVenientFee=='')?0:$conVenientFee;   
        $resCart            = $ObjCart->getCartDetails($cartID, 0);
        if (count($resCart['items']) > 0) {                    
            foreach ($resCart['items'] as $key => $items) {                    
                if($items['businessID']!=$prevBusinessID) {
                    $bussIDChk++;
                    $codFee     = $conVenientFee;                      
                } else {
                    $codFee     = 0;                        
                } 
                $itemDet = unserialize($items['itemDetails']);
                $itemDet['orderConvenientFee']  = $codFee;                    
                $ObjCart->updateCartItemsCODFee($cartID,$items['cartItemID'],$itemDet);
                $prevBusinessID = $items['businessID'];
            }
        }
        $conVenientFee      = $conVenientFee;
        $ObjCart->updateCODFee($cartID,$conVenientFee);            
    }
    //Ajax procceses in checkout page
    //@updating billing address
    //@updating shipping address
    //@listing shipping methods
    //@listing payment methods    
    public function ajaxUpdateAddressAction() { 
        $ObjCart     = new CartModel();
        $ObjUsers    = new UserModel();
        $languageIDs = $this->ObjView->languageIDs;
        $userID      = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $cartID      = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $adrsType    = isset($_POST['adrsType']) ? $_POST['adrsType'] : '';
        $sameasshipping = isset($_POST['sameasshipping']) ? $_POST['sameasshipping'] : 'no';
        
        if ($userID < 1 && ($adrsType == 'Payment' || $adrsType == 'ShippingMethod' || $adrsType == 'Billing' || $adrsType == 'Shipping')) {
            $cartSummary = $ObjCart->getCartSummary($cartID);
            $extra       = unserialize($cartSummary['extra']);
            if (isset($extra) && $extra['userCheckoutEmail'] == '') {
                $userValidationData['userError'] = 'no_user';
                $this->setMessage($this->getLanguageValue("msgCheckoutNoUserError"), "error");
                echo json_encode($userValidationData);
                return true;
            }
        }
		
        $this->ObjView->assign('userID', $userID);
        $resUserDetails 	= $ObjUsers->getUserDetails($userID);
	$userEmail = isset($resUserDetails['userEmail'])?$resUserDetails['userEmail']:'';
        $actionForm                    = ($adrsType == 'Billing') ? 'formCheckoutBilling' : 'formCheckoutShipping';
        $actionButton                  = ($adrsType == 'Billing') ? 'submitCheckoutBilling' : 'submitCheckoutShipping';
        $_POST[$actionButton]          = '1';
        $returnData['validationError'] = 'No';
        $noValidation                  = 'No';
        if ($adrsType == 'Payment' || $adrsType == 'CF' || $adrsType == 'NC' || $adrsType == 'ShippingMethod' || (isset($_POST['applyPromo']) && $_POST['applyPromo'] == 'Yes') || (isset($_POST['removePromo']) && $_POST['removePromo'] == 'Yes') || (isset($_POST['applyRedeemPoint']) && $_POST['applyRedeemPoint'] == 'Yes') || (isset($_POST['removeRedeemPoint']) && $_POST['removeRedeemPoint'] == 'Yes')) {
            $noValidation = 'Yes';
        }
        $promoCharityArray = '';
		$redeemPointArray  = '';
        if (isset($_POST['applyPromo']) && $_POST['applyPromo'] == 'Yes') {
            $promoCharityArray['applyPromo'] = 'Yes';
            $promoCharityArray['promoCode']  = $this->escape($_POST['promoCode']);
        }
        if (isset($_POST['removePromo']) && $_POST['removePromo'] == 'Yes') {
            $promoCharityArray['removePromo'] = 'Yes';
            $promoCharityArray['promoCode']   = '';
        }
        $promoData = $this->setPromoCharityBlock('cartCheckout', $promoCharityArray);
		
		/* if (isset($_POST['applyRedeemPoint']) && $_POST['applyRedeemPoint'] == 'Yes') {
            $redeemPointArray['applyRedeemPoint'] = 'Yes';
            $redeemPointArray['redeemPoint']  = $this->escape($_POST['redeemPoint']);
        }
        if (isset($_POST['removeRedeemPoint']) && $_POST['removeRedeemPoint'] == 'Yes') {
            $redeemPointArray['removeRedeemPoint'] = 'Yes';
            $redeemPointArray['redeemPoint']   = '';
        }
         if(!empty($redeemPointArray))
        {
			$redeemPtData = $this->setRedeemPoints('cartCheckout', $redeemPointArray);
        }  */
		
		
		
		
        if ($noValidation == 'No') {
            if ($this->ObjForm->isValid($actionForm, $actionButton, false) || $sameasshipping == 'yes') {
              
                if ($adrsType == 'Billing') {
                    $arrAddress = array(
                        'billingFirstName' => trim(stripslashes($_POST['billingFirstName'])),
                        'billingLastName' => trim(stripslashes($_POST['billingLastName'])),
                        'billingAddress' => trim(stripslashes($_POST['billingAddress'])),
                        'billingAddress1' => trim(stripslashes($_POST['billingAddress1'])),
                        'billingCity' => trim(stripslashes($_POST['billingCity'])),
                        'billingProvince' => trim(stripslashes((isset($_POST['billingProvince']) ? $_POST['billingProvince'] : ''))),
                        'billingZip' => trim(stripslashes($_POST['billingZip'])),
                        'billingState' => trim(stripslashes((isset($_POST['billingState']) ? $_POST['billingState'] : 0))),
                        'billingCountry' => trim(stripslashes($_POST['billingCountry'])),
                        /*'billCountrycode' => trim(stripslashes($_POST['billCountrycode'])), */
                        'billingPhone' =>  trim(stripslashes($_POST['billCountrycode'])).'-'.trim(stripslashes($_POST['billingPhone'])),
                        'billingEmail' => trim(stripslashes($_POST['billingEmail']))
                    );
                } else if ($adrsType == 'Shipping') {
                    /*$arrAddress1	= array(
                                            'shippingFname' 	=> trim(stripslashes($_POST['shippingFname'])),
                                            'shippingLname' 	=> trim(stripslashes($_POST['shippingLname'])),
                                            'shippingAddress' 	=> trim(stripslashes($_POST['shippingAddress'])),
                                            'billingAddress1' 	=> trim(stripslashes($_POST['shippingAddress1'])),
                                            'shippingCity' 		=> trim(stripslashes($_POST['shippingCity'])),
                                            'shippingProvince' 	=> trim(stripslashes((isset($_POST['shippingProvince'])?$_POST['shippingProvince']:''))),
                                            'shippingZip' 		=> trim(stripslashes($_POST['shippingZip'])),
                                            'shippingState' 		=> trim(stripslashes((isset($_POST['shippingState'])?$_POST['shippingState']:0))),
                                            'shippingCountry' 	=> trim(stripslashes($_POST['shippingCountry'])),
                                            'shippingPhone' 	=> trim(stripslashes($_POST['shippingPhone']))
											
                                                        );	*/
                    if($sameasshipping == 'yes') {
                        $_POST['shippingState'] = isset($_POST['billingStateID']) ? $_POST['billingStateID'] : 0;
                    }
                    $shippingStateID  =  isset($_POST['shippingState']) ? $_POST['shippingState'] : 0;
                    if($shippingStateID<=0 || $shippingStateID=='' || $shippingStateID=='undefined'){
                        $shippingStateID = isset($_POST['billingStateID']) ? $_POST['billingStateID'] : 0;
                    }
                    $arrAddress = array(
                        'shippingFname' => trim(stripslashes($_POST['shippingFname'])),
                        'shippingLname' => trim(stripslashes($_POST['shippingLname'])),
                        'shippingAddress' => trim(stripslashes($_POST['shippingAddress'])),
                        'shippingAddress1' => trim(stripslashes($_POST['shippingAddress1'])),
                        'shippingCity' => trim(stripslashes($_POST['shippingCity'])),
                        'shippingProvince' => trim(stripslashes((isset($_POST['shippingProvince']) ? $_POST['shippingProvince'] : ''))),
                        'shippingZip' => trim(stripslashes($_POST['shippingZip'])),
                        /*'shipCountrycode' => trim(stripslashes($_POST['shipCountrycode'])),*/
                        'shippingPhone' =>  trim(stripslashes($_POST['shipCountrycode'])).'-'.trim(stripslashes($_POST['shippingPhone'])),
                        'shippingStateID' => trim(stripslashes($shippingStateID)),
                        'shippingCountryID' => trim(stripslashes($_POST['shippingCountry']))
                       
                    );                  
                    if ($_POST['shippingSaveToList']) {
                        $ObjCart->saveCartShippingAddressToList($arrAddress, $userID);
                    }                    
                    if ($_POST['address']>0 && $userID>0) {
                        $ObjCart->updateShippingAddress($arrAddress, $_POST['address']);
                    }
                }
                $resCartUpdate	= $ObjCart->updateUserCartAddressOnestep($userID,$cartID,$arrAddress,'',$adrsType);
                // prev ship calc & tax upd
            } else {
               
                $returnData['validationError'] = 'Yes';
                echo json_encode($returnData);
                return true;
            }
        }
		//for Convient Fee Update
        if ($adrsType == 'CF' || $adrsType == 'NC') {
           $this->setCODFee($_POST['paymentKey']);
        }        
        $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
        $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
        if ($adrsType == 'Payment' || $adrsType == 'ShippingMethod' || $adrsType == 'CF' || $adrsType == 'NC') {
            $promoData = $this->setPromoCodeDiscount('', '', '', 'checkout');
            if ($adrsType == 'CF' || $adrsType == 'NC') {
                $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
            }
        } /*else {
            $promoData = $this->setPromoCodeDiscount();
        }*/
        
        $resCart = $ObjCart->getCartDetails($cartID, 0);
        if (count($resCart['items']) > 0) {
            foreach ($resCart['items'] as $key => $items) {
                $resCart['items'][$key]['itemDetails'] = unserialize($items['itemDetails']);
                $resProductOptions = $ObjCart->listCartItemOptions($languageIDs, $items['productID'],'Active');
                if($items['freeProduct']=='No')
                    if (empty($productIDList) || !in_array($items['productID'], $productIDList))
                        $productIDList[]  =   $items['productID'];
                    
                if(count($resProductOptions)==1)
                {
                        $resCart['items'][$key]['hasOption']='No';
                }
                else
                {
                        $resCart['items'][$key]['hasOption']='Yes';
                        $resCart['items'][$key]['options']=$resProductOptions;
                }
                if($userID > 0){
                        $shippingAddress = $ObjCart->getUserDefaultShippingAddress($userID);
                        if(count($shippingAddress) > 0){
                            //checking available shipping methods match with saved address
                            list($shippingMethods, $shippingReason) =$this->isShippingAvailable($cartID,$items['productID'],$shippingAddress);
                            $resCart['items'][$key]['shippingMethods'] = $shippingMethods;
                            $resCart['items'][$key]['shippingReason'] = $shippingReason;
                        }else{                            
                            $resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
                            $resCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
                        }
                    }else{
                         //get all assigned shipping methods for a product, user not logged on or                         
                         $resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
                        $resCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
                    }
                    $resCart['items'][$key]['productoptin']=$resProductOptions;
                    unset($resProductOptions);
            }
        }
        $resCart['cartDetails'] = unserialize($resCart['extra']);
        if (isset($resCart['cartDetails']['userBillingAddress']) && is_array($resCart['cartDetails']['userBillingAddress'])) {
            $tempArray = array_slice($resCart['cartDetails']['userBillingAddress'], 0, -2);
            unset($resCart['cartDetails']['userBillingAddress']);
            $resCart['cartDetails']['userBillingAddress'] = array_values($tempArray);
        }
        unset($tempArray);
        $tempArray = (isset($resCart['cartDetails']['userShippingAddress'])) ? $resCart['cartDetails']['userShippingAddress'] : '';
        unset($resCart['cartDetails']['userShippingAddress']);
        if (is_array($tempArray))
            $resCart['cartDetails']['userShippingAddress'] = array_values($tempArray);
        $this->ObjView->assign('cartData', $resCart);
        if ($adrsType == 'Payment') {
            if ($resCart['orderTotalAmount'] > 0) {
                $expYearsValues[0] = range(date("Y"), (date("Y") + 18));
                $expYearsValues[1] = range(date("Y"), (date("Y") + 18));
                foreach (range(date("Y"), (date("Y") + 18)) as $key => $expyearValue) {
                    $years[$key][] = $expyearValue;
                    $years[$key][] = $expyearValue;
                }
                if ($this->getSettingValue("security_settings", "store_cc_info") == 'Yes' && $userID > 0) {
                    $getUserCCInfo = $ObjUsers->getUserCCInfo($userID);
                }
                $resUserDetails = $ObjUsers->getUserDetails($userID);
                if (!empty($getUserCCInfo)) {
                    $creditCardFirstName = $getUserCCInfo['firstNameonCard'];
                    $creditCardLastName  = $getUserCCInfo['lastNameonCard'];
                    $creditCardNumber    = $this->decodeString($getUserCCInfo['cardNumber']);
                    $creditCardTypeId    = $getUserCCInfo['cardType'];
                    $expMonth            = $getUserCCInfo['expMonth'];
                    $expYear             = $getUserCCInfo['expYear'];
                } else {
                    $creditCardFirstName = isset($resUserDetails['userFirstName']) ? $resUserDetails['userFirstName'] : '';
                    $creditCardLastName  = isset($resUserDetails['userLastName']) ? $resUserDetails['userLastName'] : '';
                }
				$this->ObjView->assign('redmpt_point', $resCart['redeemPoint']);
                $this->ObjView->assign('redeemDiscountAmount', $resCart['redeemDiscountAmount']);
                $this->ObjView->assign('years', $years);
                $this->ObjView->assign('creditCardFirstName', $creditCardFirstName);
                $this->ObjView->assign('creditCardLastName', $creditCardLastName);
                $this->ObjView->assign('expMonth', isset($expMonth) ? $expMonth : '');
                $this->ObjView->assign('expYear', isset($expYear) ? $expYear : '');
                $this->ObjView->assign('creditCardNumber', isset($creditCardNumber) ? $creditCardNumber : '');
                $this->ObjView->assign('creditCardType', isset($creditCardTypeId) ? $creditCardTypeId : '');
                $this->ObjView->assign('userCardType', isset($creditCardTypeId) ? $creditCardTypeId : '');
                $ObjCountry		= new CountryModel();
                $iso2CountryFormat =   $ObjCountry->getCountryCode(unserialize($resCart['extra'])['userShippingAddress']['shippingCountryID']);
                $resPaymentGateways = $this->showPaymentTitleByLang($ObjCart->listPaymentGateways($resCart['currencyID'],'',$iso2CountryFormat)); 
					
                $this->ObjView->assign('resPaymentGateways', $resPaymentGateways);
                $this->ObjView->assign('paymentGatewaysCount', count($resPaymentGateways));

            }
            $settingsEnableTerms = $this->getSettingValue('product_cart_settings', 'enable_terms_privacy');
            $this->ObjView->assign('enableTermsPrivacy', $settingsEnableTerms);
            $this->ObjView->assign('selectedPaymentKey', $resCart['paymentSettingsGroupID']);
            $this->ObjCommon->setDynamicMenuPlugin($this->ObjView);
            $html = $this->ObjView->fetch('cart/CheckoutPayment.tpl');
        } else if ($adrsType == 'ShippingMethod') {
            
           $needshippingMethodReset = true;
            
            $shippingZip               = trim(stripslashes($_POST['shippingZip']));
            $shippingStateID           = trim(stripslashes((isset($_POST['shippingState']) ? $_POST['shippingState'] : 0)));
            $shippingCountryID         = trim(stripslashes($_POST['shippingCountry']));
            $shippingStateSelectedType = 'state';//trim(stripslashes($_POST['shippingStateSelectedType']));
            $businessShipping          = array();
            $shippingMethodsAll        = array();
            $shippingFreeEnable        = $this->getSettingValue('shipping_settings', 'shipping_free_enable');
            $freeShippingAmount        = $this->getSettingValue('shipping_settings', 'free_shipping_amount');
            $freeShippingQty           = $this->getSettingValue('shipping_settings', 'free_shipping_qty');
            $group_shipping_cost       = $this->getSettingValue('product_cart_settings', 'group_shipping_cost');
            
            if ($group_shipping_cost == 'Yes') {
                $shippsArgs          = array(
                    'shippingZip' => $shippingZip,
                    'shippingStateID' => $shippingStateID,
                    'shippingCountryID' => $shippingCountryID,
                    'shippingStateSelectedType' => $shippingStateSelectedType
                );
                $userDeliveryZoneIDs = $this->getUserDeliverZoneID($shippsArgs);
                $shippingMethods     = $ObjCart->listShippingMethods($cartID, 0, $languageIDs, $group_shipping_cost, $userDeliveryZoneIDs,$this->_shippingCalculationParam['shipping_cost_global']);
                
                $products            = array();
                $prevID = '';
                foreach ($resCart['items'] as $items) {
                    if($prevID != $items['productID']) {
                        $products[$items['businessID']][] = $items['productID'];
                    }
                    $prevID = $items['productID'];
                }
                $resShippingMethods = array();
                $setFlagSameShip = 'Yes';
                foreach ($shippingMethods as $methods) {
                    //if (count($products[$methods['businessID']]) == count(array_intersect(explode(",", $methods['productIDs']), $products[$methods['businessID']]))) {
                        $resShippingMethods[] = $methods;
                    /*}else{
                        $setFlagSameShip = 'No';
                    }*/
                }
                
                if (count($resShippingMethods) < count($products) && $this->_shippingCalculationParam['shipping_cost_global']!='Yes') {
                    $resShippingMethods  = $ObjCart->listShippingMethods($cartID);
                    $group_shipping_cost = 'No';
                }
            } else {
                $resShippingMethods = $ObjCart->listShippingMethods($cartID, 0, $languageIDs);
            }
            //$resShippingMethods	= $ObjCart->listShippingMethods($cartID);
            //echo '<pre>'; print_r($resShippingMethods); //exit;
            
            if (count($resShippingMethods) > 0) {
                $shippingParams['shippingZip']               = $shippingZip;
                $shippingParams['shippingStateID']           = $shippingStateID;
                $shippingParams['shippingCountryID']         = $shippingCountryID;
                $shippingParams['shippingStateSelectedType'] = $shippingStateSelectedType;
                $shippingParams['cartID']                    = $cartID;
                $shippingParams['shippingTaxable']           = $this->_shippingCalculationParam['shippingTaxable'];
                $shippingParams['globalShippingCity']        = $this->_shippingCalculationParam['globalShippingCity'];
                $shippingParams['globalShippingCountry']     = $this->_shippingCalculationParam['globalShippingCountry'];
                $shippingParams['globalShippingState']       = $this->_shippingCalculationParam['globalShippingState'];
                $shippingParams['globalShippingZipcode']     = $this->_shippingCalculationParam['globalShippingZipcode'];
                
                $prodOptionsArr                              = array();
               
                //Looping shipping methods
                foreach ($resShippingMethods as $key => $method) {
                    $itemDetails = unserialize($method['itemDetails']);
                    if ($method['settingsGroupID'] > 0) {
                        $shippingMethodsdeliveryZones = $ObjCart->listShippingMethodsDeliveryZones($method['shippingtoproductID'], $method['productID'], $group_shipping_cost);
                    }
                    if($method['settingsGroupXmlLabel']=='Jihazi Delivery Charge' || $method['settingsGroupXmlLabel']=='Jihazi Delivery') {
                        $method['settingsGroupXmlLabel'] = $this->getLanguageValue('JihaziDeliveryCharge');
                    }
                    $deliveryZoneFound = false;
                    $shippingAvilable  = true;
                    $shippingCharge    = 99999999;
                    unset($ObjShippingLib);
                    unset($ObjShipping);
                    //If shipping method have delivery zones
                    if (isset($shippingMethodsdeliveryZones) && count($shippingMethodsdeliveryZones) > 0) {
                        foreach ($shippingMethodsdeliveryZones as $key1 => $zone) {
                            $deliveryZoneDetails = $ObjCart->getDeliveryZoneDetails($languageIDs, $zone['deliveryZoneID']);
                            if (count($deliveryZoneDetails) > 0) {
                                //Looping with delivery zone values
                                foreach ($deliveryZoneDetails as $key1 => $zoneReg) {
                                    //If delivery zone countryID matching the users countryID
                                    if ($zoneReg['countryID'] == $shippingCountryID && $shippingCountryID > 0) {
                                        //If delivery zone type is region or local with state ID and user state matching delivery zone state
                                        if ($zoneReg['StateID'] > 0 && $zoneReg['StateID'] == $shippingStateID && $shippingStateID > 0) {
                                            //Delivery zone type is range with zip code or zip code combination / Delivery zone type is Local
                                            if (($zoneReg['zipCodes'] != '' || $zoneReg['isRange'] == 'Yes') && $shippingZip != '') {
                                                //Delivery zone type is range with zip code
                                                if ($zoneReg['isRange'] == 'Yes' && is_numeric($shippingZip)) {
                                                    if ($shippingZip >= $zoneReg['rangeFrom'] && $shippingZip <= $zoneReg['rangeTo']) {
                                                        $deliveryZoneFound = true;
                                                        break;
                                                    }
                                                } else if (substr($zoneReg['zipCodes'], -1) == '*') //Delivery zone type is zip code combination / Delivery zone type is Local
                                                    {
                                                    $zipArray         = explode('*', $zoneReg['zipCodes']);
                                                    $startingZip      = $zipArray[0];
                                                    $starting_str_len = strlen($startingZip);
                                                    $user_sub_zip     = substr($shippingZip, 0, $starting_str_len);
                                                    if ($user_sub_zip == $startingZip) {
                                                        $deliveryZoneFound = true;
                                                        break;
                                                    }
                                                } else //Delivery zone type is fixed zip code / Delivery zone type is Local
                                                    {
                                                    $zipArray = explode(',', $zoneReg['zipCodes']);
                                                    if (in_array($shippingZip, $zipArray)) {
                                                        $deliveryZoneFound = true;
                                                        break;
                                                    }
                                                }
                                            } else if ($zoneReg['zipCodes'] == '') //Delivery zone type is region
                                                {
                                                $deliveryZoneFound = true;
                                                break;
                                            }
                                        } //If delivery zone type is Region with out state ID
                                        else if ($shippingStateSelectedType == 'province') {
                                            //Delivery zone type is range with zip code / Delivery zone type is Local
                                            if ($zoneReg['isRange'] == 'Yes' && is_numeric($shippingZip)) {
                                                if ((int) $shippingZip >= $zoneReg['rangeFrom'] && (int) $shippingZip <= $zoneReg['rangeTo']) {
                                                    $deliveryZoneFound = true;
                                                    break;
                                                }
                                            } else if (substr($zoneReg['zipCodes'], -1) == '*') //Delivery zone type is zip code combination / Delivery zone type is Local
                                                {
                                                $zipArray         = explode('*', $zoneReg['zipCodes']);
                                                $startingZip      = $zipArray[0];
                                                $starting_str_len = strlen($startingZip);
                                                $user_sub_zip     = substr($shippingZip, 0, $starting_str_len);
                                                if ($user_sub_zip == $startingZip) {
                                                    $deliveryZoneFound = true;
                                                    break;
                                                }
                                            } elseif (!empty($zoneReg['zipCodes'])) //Delivery zone type is fixed zip code / Delivery zone type is Local
                                                {
                                                $zipArray = explode(',', $zoneReg['zipCodes']);
                                                if (in_array($shippingZip, $zipArray)) {
                                                    $deliveryZoneFound = true;
                                                    break;
                                                }
                                            } else if ($zoneReg['zipCodes'] == '' && $zoneReg['StateID'] < 1) {
                                                $deliveryZoneFound = true;
                                                break;
                                            }
                                        } //Delivery zone type is national
                                        else if ($zoneReg['zipCodes'] == '' && $zoneReg['StateID'] < 1) {
                                            $deliveryZoneFound = true;
                                            break;
                                        }
                                    }
                                } //delivery zone details Loop ends
                            }
                            if ($deliveryZoneFound)
                                break;
                        } //delivery zone assigned to shipping moethod Loop ends
                        //If current shipping methods delivery zone found
                        if ($method['settingsGroupID'] > 0 && $deliveryZoneFound) {
                            //If current looping item is free product then display shipping charge as zero
                            if (isset($cartItem['freeProduct']) && $cartItem['freeProduct'] == 'Yes') {
                                $shippingCharge = 0;
                                $shippingtype   = 'Free';
                            }
                            //If the current shipping method is free shipping
                            if ($method['settingsGroupKey'] == 'free_shipping' || $method['settingsGroupParent'] == 1) {
                                $paramsArray     = array(
                                    'tableName' => 'cart_items',
                                    'fieldName' => 'sum(orderItemQuantity) as orderItemQuantity',
                                    'conditionField' => 'productID',
                                    'condition' => '=',
                                    'conditionValue' => $method['productID'],
                                    'conditionField1' => 'cartID',
                                    'condition1' => '=',
                                    'conditionValue1' => $cartID,
                                    'conditionFieldType' => ''
                                );
                                $resOrderItemQty = $ObjCart->getFieldValue($paramsArray);
                                //checking min quantity for free shipping cehcking
                                if ($resOrderItemQty['orderItemQuantity'] >= $method['maxQtyPerShipping']) {
                                    $shippingCharge = 0;
                                    $shippingtype   = 'Free';
                                } else {
                                    $shippingAvilable = false;
                                }
                            } else if ($shippingFreeEnable != 'No') //Free shipping enbaled in settings
                                {
                                if ($shippingFreeEnable == 'Globally') //Globally Free shipping enbaled in settings
                                    {
                                    $defaultCurrencyId = $this->ObjView->_defaultCurrency;
                                    $cartcurrencyId    = $resCart['currencyID'];
                                    $cartAmount        = $this->ObjView->convertValueCustom($resCart['orderSubtotal'], $cartcurrencyId, $defaultCurrencyId);
                                    $cartQty           = $resCart['orderQty'];
                                    if (($cartAmount > $freeShippingAmount && $freeShippingAmount > 0) || ($cartQty > $freeShippingQty && $freeShippingQty > 0)) {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingCharge = 0;
                                            $shippingtype   = 'Free';
                                        } else {
                                            $shippingCharge = 0;
                                            $shippingtype   = 'Free';
                                            //$shippingAvilable=false;
                                        }
                                    } else {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingtype = 'Paid';
                                        } else {
                                            $shippingCharge = 100;
                                            $shippingtype   = 'Paid';
                                            //$shippingAvilable=false;
                                        }
                                    }
                                } else if ($shippingFreeEnable == 'Business wise') {
                                    $businesswiseDetails = $ObjCart->getBusinessWiseCartDetails($method['productID'], $cartID);
                                    $defaultCurrencyId   = $this->ObjView->_defaultCurrency;
                                    $cartcurrencyId      = $resCart['currencyID'];
                                    $cartAmount          = $this->ObjView->convertValueCustom($businesswiseDetails['orderItemSubtotal'], $cartcurrencyId, $defaultCurrencyId);
                                    $cartQty             = $businesswiseDetails['orderItemQuantity'];
                                    if (($cartAmount > $freeShippingAmount && $freeShippingAmount > 0) || ($cartQty > $freeShippingQty && $freeShippingQty > 0)) {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingCharge = 0;
                                            $shippingtype   = 'Free';
                                        } else {
                                            $shippingCharge = 0;
                                            $shippingtype   = 'Free';
                                            //$shippingAvilable=false;
                                        }
                                    } else {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingtype = 'Paid';
                                        } else {
                                            $shippingCharge = 100;
                                            $shippingtype   = 'Paid';
                                            //$shippingAvilable=false;
                                        }
                                    }
                                }
                            } else {
                                if ($method['isRealTimeCalculation'] == 'No') {
                                    $shippingtype = 'Paid';
                                } else {
                                    $shippingCharge = 100;
                                    $shippingtype   = 'Paid';
                                    //$shippingAvilable=false;
                                }
                            }
                            if ($shippingAvilable) {
                                $subArray                                                                   = array(
                                    'methodName' => $method['settingsGroupXmlLabel'],
                                    'methodID' => $method['settingsGroupID'],
                                    'shippingCharge' => $shippingCharge,
                                    'shippingtype' => $shippingtype,
                                    'settingsGroupKey' => $method['settingsGroupKey'],
                                    'settingsGroupParent' => $method['settingsGroupParent']
                                );
                                $shippingArray[$method['productID']]['methods'][$method['settingsGroupID']] = $subArray;
                            }
                        }
                    }
                   
                    $shippingArray[$method['productID']]['businessID']       = $method['businessID'];
                    $shippingArray[$method['productID']]['itemName']         = $method['productOptionName'];
                    $shippingArray[$method['productID']]['free_shipping']    = isset($itemDetails['free_shipping']) ? $itemDetails['free_shipping'] : 'false';
                    $shippingArray[$method['productID']]['shippingMethodID'] = isset($itemDetails['shippingMethod']['methodID']) ? $itemDetails['shippingMethod']['methodID'] : '';
                    
                    $prodOptionsArr[$method['productID']][]     =   $method['businessID'];
                }
            }
            
            if (!empty($shippingArray) && count($shippingArray) > 0) {
                foreach ($shippingArray as $key => $method) {
                    if (isset($method['methods']) && count($method['methods']) > 0) {
                        foreach ($method['methods'] as $key1 => $shippingMethod) {
                            
                            $prodOptionsNewArr         =   array_unique($prodOptionsArr[$key]);
                            //echo "<pre>"; print_r($prodOptionsNewArr); exit;
                            
                            $shippingParams['productID']       = $key;
                            $shippingParams['settingsGroupID'] = $shippingMethod['methodID'];
                            $shippingParams['globalBaseCharge'] = $this->_shippingParam['global_shipping_baseCharge'];
                            if ($shippingMethod['settingsGroupKey'] != '' && $shippingMethod['shippingtype'] == 'Paid') {
                                $paramsArray           = array(
                                    'tableName' => 'shipping_methods',
                                    'fieldName' => 'settingsGroupKey',
                                    'conditionField' => 'settingsGroupID',
                                    'condition' => '=',
                                    'conditionValue' => $shippingMethod['settingsGroupParent'],
                                    'conditionFieldType' => 'int'
                                );
                                $resshippingGateWayKey = $ObjCart->getFieldValue($paramsArray);
                                $shippingGateWayKey    = $resshippingGateWayKey['settingsGroupKey'];                               
                                $ObjShippingLib        = new Shipping($shippingGateWayKey);
                                $ObjShipping           = $ObjShippingLib->getShippingObject();
                                if (!is_object($ObjShipping)) {
                                    continue;
                                } else {
                                    
                                    list($shippingTax, $shippingCharge) = $ObjShipping->getShippingRate($shippingParams);
                                    if ($group_shipping_cost == 'Yes') {
                                        if($this->_shippingCalculationParam['shipping_cost_global']!='Yes')
                                            $busID  =   $method['businessID'];
                                        else
                                            $busID  =   0;
                                        $shippingCharge = $this->groupShippingAmount($cartID, $busID, $shippingMethod['methodID'], $userDeliveryZoneIDs,$shippingCharge);
                                    }
                                    if(count($prodOptionsNewArr)>1){
                                        $shippingCharge = $shippingCharge*count($prodOptionsNewArr);
                                    }
                                    $needshippingMethodReset = false;
                                }
                                if ($shippingCharge == 'error') {
                                    unset($shippingArray[$key]['methods'][$key1]);
                                } else {
                                    $shippingArray[$key]['methods'][$key1]['shippingCharge'] = $shippingCharge;
                                    $shippingArray[$key]['methods'][$key1]['shippingTax']    = $shippingTax;
                                }
                            }
                        }
                    }
                }
            } else {
                //Double checking
                //If address not matching for shiping method need to reset
                $ObjCart->resetShippingMethod($cartID);
            }
            if(empty($shippingArray)) {
                $shippingArray = array();
            }
           //echo '<pre>'; print_r($shippingArray);echo $group_shipping_cost; exit;
            $this->ObjView->assign('group_shipping_cost', $group_shipping_cost);
            $this->ObjView->assign('shippingMethods', $shippingArray);
            $this->ObjView->assign('showWarning', 1);
            $html = $this->ObjView->fetch('cart/CheckoutShippingMethod.tpl');
        } else {
            $html    = $this->ObjView->fetch('cart/CheckoutLeftBlock.tpl');
            $summary = $this->ObjView->fetch('cart/CheckoutOrderSummary.tpl');
            //$summary = $this->ObjView->fetch('cart/CheckoutOrderDetails.tpl');
            
             //23-04-15 START
            $this->ObjView->assign('orderTotalAmount', $resCart['orderTotalAmount']);
            $this->ObjView->assign('shippingAmount', $resCart['shippingAmount']);
            $this->ObjView->assign('cartDatacurrencyID', $resCart['currencyID']);
            $this->ObjView->assign('cartUsercurrencyID', $resCart['userCurrencyID']);
            $returnData['htmlShipp'] = $this->ObjView->fetch('cart/CartShippingTotal.tpl');
            //23-04-15 
        }
        $returnData['html']      = $html;
        $returnData['summary']   = isset($summary) ? $summary : '';
        $returnData['promoData'] = $promoData;
		$returnData['redeemPtData'] = $redeemPtData;
	if ($adrsType == 'CF' || $adrsType == 'NC') {
            return $returnData;
        }
        echo json_encode($returnData);
        return true;
    }
    public function showPaymentTitleByLang($resPaymentGateways) {
       
        if(!empty($resPaymentGateways)) {
            
            foreach($resPaymentGateways as $keyp=>$pg) {                
                if($this->getLanguageValue($pg['paySetGroupKey'])!=''){
                    $resPaymentGateways[$keyp]['label'] = $this->getLanguageValue($pg['paySetGroupKey']);
                    $resPaymentGateways[$keyp][1]       = $this->getLanguageValue($pg['paySetGroupKey']);
                }
                
            }
            
        }
        return $resPaymentGateways;
    }
    public function groupShippingAmount($cartID, $businessID, $methodID, $userDeliveryZoneIDs,$shippingCharge) {
        $ObjCart = new CartModel();
        $params  = array(
            'businessID' => $businessID,
            'cartID' => $cartID,
            'methodID' => $methodID,
            'userDeliveryZoneIDs' => $userDeliveryZoneIDs
        );
        $result  = $ObjCart->groupShippingAmount($params);
        //$result['baseCharge'] = $shippingCharge;
        if ($result['orderItemQuantity'] > $result['maxQtyPerShipping']) {
            $extraQty       = $result['orderItemQuantity'] - $result['maxQtyPerShipping'];
            $extraCharge    = $extraQty * $result['chargePerExtraQty'];
            $shippingCharge = ($result['baseCharge']) + $result['handlingCharge'] + $extraCharge;
        } else {
            $shippingCharge = ($result['baseCharge']) + $result['handlingCharge'];
        }
        return $shippingCharge;
    }
    public function getUserDeliverZoneID($params = array()) {        
        extract($params);
        $ObjDelivery         = new DeliveryZoneModel();
        $ObjCart             = new CartModel();
        $languageIDs         = $this->ObjView->languageIDs;
        $userDeliveryZoneIDs = array();
        $deliveryZones       = $ObjDelivery->listDeliveryZones($languageIDs);        
        foreach ($deliveryZones as $zone) {
            $deliveryZoneFound   = false;
            $deliveryZoneDetails = $ObjCart->getDeliveryZoneDetails($languageIDs, $zone['deliveryZoneID']);  
            if (count($deliveryZoneDetails) > 0) {
                //Looping with delivery zone values
                foreach ($deliveryZoneDetails as $key1 => $zoneReg) {
                    //If delivery zone countryID matching the users countryID
                    if ($zoneReg['countryID'] == $shippingCountryID && $shippingCountryID > 0) {                       
                        //If delivery zone type is region or local with state ID and user state matching delivery zone state
                        if ($zoneReg['StateID'] > 0 && $zoneReg['StateID'] == $shippingStateID && $shippingStateID > 0) {
                            //Delivery zone type is range with zip code or zip code combination / Delivery zone type is Local
                            if (($zoneReg['zipCodes'] != '' || $zoneReg['isRange'] == 'Yes') && $shippingZip != '') {
                                //Delivery zone type is range with zip code
                                if ($zoneReg['isRange'] == 'Yes' && is_numeric($shippingZip)) {
                                    if ($shippingZip >= $zoneReg['rangeFrom'] && $shippingZip <= $zoneReg['rangeTo']) {
                                        $deliveryZoneFound = true;
                                        break;
                                    }
                                } else if (substr($zoneReg['zipCodes'], -1) == '*') //Delivery zone type is zip code combination / Delivery zone type is Local
                                    {
                                    $zipArray         = explode('*', $zoneReg['zipCodes']);
                                    $startingZip      = $zipArray[0];
                                    $starting_str_len = strlen($startingZip);
                                    $user_sub_zip     = substr($shippingZip, 0, $starting_str_len);
                                    if ($user_sub_zip == $startingZip) {
                                        $deliveryZoneFound = true;
                                        break;
                                    }
                                } else //Delivery zone type is fixed zip code / Delivery zone type is Local
                                    {
                                    $zipArray = explode(',', $zoneReg['zipCodes']);
                                    if (in_array($shippingZip, $zipArray)) {
                                        $deliveryZoneFound = true;
                                        break;
                                    }
                                }
                            } else if ($zoneReg['zipCodes'] == '') //Delivery zone type is region
                                {
                                $deliveryZoneFound = true;
                                break;
                            }
                        } //If delivery zone type is Region with out state ID
                        else if ($shippingStateSelectedType == 'province') {
                            //Delivery zone type is range with zip code / Delivery zone type is Local
                            if ($zoneReg['isRange'] == 'Yes' && is_numeric($shippingZip)) {
                                if ((int) $shippingZip >= $zoneReg['rangeFrom'] && (int) $shippingZip <= $zoneReg['rangeTo']) {
                                    $deliveryZoneFound = true;
                                    break;
                                }
                            } else if (substr($zoneReg['zipCodes'], -1) == '*') //Delivery zone type is zip code combination / Delivery zone type is Local
                                {
                                $zipArray         = explode('*', $zoneReg['zipCodes']);
                                $startingZip      = $zipArray[0];
                                $starting_str_len = strlen($startingZip);
                                $user_sub_zip     = substr($shippingZip, 0, $starting_str_len);
                                if ($user_sub_zip == $startingZip) {
                                    $deliveryZoneFound = true;
                                    break;
                                }
                            } elseif (!empty($zoneReg['zipCodes'])) //Delivery zone type is fixed zip code / Delivery zone type is Local
                                {
                                $zipArray = explode(',', $zoneReg['zipCodes']);
                                if (in_array($shippingZip, $zipArray)) {
                                    $deliveryZoneFound = true;
                                    break;
                                }
                            } else if ($zoneReg['zipCodes'] == '' && $zoneReg['StateID'] < 1) {
                                $deliveryZoneFound = true;
                                break;
                            }
                        } //Delivery zone type is national
                        else if ($zoneReg['zipCodes'] == '' && $zoneReg['StateID'] < 1) {
                            
                            $deliveryZoneFound = true;
                            break;
                        }
                    }
                } //delivery zone details Loop ends
                if ($deliveryZoneFound) {
                    $userDeliveryZoneIDs[] = $zone['deliveryZoneID']; 
                }
            }
            
        }
        return $userDeliveryZoneIDs;
    }
    public function checkoutAction() {
        $ObjCart              = new CartModel();
        $ObjPayment           = new PaymentModel();
        $ObjPaymentgateway      = new PaymentgatewayModel();
        $languageIDs          = $this->ObjView->languageIDs;
        //$otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
        //$this->ObjView->assign('otpEnableCheckout', $otpEnableCheckout);
        $cartID  = $this->decodeString($this->ObjSession->getSession("CARTID"));
		
		$resCart = $ObjCart->getCartDetails($cartID, 0);
		$result = $this->processOrder($cartID, $resCart);
    }
    
    public function ajaxcheckoutAction() {
        $ObjCart              = new CartModel();
        $ObjPayment           = new PaymentModel();
        $ObjPaymentgateway      = new PaymentgatewayModel();
        $languageIDs          = $this->ObjView->languageIDs;
        //$otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
        //$this->ObjView->assign('otpEnableCheckout', $otpEnableCheckout);
        $cartID  = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $resCart = $ObjCart->getCartDetails($cartID, 0);
        $username	=	isset($_POST['username']) && $_POST['username']!='' ? $_POST['username'] : '';
		$useremail	=	isset($_POST['useremail']) && $_POST['useremail']!='' ? $_POST['useremail'] : '';
		$userphone	=	isset($_POST['userphone']) && $_POST['userphone']!='' ? $_POST['userphone'] : '';
		$useremail = filter_var($useremail, FILTER_SANITIZE_EMAIL);
		$containsblockedwords = 'no';
		$blockedWords = ['testing','test','example'];
		if ($badWord = $this->containsBlockedWords($username, $blockedWords)){
			$containsblockedwords = 'yes';
		}
		if ($badWord = $this->containsBlockedWords($useremail, $blockedWords)) {
			$containsblockedwords = 'yes';
		}
		if(!empty($username) && !empty($useremail) && !empty($userphone) && $userphone!='971' && filter_var($useremail, FILTER_VALIDATE_EMAIL) != false && $containsblockedwords == 'no'){
			$result = $this->processOrder($cartID, $resCart);
		}else{
			echo json_encode(array('result'=>'failed'));exit;
		}
        //$result = $this->processOrder($cartID, $resCart);
    }
    //AJAX CARD TYPE ACTION
    public function ajaxCardTypeAction() {
        $paymentCardType = '';
        $str             = '';
        if ($_POST['paymentKey'] != '') {
            $ObjCart      = new CartModel();
            $listCardType = $ObjCart->listPaymentSettingByGroupKey($_POST['paymentKey'], 'payment_card_type');
            if ($listCardType['paySetValue'] != '') {
                $paymentCardType = $this->getLanguageValue('lblselecttext') . "->";
                $paymentCardType .= '~*' . $listCardType['paySetValue'];
                $cardTypeArray = explode('~*', $paymentCardType);
                foreach ($cardTypeArray as $key => $cardTypeValue) {
                    $cardTypeValue = explode('->', $cardTypeValue);
                    $str .= ' <option value="' . $cardTypeValue[1] . '">' . $cardTypeValue[0] . '</option>';
                }
            }
        }
        echo $str;
    }
    //END OF FUNCTION	
	 //unset extra fees
    public function ajaxUnsetExtraFeeAction() {
        $ObjCart               = new CartModel();
        $paymentKey            = $_POST['paymentKey'];
        $cartID                = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $ObjPaymentObject      = new PaymentModel();
        $paymentGatewayDetails = array();
        $res = array();		
        $str = '';
        if ($paymentKey != '') {  
            if($cartID>0) {
                $ObjCart->updatePaymentSettingsID($cartID,$paymentKey);
            }
            if($paymentKey=='CashOnDeliveryRedemption') {
                $_POST['adrsType']      = 'CF';                
            } else {
                $_POST['adrsType']      = 'NC';   
            }
            $returnData = $this->ajaxUpdateAddressAction();   
            $returnData['str'] = $str; 
        } 
        echo json_encode($returnData);
    }
    //For Showing Offline Payment Descriptions.
    public function ajaxOfflinePaymentsAction() {
        $ObjCart               = new CartModel();
        $ObjLanguage           = new LanguageModel();
        $ObjPaymentObject      = new PaymentModel();
        $paymentKey            = $_POST['paymentKey'];
        $cartID                = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $paymentGatewayDetails = array();
        $languageIDs       = $this->ObjView->languageIDs;
        $language_id              = $languageIDs['Current'];	
	$str = '';
        if ($paymentKey != '') {
            if($cartID>0) {
                $ObjCart->updatePaymentSettingsID($cartID,$paymentKey);
            }
            if($language_id==1){
                $paymentGatewayDetails = $ObjCart->listPaymentSettingByGroupKey($paymentKey, 'payment_instructions');
            } else {
                $paymentGatewayDetails = $ObjCart->listPaymentSettingByGroupKey($paymentKey, 'payment_instructions_arabic');
            }
            if ($paymentGatewayDetails['paySetValue'] != '') {
                
                $str = "<div><strong>" . $this->getLanguageValue('lblPaymentInstructions') . "</strong></div><p>
				" . $this->decodeSplChar($paymentGatewayDetails['paySetValue']) . "</p>";
                
            }
            $_POST['adrsType']      = 'CF';                
            $returnData = $this->ajaxUpdateAddressAction(); 
            if ($paymentKey =='CashOnDeliveryRedemption') {
                $codFee     = $ObjPaymentObject->getPaymentSettingByKey(18,'convenientFee');
            } else {
                $codFee     = 0;
            }
            $returnData['str']      = $str;
            if($codFee>0) {
                $returnData['codFee']   = $this->getLanguageValue('lblConvenientFee').': '.$this->ObjView->getFormattedCurrency($codFee, 'Full', 0, $this->ObjView->_defaultCurrency);
            } else {
                $returnData['codFee']   = '';
            }
            
        }
       echo json_encode($returnData);
    }
    private function processOrder($cartID = 0, $resCart = array()) {
        
        $ObjCart           = new CartModel();
        $ObjLanguage       = new LanguageModel();
        $ObjPaymentgateway = new PaymentgatewayModel();
        $ObjPaymentObject  = new PaymentModel();
        $languageIDs       = $this->ObjView->languageIDs;
        $defaultCurrencyId = $this->ObjView->_defaultCurrency;
        if ((int)$cartID > 0) {
            $orderType = 'single';
            //$getDistinctCartItem = $ObjCart->getDistinctCartBusiness($cartID); //For SVS
            $paymentStatus           = 'Pending';
            $orderStatus             = 'New';
			
            $paymentSettingsGroupKey = (isset($_POST['paymentSettingsGroupKey']) ? $_POST['paymentSettingsGroupKey'] : '');
            if($paymentSettingsGroupKey!='') {
            //============================================================
                $paramsArray             = array(
                    'tableName' => 'payment_settings_group',
                    'fieldName' => 'paySetGroupID',
                    'conditionField' => 'paySetGroupKey',
                    'condition' => '=',
                    'conditionValue' => $paymentSettingsGroupKey,
                    'conditionFieldType' => ''
                );
                $resPaymentSettings      = $ObjCart->getFieldValue($paramsArray);
                $paymentSettingsGroupID  = $resPaymentSettings['paySetGroupID'];
                $resTransactionType      = $ObjPaymentgateway->listPaymentSettingsByGroupId($paymentSettingsGroupID, '', 'transaction_type');
                if (isset($resTransactionType[0]['paySetValue']) && $resTransactionType[0]['paySetValue'] == 'AUTH_ONLY') {
                    $authValue = ($paymentSettingsGroupKey == 'Authorize' || $paymentSettingsGroupKey == 'Free_Checkout') ? 'AUTH_ONLY' : 'Authorization';
                    $authType  = 'AUTH_ONLY';
                } else {
                    $authValue = ($paymentSettingsGroupKey == 'Authorize' || $paymentSettingsGroupKey == 'Free_Checkout') ? 'AUTH_CAPTURE' : 'Sale';
                    $authType  = 'AUTH_CAPTURE';
                }
            } else {
                 $authType  = 'AUTH_CAPTURE';
                 $authValue = $authType;
            }
            //==========================================================
            
            $resCart['authType']      = $authType;
            $resCart['authValue']     = $authValue;
            $resCart['paymentStatus'] = $paymentStatus;
            $resCart['orderStatus']   = $orderStatus;
            $resCart['subtitle']      =   isset($_POST['subtitle']) && $_POST['subtitle']!='' ? $_POST['subtitle'] : $_POST['hidSubTitle'];
            $resCart['userFirstName'] =   isset($_POST['username']) && $_POST['username']!='' ? $_POST['username'] : $_POST['hidUserName'];
            $resCart['userEmail']     =   isset($_POST['useremail']) && $_POST['useremail']!='' ? $_POST['useremail'] : $_POST['hidUserEmail'];
            $resCart['userPhone']     =   isset($_POST['userphone']) && $_POST['userphone']!='' ? $_POST['userphone'] : $_POST['hidUserPhone'];
            $order_id = $this->createOrder($resCart, $orderType, 0);
            $cartcurrencyId = $resCart['currencyID'];
            if ($resCart['orderTotalAmount'] > 0) {
                $resOrder      = $ObjCart->getOrderMasterDetails($order_id);
                $resOrderItems = $ObjCart->getOrderItemDetails($order_id);
                $storeCcInfo                 = $this->getSettingValue("security_settings", "store_cc_info");
                $resOrder['store_cc_info']   = $storeCcInfo;
                $resOrder['postData']        = $_POST;
                $resOrder['siteDesc']        = substr($this->getSettingValue('site_settings', 'site_name'), 0, 90);
                $resOrder['authValue']       = $authValue;
                $resOrder['orderDesc']       = substr("MSTR ORD NUM - " . $order_id . "  " . $this->getSettingValue('site_settings', 'site_name'), 0, 90);
                $resOrder['langLCID']        = $this->ObjView->_currLanguageLCID;
                
                $this->ObjSession->setSession("HOLDCARTID", $this->encodeString($cartID));
                //Call Gateway Proccess
                switch ($paymentSettingsGroupKey) {
                    case 'CashOnDeliveryRedemption':
                        $className  = 'CashOnDeliveryRedemptionModel';
                        $siteHosted = 0;
                        break;
                    case 'NetworkOnline':
                        $className             = 'NetworkOnlineModel';
                        $siteHosted            = 0;
                        $resOrder['returnURL'] = $this->ObjView->_views_host . '/cart/expresscheckout/source/networkonline/orderID/' . $this->encodeString($order_id) . '/';
                        $resOrder['cancelURL'] = $this->ObjView->_views_host . '/cart/expresscheckout/source/networkonline/orderID/' . $this->encodeString($order_id) . '/';
                        $resOrder['payment_mode'] = 1;
                        break;
					case 'Ngeniusonline':
                        $className             = 'NgeniusonlineModel';
                        $siteHosted            = 0;
                        $resOrder['returnURL'] = $this->ObjView->_views_host . '/cart/expresscheckout/source/ngeniusonline/orderID/' . $this->encodeString($order_id) . '/';
                        $resOrder['cancelURL'] = $this->ObjView->_views_host . '/cart/expresscheckout/source/ngeniusonline/orderID/' . $this->encodeString($order_id) . '/';
                        $resOrder['payment_mode'] = 1;
                        break;
                    case 'Free_Checkout':
                        $className  = 'FC';
                        $siteHosted = 0;
                        break;
                }
                if ($className != '') {
                    $ObjPayment = new Payment($className);
                    $Objgateway = $ObjPayment->getPaymentObject();
                    if (!is_object($Objgateway)) {
                        $this->setMessage($this->getLanguageValue("lblCartCartGatewayNotConfigured"), "error");
                        $this->setRedirect();
                    }
                    $this->ObjSession->setSession("HOLD_ORDERID", $order_id);
                    $paymentResponse = $Objgateway->process($resOrder, $resOrderItems,'',$cartID);
                 
                    
              //      print_r($paymentResponse);
                    $orderSuccess    = ($paymentResponse == 'Pending') ? 'Success' : 'Failure';
                }
                if ($paymentSettingsGroupKey == 'Free_Checkout') {
                    $orderSuccess                 = 'Success';
                    $resOrder['paymentType']      = 'Free';
                    $resOrder['paySetGroupLabel'] = 'Free_Checkout';
                    $insertPaymentTransaction     = $ObjPaymentObject->createTransaction($resOrder, '', 'Success', '', $authType, 0, 'Free_Checkout');
                }
                //Payment success
                if ($orderSuccess == 'Success') {
                    $orderID = $this->paymentSuccess($order_id);
                    //$ObjCart->changeMasterOrderStatus(0, 'Pending', '', $order_id,'update');
					if($paymentSettingsGroupKey=='NetworkOnline' || $paymentSettingsGroupKey=='Ngeniusonline'){
					$method = 'credit-card';
					}
					else{
						$method = 'pay-at-showroom';
					}
                    $this->ObjSession->setSession("CART_REDIRECT", "Yes");
                    $_SESSION['CART_REDIRECT'] = 'Yes';                    
                    $res['result']  =   'success';
                    $res['type']  	=   $method;
                    $res['orderid']  =   $this->encryptDecrypt("encrypt",$order_id);
                    echo json_encode($res);
                    //$this->setRedirect('/payment/index/id/' . $order_id . '/');
                    exit;
                } else if ($orderSuccess == 'Failure' && $Objgateway->isError) {
                    $ObjCart->changeMasterOrderStatus(0, 'Error', 'Denied', $order_id);
					
                    $this->setMessage($Objgateway->errorMessage, 'error');
                    $this->setRedirect();
                    exit;
                } else {
                    $this->setRedirect();
                }
            } else {
				if($paymentSettingsGroupKey=='NetworkOnline' || $paymentSettingsGroupKey=='Ngeniusonline'){
					$method = 'credit-card';
				}
				else{
					$method = 'pay-at-showroom';
				}
                $orderID = $this->paymentSuccess($order_id);
                $this->ObjSession->setSession("CART_REDIRECT", "Yes");
                $_SESSION['CART_REDIRECT'] = 'Yes';    
                $this->setRedirect('/payment/index/type/'.$method.'/id/' . $order_id . '/');
                exit;
            }
        }
    }
    //Payment success Function 
    public function payfortpaymentAction() {
        $response = $_REQUEST;
        $order_id = $this->decodeString($this->getRequestValue("orderID"));
        if($order_id>0) {
            if($response['response_message']=='Success' && $response['token_name']!='') {
                $className = 'PayfortModel';
                if ($className != '') {
                    $ObjPaymentLib = new Payment($className);
                    $Objgateway    = $ObjPaymentLib->getPaymentObject();
                    if (!is_object($Objgateway)) {
                        $this->setMessage("Gateway not configured", "error");
                        $this->setRedirect('/cart/');
                        exit;
                    }
                }
                $purchaseResp = $Objgateway->process($getOrderDetails,$getOrderedItems,'Y',$response); 
            } else {            
                $ObjCart->changeMasterOrderStatus(0, 'Error', 'Denied', $order_id);
                $this->reupdateCartPromoUsage();
                $this->setRedirect("/cart/checkout/");
                exit;
                
            } 
        }else {
            $this->setRedirect("/cart/checkout/");
            exit;
        }
    }
    
    //Note here $orderID => master order number
    public function paymentSuccess($orderID) {
        $ObjOrder                       = new OrderModel();
        $ObjPayment                     = new PaymentModel();
        $ObjPaymentgateway              = new PaymentgatewayModel();
        $ObjCart                        = new CartModel();
        $ObjEmailtemplate               = new EmailtemplateModel();
        $ObjCountry                     = new CountryModel();
        $ObjUsers                       = new UserModel();
        $mail_settings                  = $this->getSettingValue('mail_settings');
        $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
        $ObjMail                        = new Mail($mail_settings);
        $siteName                       = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl                        = $this->getSettingValue('site_settings', 'global_http_url');
        $companyLogo                    = $this->getSettingValue('company_information', 'company_logo');
        
        //$this->checkOrderAction($orderID);
        $languageIDs        = $this->ObjView->languageIDs;
        $defaultCurrencyId  = $this->ObjView->_defaultCurrency;
        $parentOrderID      = $orderID;
        $refStatus          = '';
        $allMasterOrders    = $ObjCart->getOrderMasterIDByOrderNumber($orderID, 'all');
        $masterOrderDetails = $ObjCart->getOrderMasterDetailsByParentOrderID($orderID);
        $creditAmount       = ($masterOrderDetails['orderUserCreditAmount'] > 0) ? $masterOrderDetails['orderUserCreditAmount'] : 0;
        $creditAmount       = $this->ObjView->convertValueCustom($creditAmount, $masterOrderDetails['purchasedCurrency'], $defaultCurrencyId);
        $orderLangIDs       = $languageIDs;
		
        foreach ($allMasterOrders as $key => $items) {
            $orderID            = $items['masterOrderID'];
            //======================================================================================
            $resTransactionType = $ObjPaymentgateway->listPaymentSettingsByGroupId($masterOrderDetails['paymentSettingsGroupID'], '', 'transaction_type');
            if (isset($resTransactionType[0]['paySetValue']) && $resTransactionType[0]['paySetValue'] == 'AUTH_ONLY') {
                $paymentStatus = 'Pending';
            } else {
                $paymentStatus = 'Received';
            }
            $orderStatus = 'Process';
            //======================================================================================
            $ObjCart->changeMasterOrderStatus($orderID, $orderStatus, $paymentStatus);
            $updateOrderNumber = $ObjOrder->updateOrderHold($orderID, 'No');
            $getOrderDetails   = $ObjCart->getOrderMasterDetails($orderID);
            $fileName   =   $this->cartbroucherconfirmationAction($orderID);
            $updateOrderFile = $ObjOrder->updateOrderFile($fileName,$orderID);
            $ObjMail->ClearAddresses();
            $orderItems                                       = $ObjCart->getOrderItemDetails($orderID, $orderLangIDs);
            $master_order_details[$key]['order_details']      = $getOrderDetails;
            $master_order_details[$key]['order_item_details'] = $orderItems;
            $resUpdateProductInventory                        = $ObjCart->updateProductInventory($orderID);
            $orderLangIDs['Default']                          = $getOrderDetails['languageID'];
            $orderLangIDs['Current']                          = $getOrderDetails['languageID'];
            //Admin LanguageID
            $languageIDsCustomAdmin            = $languageIDs;
            $languageIDsCustomAdmin['Current'] = $languageIDs['Default'];
            //if ($getOrderDetails['paymentSettingsGroupID'] > 0) {
                $getPaymentSettingGroupDetails = $ObjPaymentgateway->getPaymentSettingGroupDetails($getOrderDetails['paymentSettingsGroupID']);
                $resPaymentSettingDetails = $ObjPaymentgateway->listPaymentSettingsValueByGroupId($getOrderDetails['paymentSettingsGroupID']);
//            } else {
//                $getPaymentSettingGroupDetails['paySetGroupLabel'] = 'Account Credit';
//                $getPaymentSettingGroupDetails['paySetGroupKey']   = 'AccountCredit';
//            }
            $getOrderDetails['paymentSetGroupKey'] = $getPaymentSettingGroupDetails['paySetGroupKey'];
            
            //mail to business for Cash On Delivery/Redemption
//            if ($getPaymentSettingGroupDetails['paySetGroupKey'] == 'CashOnDeliveryRedemption' || $sendMailToBus == 'Yes') {
//                $ObjMail->ClearAddresses();
//                $this->sendCashOnDeliveryMail($ObjMail, $getOrderDetails, $orderID, $ObjCart, $ObjEmailtemplate, $ObjCountry);
//            }
            //if ($getPaymentSettingGroupDetails['paySetGroupKey'] == 'CashOnDeliveryRedemption' || $getPaymentSettingGroupDetails['paySetGroupKey'] == 'ChequeMoneyOrder') {
//            if(isset($resPaymentSettingDetails['transaction_mode']) && $resPaymentSettingDetails['transaction_mode'] == 'Offline'){
//                $orderStatus                      = 'Process';
//                $paymentStatus                    = 'Pending';
//                $getOrderDetails['paymentStatus'] = 'Pending';
//                $ObjCart->changeMasterOrderStatus($orderID, $orderStatus, $paymentStatus);
//            }
            //mail to admin for out of stock
            $ObjMail->ClearAddresses();
            $ObjMail->ClearAddresses();
            
            
            //Save affiliate referral purchases   
            if ($key > 0) {
                $newOrderNumber = $items['orderNumber'];
                ;
                $orderNumbers .= "," . $newOrderNumber;
            } else {
                $newOrderNumber = $items['orderNumber'];
                $orderNumbers   = $newOrderNumber;
            }
	
        }
        $masterOrderDetails['orderNumbers'] = $orderNumbers;
        $this->sendProductOrderConfirmationAdmin($ObjMail, $masterOrderDetails, $parentOrderID, $ObjCart, $ObjEmailtemplate, $ObjCountry);
        if (isset($master_order_details) && count($master_order_details) > 0) {
            foreach ($master_order_details as $j => $item) {
                $getOrderDetails = $item['order_details'];
                $orderItems      = $item['order_item_details'];
                //if ($getOrderDetails['paymentSettingsGroupID'] > 0) {
                $getPaymentSettingGroupDetails = $ObjPaymentgateway->getPaymentSettingGroupDetails($getOrderDetails['paymentSettingsGroupID']);
//                } else {
//                    $getPaymentSettingGroupDetails['paySetGroupLabel'] = 'Account Credit';
//                    $getPaymentSettingGroupDetails['paySetGroupKey']   = 'AccountCredit';
//                }
                $getOrderDetails['paymentSetGroupKey'] = $getPaymentSettingGroupDetails['paySetGroupKey'];
                $this->sendProductOrderConfirmationUser($ObjMail, $getOrderDetails, $orderItems, $ObjEmailtemplate, $ObjCountry);
		//$this->sendsmsToUser($getOrderDetails);
                $ObjMail->ClearAddresses();
                
            }
        }
        //LOG TRACKING ORDER DETAILS UPDATION

        //Update user billing address if its users first purchase
        $updateUsersAddress = $ObjCart->saveUserBillingAddress($masterOrderDetails['userID'], $masterOrderDetails);
        ///////////////////////////////////////////////////////////////////////
        $cartID             = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $this->ObjSession->unsetSession("CARTID");
        $this->ObjSession->unsetSession("HOLD_ORDERID");
        $this->ObjSession->unsetSession("GUEST_ORDER_ID");
        $this->ObjSession->unsetSession("GUEST_EMAIL_ID");          
        $this->ObjCookie->setCookie("EMAIL_NOTIFICATION_ID", 0);
        $this->ObjCookie->setCookie("EMAIL_CAMPAIGN_USER", '');
        $ObjCart->clearCart($cartID);
        $orderNumbers = $masterOrderDetails['orderNumber'];
        //exit;
        return $parentOrderID;
    }
    public function testEmailAction() {
        $mail_settings                  = $this->getSettingValue('mail_settings');
        $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
        $ObjMail                        = new Mail($mail_settings);
        
        $emailbody                = 'test content ';
        $emailbody                .= $this->ObjView->getFormattedCurrency('200', '', 0, 13);
        $from                     = array(
            'vinu@ispg.in',
            'vinu'
        );
        $subject                  = 'checking...';
        $siteName                 = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl                  = $this->getSettingValue('site_settings', 'global_http_url');
        $companyLogo              = $this->getSettingValue('company_information', 'company_logo');
        
        $orderLangIDs['Default']  = 2;
        $orderLangIDs['Current']  = 2;
        //echo "<pre>";print_r($this->ObjView->_currencies);exit;
        $mailContent = $emailbody;
        $emailID     = stripslashes($billingInfo['billingEmail']);
        $this->ObjView->assign('companyLogo', $companyLogo);
        $this->ObjView->assign('emailbody', $mailContent);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('siteName', $siteName);
        $this->ObjView->assign('userName', $userName);
        $this->ObjView->assign('unsubscribeID', $emailID);
        $body = $this->ObjCommon->fetch("email_templates/Layout.tpl", $orderLangIDs);
        //echo $body;exit;
        //send mail to user
        $ObjMail->IsHTML();
        
        try {
            //echo $body;exit;
            $send = $ObjMail->sendMail($from, $emailID, $subject, $body);
            $ObjMail->Send();
        }
        catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
    private function sendProductOrderConfirmationUser($ObjMail, $getOrderDetails, $orderedItems, $ObjEmailtemplate, $ObjCountry) {
        $ObjOrder                       = new OrderModel();
        $ObjCart                        = new CartModel();
        $ObjBrand                       = new BrandModel();
        $ObjCustomOption                = new CustomOptionModel();
        $ObjShowroom                    = new ShowroomsModel();
        $ObjProduct                     = new ProductModel();
        $languageIDs                         = $this->ObjView->languageIDs;
            $languageIDs['Content'] = $languageIDs['Current'];
        $orderID    =   $getOrderDetails['masterOrderID'];
        $getOrderDetails   = $ObjCart->getOrderMasterDetails($orderID);
        $orderItems    = $ObjCart->getOrderItemDetailsByParentOrderID($orderID,array(),'','Yes');
        $productID  =   $orderItems[0]['productID'];

        $emailbody  =   '';
        ////////////////////////////////////////
        $productType          = array(
                    'productTypeID' => 1,
                    'productTypeKey' => 'product_product',
                    'productTypeUrlKey' => '',
                    'isFeatured' => 1,
                    'limitMainListing' => '',
                    'limitDefListing' => '',
                    'productTypeName' => $this->getLanguageValue('lblProducts')
        );
        $args                 = array(
            'requestedBy' => 'customer',
            'requestPage' => 'product_detail',
            'limitFrom' => 0,
            'limitTo' => 1,
            'productType' => $productType,
            'languageIDs' => $languageIDs,
            'selectedProductID' => $productID,
            'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID,
            'productStatus' => 'Active'
        );
        $resultProductProduct = $ObjProduct->getProductDetails($args);
        ////////////////////////////////////////
        $imagesetarr	=	explode('-',$resultProductProduct[0]['optionSKU']);
        $modelVariantCode   =   $imagesetarr[0];
        $itemDetails              =   unserialize($orderItems[0]['extra']);
             $variantText = '<table border="0" cellpadding="10" cellspacing="0" width="100%" style="font-size: 14px;">
	<tbody>';
            foreach ($itemDetails['customOptionValues'] as $values) {    
                $customOptionVariantID	=	$values[0]['customOptionVariantID'];
                $variantdetails	=	$ObjCustomOption->getVariantDetails($customOptionVariantID);
                if($values[0]['customOptionName']!='Wheel' && $values[0]['customOptionName']!='Trim')
                        $imagesetarr[]	=	$variantdetails['variantCode'];

                $variantText .= '<tr>
			<td style="color: #848586;" width="160">'.$this->getLanguageValue("lbl".$values[0]['customOptionName']).'</td>
			<td style="color: #111315;">'.$values[0]['variantValue'].'</td>
                            </tr>';
            }
            $variantText .= '</tbody>
</table>';
        $resProductSummaryImages  =   $ObjProduct->getProductImages(implode('_',$imagesetarr),'extr','yes',30,'thumb');
        $psarr	=	array('showroomID'=>$itemDetails['showroom'],'languageIDs'=>$languageIDs,'brandID' => $this->ObjCommon->brandID);
        $resShowroomDets	=	$ObjShowroom->getShowroom($psarr);
        $paramsBrand            = array(
                    'languageIDs' => $languageIDs,
                    'brandID'     => $getOrderDetails['brandID']
                );
        $brandInfo              = $ObjBrand->getBrand($paramsBrand);
        //Getting template
        
        $ObjPaymentgateway              = new PaymentgatewayModel();
        $getPaymentSettingGroupDetails = $ObjPaymentgateway->getPaymentSettingGroupDetails($getOrderDetails['paymentSettingsGroupID']);
        
        //Getting template
        if($getPaymentSettingGroupDetails['paySetGroupKey'] == 'NetworkOnline' || $getPaymentSettingGroupDetails['paySetGroupKey'] == 'Ngeniusonline')
            $emailbody                = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-order-confirmation-user');
        else
            $emailbody                = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-order-request-confirmation-user');
        $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');
        $emailbody            = $emailbody['emailHtml'];

        $subject        = stripslashes($subject);
        $userName       =stripslashes($getOrderDetails['subtitle']).stripslashes($getOrderDetails['billingFirstName']) . " " . stripslashes($getOrderDetails['billingLastName']);
        $bodytag        = str_replace('{$userName}', $userName, $emailbody);
        $bodytag        = str_replace('{$modelVariantCode}', $modelVariantCode, $bodytag);
        //$bodytag        = str_replace('{$variantlist}', $variantText, $bodytag);
        foreach ($itemDetails['customOptionValues'] as $values) {    
                $bodytag        = str_replace('{$'.$values[0]['customOptionName'].'}', $values[0]['variantValue'], $bodytag);
            }
        $bodytag        = str_replace('{$externalviewimage}', $resProductSummaryImages[0]['Imageslist'], $bodytag);
        $bodytag     = str_replace('{$productTitle}', $orderItems[0]['productOptionName'], $bodytag);
        $bodytag        = str_replace('{$franchisee}', stripslashes($brandInfo['brandName']), $bodytag);
        $bodytag        = str_replace('{$showroomName}', stripslashes($resShowroomDets['name']), $bodytag);
        $bodytag        = str_replace('{$showroomEmail}', stripslashes($resShowroomDets['email']), $bodytag);
            //$bodytag        = str_replace('{$showroomPhone}', stripslashes($resShowroomDets['phone']), $bodytag);
			$phone = stripslashes(preg_replace('/\s+/', '', $resShowroomDets['phone']));
            $bodytag        = str_replace('{$showroomPhone}', '<a href="tel:'.$phone.'">'.$phone.'</a>', $bodytag);
            $bodytag        = str_replace('{$showroomAddress}', stripslashes(nl2br($resShowroomDets['address'])), $bodytag);
            /* $bodytag        = str_replace('{$showroomLatitude}', stripslashes($resShowroomDets['latitude']), $bodytag);
            $bodytag        = str_replace('{$showroomLongitude}', stripslashes($resShowroomDets['longitude']), $bodytag); */
		$bodytag        		= str_replace('{$mapLink}', stripslashes($resShowroomDets['mapLink']), $bodytag);
        $bodytag        = str_replace('{$userEmail}', stripslashes($getOrderDetails['customer_email']), $bodytag);
        $bodytag        = str_replace('{$userPhone}', stripslashes($getOrderDetails['billingPhone']), $bodytag);
        $bodytag     = str_replace('{$orderID}', $getOrderDetails['orderNumber'], $bodytag);
        $bodytag     = str_replace('{$siteUrl}', $siteUrl, $bodytag);
        $bodytag     = str_replace('{$companyLogo}', $companyLogo, $bodytag);
        $bodytag        = str_replace('{$orderPaidAmount}', stripslashes($this->ObjView->getFormattedCurrency($getOrderDetails['orderPaidAmount'] , '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID'])), $bodytag);
        $bodytag        = str_replace('{$orderTotalAmount}', stripslashes($this->ObjView->getFormattedCurrency($getOrderDetails['orderTotalAmount'] , '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID'])), $bodytag);
        $mailContent = $bodytag;
        $emailID     = stripslashes($getOrderDetails['customer_email']);
        $this->ObjView->assign('companyLogo', $companyLogo);
        $this->ObjView->assign('emailbody', $mailContent);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('siteName', $siteName);
        $this->ObjView->assign('userName', $userName);
        
        $body = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
        //send mail to user
        $ObjMail->IsHTML();
        $ObjMail->AddAttachment(__CORE_PUBLIC_PATH.'/uploads/invoice/'.$getOrderDetails['orderFileName'], $getOrderDetails['orderFileName']);
        try {
            $send = $ObjMail->sendMail($from, $emailID, $subject, $body);
            $ObjMail->Send();
        }
        catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
    private function sendProductOrderConfirmationAdmin($ObjMail, $getOrderDetails, $orderID, $ObjCart, $ObjEmailtemplate, $ObjCountry) {
        $ObjOrder                       = new OrderModel();
        $ObjCart                        = new CartModel();
        $ObjCustomOption                = new CustomOptionModel();
        $ObjBrand                       = new BrandModel();
        $ObjShowroom                    = new ShowroomsModel();
        $ObjProduct                     = new ProductModel();
        $languageIDs                         = $this->ObjView->languageIDs;
            $languageIDs['Content'] = $languageIDs['Current'];
        $orderID    =   $getOrderDetails['masterOrderID'];
        $getOrderDetails   = $ObjCart->getOrderMasterDetails($orderID);
        $orderItems    = $ObjCart->getOrderItemDetailsByParentOrderID($orderID,array(),'','Yes');
        $productID  =   $orderItems[0]['productID'];

        $emailbody  =   '';
        ////////////////////////////////////////
        $productType          = array(
                    'productTypeID' => 1,
                    'productTypeKey' => 'product_product',
                    'productTypeUrlKey' => '',
                    'isFeatured' => 1,
                    'limitMainListing' => '',
                    'limitDefListing' => '',
                    'productTypeName' => $this->getLanguageValue('lblProducts')
        );
        $args                 = array(
            'requestedBy' => 'customer',
            'requestPage' => 'product_detail',
            'limitFrom' => 0,
            'limitTo' => 1,
            'productType' => $productType,
            'languageIDs' => $languageIDs,
            'selectedProductID' => $productID,
            'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID,
            'productStatus' => 'Active'
        );
        $resultProductProduct = $ObjProduct->getProductDetails($args);
        ////////////////////////////////////////
        $imagesetarr	=	explode('-',$resultProductProduct[0]['optionSKU']);
        $modelVariantCode   =   $imagesetarr[0];
        $itemDetails              =   unserialize($orderItems[0]['extra']);
            $variantText = '<table border="0" cellpadding="10" cellspacing="0" width="100%" style="font-size: 14px;">
	<tbody><tr>
			<td style="color: #848586;" width="160">'.$this->getLanguageValue("lblVariant").'</td>
			<td style="color: #111315;">'.$modelVariantCode.'</td>
                            </tr>';
            foreach ($itemDetails['customOptionValues'] as $values) {    
                $customOptionVariantID	=	$values[0]['customOptionVariantID'];
                $variantdetails	=	$ObjCustomOption->getVariantDetails($customOptionVariantID);
                if($values[0]['customOptionName']!='Wheel' && $values[0]['customOptionName']!='Trim')
                        $imagesetarr[]	=	$variantdetails['variantCode'];
//                $variantText .= '<tr>
//                                    <td style="font-family:Arial, Helvetica, sans-serif; color: #848586; font-size: 14px; padding:0px 0px 30px 50px;" width="160">'.$values[0]['customOptionName'].'</td>
//                                    <td style="font-family:Arial, Helvetica, sans-serif; color: #111315; font-size: 14px; padding:0px 0px 30px 0px;">'.$values[0]['variantValue'].'</td>
//                            </tr>';
                $variantText .= '<tr>
			<td style="color: #848586;" width="160">'.$this->getLanguageValue("lbl".$values[0]['customOptionName']).'</td>
			<td style="color: #111315;">'.$values[0]['variantValue'].'</td>
                            </tr>';
            }
            $variantText .= '</tbody>
</table>';
        $resProductSummaryImages  =   $ObjProduct->getProductImages(implode('_',$imagesetarr),'extr','yes',30,'thumb');
        $psarr	=	array('showroomID'=>$itemDetails['showroom'],'languageIDs'=>$languageIDs,'brandID' => $this->ObjCommon->brandID);
        $resShowroomDets	=	$ObjShowroom->getShowroom($psarr);
        $paramsBrand            = array(
                    'languageIDs' => $languageIDs,
                    'brandID'     => $getOrderDetails['brandID']
                );
        $brandInfo              = $ObjBrand->getBrand($paramsBrand);
        $ObjPaymentgateway              = new PaymentgatewayModel();
        $getPaymentSettingGroupDetails = $ObjPaymentgateway->getPaymentSettingGroupDetails($getOrderDetails['paymentSettingsGroupID']);
        $sendMailToAdmin = 'No';
        //Getting template
        if($getPaymentSettingGroupDetails['paySetGroupKey'] == 'NetworkOnline' || $getPaymentSettingGroupDetails['paySetGroupKey']=='Ngeniusonline'){
            $emailbody                = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-order-confirmation-admin');
            $ccMails    =   $this->getSettingValue('product_cart_settings', 'creditcard_cc');
			$sendMailToAdmin = $this->getSettingValue('product_cart_settings', 'enable_credit_card_cc');
        }
        else{
            $emailbody                = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-order-request-confirmation-admin');
            $ccMails    =   $this->getSettingValue('product_cart_settings', 'pay_at_showroom_cc');
			$sendMailToAdmin = $this->getSettingValue('product_cart_settings', 'enable_pay_at_showroom');
        }
        $showroomNotificationEmail  =   $resShowroomDets['notificationEmail'];
        $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');
        $emailbody            = $emailbody['emailHtml'];
        if(!empty($getOrderDetails['billingLastName'])) {
           //$getOrderDetails['billingLastName'] = $this->encryptDecrypt("decrypt",stripslashes($getOrderDetails['billingLastName']));
        }
        $subject        = stripslashes($subject);
        $userName       = stripslashes($getOrderDetails['subtitle']).stripslashes($getOrderDetails['billingFirstName']) . " " . stripslashes($getOrderDetails['billingLastName']);
        $bodytag        = str_replace('{$userFirstName}',$getOrderDetails['subtitle'].$getOrderDetails['billingFirstName'], $emailbody);
        $bodytag        = str_replace('{$userLastName}', $getOrderDetails['billingLastName'], $bodytag);
        $bodytag        = str_replace('{$variantlist}', $variantText, $bodytag);
        $bodytag        = str_replace('{$modelVariantCode}', $modelVariantCode, $bodytag);
        //$bodytag        = str_replace('{$variantlist}', $variantText, $bodytag);
        foreach ($itemDetails['customOptionValues'] as $values) {    
                $bodytag        = str_replace('{$'.$values[0]['customOptionName'].'}', $values[0]['variantValue'], $bodytag);
            }
        $bodytag        = str_replace('{$externalviewimage}', $resProductSummaryImages[0]['Imageslist'], $bodytag);
        $bodytag     = str_replace('{$productTitle}', $orderItems[0]['productOptionName'], $bodytag);
        $bodytag        = str_replace('{$franchisee}', stripslashes($brandInfo['brandName']), $bodytag);
        $bodytag        = str_replace('{$showroomName}', stripslashes($resShowroomDets['name']), $bodytag);
        $bodytag        = str_replace('{$showroomEmail}', stripslashes($resShowroomDets['email']), $bodytag);
		$phone = stripslashes(preg_replace('/\s+/', '', $resShowroomDets['phone']));
            $bodytag        = str_replace('{$showroomPhone}', '<a href="tel:'.$phone.'">'.$phone.'</a>', $bodytag);
            $bodytag        = str_replace('{$showroomAddress}', stripslashes(nl2br($resShowroomDets['address'])), $bodytag);
            $bodytag        = str_replace('{$showroomLatitude}', stripslashes($resShowroomDets['latitude']), $bodytag);
            $bodytag        = str_replace('{$showroomLongitude}', stripslashes($resShowroomDets['longitude']), $bodytag);
        $bodytag        = str_replace('{$userEmail}',stripslashes($getOrderDetails['customer_email']), $bodytag);
        $bodytag        = str_replace('{$userPhone}', stripslashes($getOrderDetails['billingPhone']), $bodytag);
         $bodytag        = str_replace('{$orderPaidAmount}', stripslashes($this->ObjView->getFormattedCurrency($getOrderDetails['orderPaidAmount'] , '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID'])), $bodytag);
        $bodytag        = str_replace('{$orderTotalAmount}', stripslashes($this->ObjView->getFormattedCurrency($getOrderDetails['orderTotalAmount'] , '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID'])), $bodytag);
        $bodytag     = str_replace('{$orderID}', $getOrderDetails['orderNumber'], $bodytag);
        $bodytag     = str_replace('{$siteUrl}', $siteUrl, $bodytag);
        $bodytag     = str_replace('{$companyLogo}', $companyLogo, $bodytag);
        $mailContent = $bodytag;
        $emailID     = stripslashes($getOrderDetails['customer_email']);
        $this->ObjView->assign('companyLogo', $companyLogo);
        $this->ObjView->assign('emailbody', $mailContent);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $this->ObjView->assign('siteName', $siteName);
        $this->ObjView->assign('userName', $userName);
        
        $body = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
        //send mail
		if($sendMailToAdmin=='Yes') { 
			$adminMail             = $this->getSettingValue('site_settings', 'global_notification_email');
			$ObjMail->IsHTML();
			try {
				if($showroomNotificationEmail!='') {
					$send = $ObjMail->sendMail($from, $showroomNotificationEmail, $subject, $body);
					$ObjMail->Send();
				}
				$ObjMail->ClearAddresses();
				$expccMails =   explode(',',$ccMails);
				for($i=0;$i<count($expccMails);$i++)
					$ObjMail->AddCC($expccMails[$i]);
				$send = $ObjMail->sendMail($from, $adminMail, $subject, $body);
				$ObjMail->Send();
				$ObjMail->ClearAddresses();
			}
			catch (Exception $e) {
				$error = $e->getMessage();
			}
		}
    }
	
    private function sendCashOnDeliveryMail($ObjMail, $getOrderDetails, $orderID, $ObjCart, $ObjEmailtemplate, $ObjCountry) {
        $languageIDs       = $this->ObjView->languageIDs;
        //get productOptionName using business languageIDs
        $siteName          = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl           = $this->getSettingValue('site_settings', 'global_http_url');
        $companyLogo       = $this->getSettingValue('company_information', 'company_logo');
        $resBusinessOrders = $ObjCart->getOrderDetails($orderID);
        $orderTaxDescription = '';
        if (!empty($resBusinessOrders)) {
            $purchasedCurrency = $getOrderDetails['purchasedCurrency'];
            $shippingInfo      = '';
            
            $shippingAddress          = unserialize($getOrderDetails['shippingAddress']);
            $shippingPhone            = $shippingAddress['shippingPhone'];
            unset($shippingAddress['shippingPhone']);
            unset($shippingAddress['shippingProvince']);
            $shippingAddress          = array_values($shippingAddress);        
            if (count($shippingAddress) > 0) {
                $shippingAdressFormat = '';
                $shippingAdressFormat .= $ObjCountry->getFormattedAddress($shippingAddress, $languageIDs);
                if($shippingPhone!='') {
                    $shippingAdressFormat .= '<br>PH: '.$shippingPhone;
                }
            }       
            
            $billingAdressFormat = '';
            $billingAdress       = array_slice(array_values(unserialize($getOrderDetails['billingAddress'])), 0, -2);
            $billingAdressFormat = $ObjCountry->getFormattedAddress($billingAdress, $languageIDs);
            foreach ($resBusinessOrders as $ordItems) {
                $orderDetailsBusiness                 = '';
                $languageIDsCustomBusiness            = $languageIDs;
                $languageIDsCustomBusiness['Current'] = $ordItems['businessDefaultLanguageID'];
                $emailbody                            = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustomBusiness, '', 'product-order-confirmation-admin');
                $emailbodyBus                         = $emailbody['emailHtml'];
                $orderInformationText                 = $this->getTemplateDetails('ORDER INFORMATION', $emailbodyBus);
                $orderInformationBusinessCopy         = '';
                $commonTemplate                       = $this->getTemplateDetails('COMMON INFORMATION', $emailbodyBus);
                $commonInformation                    = $commonTemplate;
                $getFreeProductsSubTotal              = $ObjCart->getFreeProductsSubTotal($ordItems['masterOrderID']);
                $totSubTotal                          = $ordItems['orderSubtotal'] + $getFreeProductsSubTotal;
                $commonTemplate                       = str_replace('{$orderSubtotal}', $this->ObjView->getFormattedCurrency($totSubTotal, '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                $otherTemplate                        = $this->getTemplateDetails('SHIPPING AMOUNT', $commonTemplate);
                
                if ($ordItems['shippingAmount'] > 0) {
                    $commonTemplate = str_replace('{$shippingAmount}', $this->ObjView->getFormattedCurrency($ordItems['shippingAmount'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                } else {
                    $commonTemplate = str_replace($otherTemplate, '', $commonTemplate);
                }
                $otherTemplate = $this->getTemplateDetails('SERVICE CHARGE', $commonTemplate);
                if ($ordItems['orderOtherServiceCharge'] > 0) {
                    $commonTemplate = str_replace('{$orderOtherServiceCharge}', $this->ObjView->getFormattedCurrency($ordItems['orderOtherServiceCharge'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                } else {
                    $commonTemplate = str_replace($otherTemplate, '', $commonTemplate);
                }
                $otherTemplate = $this->getTemplateDetails('CONVENIENT CHARGE', $commonTemplate);
                if ($ordItems['orderConvenientFee'] > 0) {
                        $commonTemplate = str_replace('{$orderConvenientFee}', $this->ObjView->getFormattedCurrency($ordItems['orderConvenientFee'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                } else {
                        $commonTemplate = str_replace($otherTemplate, '', $commonTemplate);
                }
                $otherTemplate = $this->getTemplateDetails('TAX AMOUNT', $commonTemplate);
                if ($ordItems['orderTaxAmount'] > 0) {
                    $commonTemplate = str_replace('{$orderTaxAmount}', $this->ObjView->getFormattedCurrency($ordItems['orderTaxAmount'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                } else {
                    $commonTemplate = str_replace($otherTemplate, '', $commonTemplate);
                }
                $otherTemplate = $this->getTemplateDetails('PROMO CODE', $commonTemplate);
                if ($getOrderDetails['orderPromoDiscountAmount'] > 0) {
                    if ($getOrderDetails['orderPromoCode'] != '') {
                        $commonTemplate = str_replace('{$orderPromoDiscountAmount}', '-' . $this->ObjView->getFormattedCurrency($ordItems['orderPromoDiscountAmount'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']) . ' (' . $getOrderDetails['orderPromoCode'] . ')', $commonTemplate);
                    } else {
                        $commonTemplate = str_replace('{$orderPromoDiscountAmount}', '-' . $this->ObjView->getFormattedCurrency($ordItems['orderPromoDiscountAmount'], '',$getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                    }
                } else {
                    $commonTemplate = str_replace($otherTemplate, '', $commonTemplate);
                }
                $otherTemplate = $this->getTemplateDetails('REDEEM POINT DISCOUNT AMOUNT', $commonTemplate);
                if ($getOrderDetails['redeemDiscountAmount'] > 0) {
                   $commonTemplate = str_replace('{$redeemDiscountAmount}',  '-' .$this->ObjView->getFormattedCurrency($getOrderDetails['redeemDiscountAmount'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                } else {
                    $commonTemplate = str_replace($otherTemplate, '', $commonTemplate);
                }
                //$commonTemplate = str_replace($otherTemplate, '', $commonTemplate);								
                $otherTemplate = $this->getTemplateDetails('USER CREDIT AMOUNT', $commonTemplate);
                if ($ordItems['orderUserCreditAmount'] > 0) {
                    $commonTemplate = str_replace('{$orderUserCreditAmount}', '-' . $this->ObjView->getFormattedCurrency($ordItems['orderUserCreditAmount'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                } else {
                    $commonTemplate = str_replace($otherTemplate, '', $commonTemplate);
                }
                //$commonTemplate  = str_replace($otherTemplate, '', $commonTemplate);	
                $commonTemplate             = str_replace('{$orderTotalAmount}', $this->ObjView->getFormattedCurrency($ordItems['orderTotalAmount']+$getFreeProductsSubTotal, '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $commonTemplate);
                //shipping information label
                $shippingLabelTemplate      = $this->getTemplateDetails('SHIPPING INFORMATION', $emailbodyBus);
                $shippingLabelTemplateValue = str_replace($shippingLabelTemplate, '', $shippingLabelTemplate);
                $ordItems['orderID']        = isset($ordItems['orderID']) ? $ordItems['orderID'] : 0;
                $orderedItemsBusiness       = $ObjCart->getOrderItemDetails($orderID, $languageIDsCustomBusiness, $ordItems['orderID']);
                if (!empty($orderedItemsBusiness)) {
                    foreach ($orderedItemsBusiness as $item) {
                        $tempStr     = '';
                        $unserialize = unserialize($item['extra']);
                        if($this->_taxCalculationParam['taxApplicable']=='Yes' && $unserialize['orderItemTaxDescription']!='') {
                            $orderTaxDescription = ' - '.$unserialize['orderItemTaxDescription'];
                        }
                        if (isset($unserialize['combinationValues']['customOption']) && count($unserialize['combinationValues']['customOption']) > 0) {
                            $tempStr = '<table width="100%" border="0" cellspacing="0" cellpadding="0">
							<tr><td colspan="2"><b>Combination</b></td></tr>
							<tr><td width="30%">SKU </td><td>' . $unserialize['combinationValues']['cimbinationSKU'] . '</td></tr>';
                            foreach ($unserialize['combinationValues']['customOption'] as $combination) {
                                $tempStr .= '<tr><td>' . $combination['customOptionName'] . '</td>
								<td>' . $combination['variantValue'] . '</td>
								</tr>';
                            }
                            $tempStr .= '</table>';
                        }
                        if (count($unserialize['customOptionValues']) > 0) {
                            $tempStr .= '<table width="100%" border="0" cellspacing="0" cellpadding="0">
							<tr><td colspan="2"><b>Options</b></td></tr>';
                            foreach ($unserialize['customOptionValues'] as $customOptionValues) {
                                $tempStr .= '<tr>
								<td width="30%">' . $customOptionValues['0']['customOptionName'] . '</td>';
                                foreach ($customOptionValues as $key => $customOption) {
                                    $varinant = $customOption['variantValue'];
                                    if ($key > 0) {
                                        $varinant .= ' ,';
                                    }
                                    ;
                                    $tempStr .= '<td>' . $varinant . '</td>';
                                }
                                $tempStr .= '</tr>';
                            }
                            $tempStr .= '</table>';
                        }
                        $optionSKU = '';
                        if (isset($item['optionSKU'])) {
                            $optionSKU = ' [SKU: ' . $item['optionSKU'] . ']';
                        }
                        if($item['sellAsBatch'] == 'Yes'){
                                $sellAsBathText =   "<br/> ".$this->getLanguageValue("lblSetof")." ".$item['qtyPerBatch']." ".$item['batchType']."<br/>";
                        }else{
                                $sellAsBathText =   "";
                        }
                        $orderDetailsBusiness = $orderInformationText;
                        $prodTitleStr        = preg_replace('/\s+/', ' ', trim($item['productTitle']));
                        $prodOptionStr       = preg_replace('/\s+/', ' ', trim($item['optionName']));
                        if ($prodTitleStr == $prodOptionStr) {
                            $orderDetailsBusiness = str_replace('{$productOptionName}', stripslashes($item['productTitle']) . $optionSKU . $tempStr." ".$sellAsBathText, $orderDetailsBusiness);
                        } else {
                            $orderDetailsBusiness = str_replace('{$productOptionName}', stripslashes($item['productTitle'] . " ( " . $item['optionName']) . " )" . $optionSKU . $tempStr." ".$sellAsBathText, $orderDetailsBusiness);
                        }
                        $otherTemplate        = $this->getTemplateDetails('GIFT', $orderDetailsBusiness);
                        $orderDetailsBusiness = str_replace($otherTemplate, '', $orderDetailsBusiness);
                        if($item['freeProduct']=='Yes' && $item['freeBaseProductID']>0) {
                            $orderDetailsBusiness = str_replace('{$orderItemPrice}', $this->ObjView->getFormattedCurrency($item['originalSubtotal']/$item['orderItemQuantity'], '', $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $orderDetailsBusiness);
                            $orderDetailsBusiness = str_replace('{$orderItemSubtotal}', $this->ObjView->getFormattedCurrency($item['originalSubtotal'], '',$getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $orderDetailsBusiness);
                        } else {
                            $orderDetailsBusiness = str_replace('{$orderItemPrice}', $this->ObjView->getFormattedCurrency($item['orderItemPrice'], '',$getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $orderDetailsBusiness);
                            $orderDetailsBusiness = str_replace('{$orderItemSubtotal}', $this->ObjView->getFormattedCurrency($item['orderItemSubtotal'], '',$getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']), $orderDetailsBusiness);
                        }                        
                        $orderDetailsBusiness = str_replace('{$orderItemQuantity}', $item['orderItemQuantity'], $orderDetailsBusiness);                        
                        $orderInformationBusinessCopy .= $orderDetailsBusiness;
                    }
                }
                if ($getOrderDetails['orderTaxAmount'] > 0) {
                    $commonTemplate = str_replace('{$orderTaxDescription}', $orderTaxDescription, $commonTemplate);
                }
                $businessMailID = $ordItems['businessEmail'];
                $from           = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $subject        = $emailbody['emailSubject'];
                $ObjMail->ClearAddresses();
                $bodytag         = $emailbody['emailHtml'];
                //shipping info
                /*
                $bodytag  = str_replace($shippingLabelTemplate, $shippingLabelTemplateValue,
                $bodytag);
                */
                $bodytag         = str_replace('{$shippingInfo}', ' <br /> ' . $shippingAdressFormat, $bodytag);
                //billing details
                $bodytag         = str_replace('{$billingAddress}', ' <br /> ' . $billingAdressFormat, $bodytag);
                $billingInfo     = unserialize($getOrderDetails['billingAddress']);
                $bodytag         = ($billingInfo['billingPhone'] != '') ? str_replace('{$billingPhone}', stripslashes($billingInfo['billingPhone']), $bodytag) : preg_replace('#(' . preg_quote('<!--PHONE NUMBER BEGIN-->') . ')(.*)(' . preg_quote('<!--PHONE NUMBER END-->') . ')#si', '', $bodytag);
                $bodytag         = ($billingInfo['billingEmail'] != '') ? str_replace('{$billingEmail}', stripslashes($billingInfo['billingEmail']), $bodytag) : preg_replace('#(' . preg_quote('<!--EMAILID BEGIN-->') . ')(.*)(' . preg_quote('<!--EMAILID END-->') . ')#si', '', $bodytag);
                //order information
                $bodytag         = str_replace('{$orderNumber}', $getOrderDetails['orderNumber'], $bodytag);
                $bodytag         = str_replace($orderInformationText, $orderInformationBusinessCopy, $bodytag);
                $bodytag         = str_replace($commonInformation, $commonTemplate, $bodytag);
                //payment information not needed for business
                $paymentTemplate = $this->getTemplateDetails('PAYMENT', $bodytag);
                $bodytag         = str_replace($paymentTemplate, '', $bodytag);
                $bodytag         = str_replace('{$userName}', $emailbody['emailFromName'], $bodytag);
                $bodytag         = str_replace('{$siteUrl}', $siteUrl, $bodytag);
                $bodytag         = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $mailContent     = $bodytag;
                $this->ObjView->assign('emailbody', $mailContent);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $body = $this->ObjCommon->fetch("email_templates/OrderMail.tpl", $languageIDsCustomBusiness);
               
                //send mail
                $ObjMail->IsHTML();
                try {
                    $send = $ObjMail->sendMail(array(
                        $emailbody['emailFromEmail'],
                        $emailbody['emailFromName']
                    ), $businessMailID, $subject, $body);
                    $ObjMail->Send();
                    $ObjMail->ClearAddresses();
                }
                catch (Exception $e) {
                    $error = $e->getMessage();
                }
            }
        }
    }
    private function sendProductOutOfStock($ObjMail, $getOrderDetails, $orderID, $ObjCart, $ObjEmailtemplate) {
        $languageIDs                       = $this->ObjView->languageIDs;
        $siteName                          = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl                           = $this->getSettingValue('site_settings', 'global_http_url');
        $companyLogo                       = $this->getSettingValue('company_information', 'company_logo');
        //Admin LanguageID
        $languageIDsCustomAdmin            = $languageIDs;
        $languageIDsCustomAdmin['Current'] = $languageIDs['Default'];
        $outOfStockProducts                = $ObjCart->checkProductOutOfStock($languageIDs, $orderID);
        if (count($outOfStockProducts) > 0) {
            $emailTempDetRes = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustomAdmin, '', 'product-out-of-stock');
            $emailFrom       = array(
                $emailTempDetRes['emailFromEmail'],
                $emailTempDetRes['emailFromName']
            );
            foreach ($outOfStockProducts as $key => $value) {
                $emailTempDet          = $emailTempDetRes;
                $adminMail             = $this->getSettingValue('site_settings', 'global_notification_email');
                $unseralizedBillingAdd = unserialize($getOrderDetails['billingAddress']);
                $toEmailID             = $adminMail;
                $Subject               = $emailTempDet['emailSubject'];
                $Body                  = $emailTempDet['emailHtml'];
                $Body                  = str_replace('{$orderID}', $getOrderDetails['orderNumber'], $Body);
                $Body                  = str_replace('{$cName}', $unseralizedBillingAdd['billingFirstName'] . " " . $unseralizedBillingAdd['billingLastName'], $Body);
                $settingsDateFormat    = $this->getSettingValue("site_settings", "date_format");
                $settingsTimeFormat    = $this->getSettingValue("site_settings", "time_format");
                $outOfStockOrderDate   = new DateTime($getOrderDetails['orderStatusDate']);
                $outOfStockOrderTime   = new DateTime($getOrderDetails['orderStatusDate']);
                switch ($settingsDateFormat) {
                    case '%A, %B %e, %Y':
                        $outOfStockOrderDate = date_format($outOfStockOrderDate, 'l F d, Y');
                        break;
                    case '%B %e, %Y':
                        $outOfStockOrderDate = date_format($outOfStockOrderDate, 'F d, Y');
                        break;
                    case '%m/%d/%Y':
                        $outOfStockOrderDate = date_format($outOfStockOrderDate, 'm/d/Y');
                        break;
                    case '%d/%m/%Y':
                        $outOfStockOrderDate = date_format($outOfStockOrderDate, 'd/m/Y');
                        break;
                    case '%d-%m-%Y':
                        $outOfStockOrderDate = date_format($outOfStockOrderDate, 'd-m-Y');
                        break;
                    case '%Y-%m-%d':
                        $outOfStockOrderDate = date_format($outOfStockOrderDate, 'Y-m-d');
                        break;
                    default:
                        $outOfStockOrderDate = date_format($outOfStockOrderDate, 'M d, Y');
                }
                switch ($settingsTimeFormat) {
                    case '%I:%M %p':
                        $outOfStockOrderTime = date_format($outOfStockOrderTime, 'h:i A');
                        break;
                    case '%l:%M %p':
                        $outOfStockOrderTime = date_format($outOfStockOrderTime, 'g:i A');
                        break;
                    case '%H:%M':
                        $outOfStockOrderTime = date_format($outOfStockOrderTime, 'G:i');
                        break;
                    default:
                        $outOfStockOrderTime = date_format($outOfStockOrderTime, 'h:i A');
                }
                $outOfStockOrderDateTime = $outOfStockOrderDate . "," . $outOfStockOrderTime;
                $Body                    = str_replace('{$date}', $outOfStockOrderDateTime, $Body);
                $Body                    = str_replace('{$product}', $value[0]['productTitle'], $Body);
                $outOpt                  = '';
                foreach ($value as $subItem) {
//                    $outOpt .= "<li>: '" . $subItem['optName'] . "'</li><br/>";
                     $outOpt =  $subItem['optName'];
                }
                $Body = str_replace('{$outOpt}', $outOpt, $Body);
                $this->ObjView->assign('emailbody', $Body);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $email_body = $this->ObjCommon->fetch('email_templates/Layout.tpl', $languageIDsCustomAdmin);
                try {
                    $ObjMail->IsHTML();
                    $ObjMail->sendMail($emailFrom, $toEmailID, $Subject, $email_body);
                    $ObjMail->Send();
                }
                catch (Exception $e) {
                    $e->getMessage();
                }
            }
        }
    }
    public function setCartAction() {
        $ObjCart        = new CartModel();
        $id             = $this->getRequestValue("id");
        $notificationID = $this->decodeString($id);
        $resDetails     = $ObjCart->getNotificationDetails($notificationID);
        $cartID         = $resDetails['cartID'];
        //echo '--'.$cartID;
        $resCart        = $ObjCart->getCartDetails($cartID);
        $ObjCart->updateCartUserID($cartID, 0);
        //echo '<pre>';print_r($resCart);
        $validatedCart = $this->validateCart($resCart, 'No');
        //echo '<pre>';print_r($validatedCart);exit;
        /*
        if(count($validatedCart['error'])>0 || empty($validatedCart['items']))
        {
        $ObjCart->clearCart($cartID);
        $this->setMessage("language.errCartExpired",$div_class = "error",
        $section = 'Subscribe',$div_id = 'common_message');
        $this->setRedirect("/index/");
        }
        else
        {
        */
        $extra         = unserialize($resDetails['extra']);
        if ($extra['discount'] > 0) {
            $this->ObjCookie->setCookie("EMAIL_CAMPAIGN_USER", $resCart['userEmail']);
            $this->ObjCookie->setCookie("EMAIL_NOTIFICATION_ID", (int) $notificationID);
            $this->ObjCookie->setCookie("EMAIL_CAMPAIGN_ID", 0);
        }
        //For clear the current login
        $this->ObjSession->unsetSession("REGISTERED_USER_ID");
        $this->ObjCookie->unsetCookie('SUBSCRIBED_USER');
        $this->ObjSession->setSession("CARTID", $this->encodeString($cartID));
        $this->setRedirect('/cart/');
        /*
        }
        */
    }
public function createOrder($resCart, $orderType = 'sigle', $orderCount = 0) {
        $ObjCart                  = new CartModel();
        $ObjPaymentgateway        = new PaymentgatewayModel();
        $finalArray               = array();
        $finalArray['items']      = array();
        $cartExtraData            = unserialize($resCart['extra']);
        $cartcurrencyId           = $resCart['currencyID'];
        $defaultCurrencyId        = $this->ObjView->_defaultCurrency;
        $languageIDs              = $this->ObjView->languageIDs;
        $ordersubTotal            = 0;
        $orderCommissionAmount    = 0;
        $orderOtherServiceCharge  = 0;
        $orderItemQuantity        = 0;
        $orderShippingAmount      = 0;
	$orderConvenientFee       = 0;
        $orderTaxAmount           = 0;
        $orderPromoDiscountAmount = 0;
        foreach ($resCart['items'] as $key => $items) {
            $params[0]       = 'shippingSetting';
            $params[1]       = 'taxPayableToBusiness';
            $params[2]       = 'businessID';
            $productDetails  = $ObjCart->getProductProperties($items['productID'], $params);
            $unserializeData = unserialize($items['itemDetails']); 
            if($resCart['parentOrderID']>0) {
                $unserializeData['orderConvenientFee'] = 0;
            }
            $calcItemPrice  =   $items['actualPrice'];
            if($this->_taxCalculationParam["inclusive_tax"]=='Yes' && $productDetails['taxPayableToBusiness'] != 'Yes' && $unserializeData['isTaxable']=='Yes' && $unserializeData['orderItemTaxRate']>0) {
                $taxBusinessAmount      = (($items['actualPrice'] - $items['actualPrice'] / 100) * $unserializeData['orderItemTaxRate']) / 100;
                $taxBusinessAmount      =  $taxBusinessAmount > 0 ? $taxBusinessAmount : 0.00;                    
                $calcItemPrice          =  $calcItemPrice - $taxBusinessAmount;
            }
            if ($productDetails['shippingSetting'] == 'admin') {
                $businessPayment = (($calcItemPrice * $items['orderItemQuantity']) + $unserializeData['orderOtherServiceCharge']) - $unserializeData['orderCommissionAmount'];
            } else {
                $businessPayment = (($calcItemPrice * $items['orderItemQuantity']) + $unserializeData['orderOtherServiceCharge'] + $unserializeData['shippingAmount']) - $unserializeData['orderCommissionAmount'];
            }
            if ($productDetails['taxPayableToBusiness'] == 'Yes' && $this->_taxCalculationParam["inclusive_tax"]!='Yes') {
                $businessPayment = $businessPayment + $unserializeData['orderTaxAmount'];
            }
            
            $unserializeData['businessPayment']                           = $businessPayment;                 
            $unserializeData['orderPaymentGatewayCharge']                 = 0;
            //Admin amount details
            $unserializeData['amountDetails']['admin']['subTotal']        = $this->ObjView->convertValueCustom($items['orderItemSubtotal'], $cartcurrencyId, $defaultCurrencyId);
            $unserializeData['amountDetails']['admin']['serviceCharge']   = $this->ObjView->convertValueCustom($unserializeData['orderOtherServiceCharge'], $cartcurrencyId, $defaultCurrencyId);
            $unserializeData['amountDetails']['admin']['commission']      = $this->ObjView->convertValueCustom($unserializeData['orderCommissionAmount'], $cartcurrencyId, $defaultCurrencyId);
            $unserializeData['amountDetails']['admin']['ccCharge']        = $this->ObjView->convertValueCustom($unserializeData['orderPaymentGatewayCharge'], $cartcurrencyId, $defaultCurrencyId);
            $unserializeData['amountDetails']['admin']['tax']             = $this->ObjView->convertValueCustom($unserializeData['orderTaxAmount'], $cartcurrencyId, $defaultCurrencyId);
            $unserializeData['amountDetails']['admin']['shippingAmount']  = $this->ObjView->convertValueCustom($unserializeData['shippingAmount'], $cartcurrencyId, $defaultCurrencyId);
            $unserializeData['amountDetails']['admin']['convenientFee']   = $this->ObjView->convertValueCustom($unserializeData['orderConvenientFee'], $cartcurrencyId, $defaultCurrencyId);
			$unserializeData['amountDetails']['admin']['businessPayment'] = $this->ObjView->convertValueCustom($businessPayment, $cartcurrencyId, $defaultCurrencyId);
            $unserializeData['amountDetails']['admin']['totalAmount']     = $this->ObjView->convertValueCustom($unserializeData['orderItemTotal'], $cartcurrencyId, $defaultCurrencyId);
            $defaultLangageID                                             = $languageIDs['Default'];
            $adminLamguageIDS['Default']                                  = $defaultLangageID;
            $adminLamguageIDS['Current']                                  = $defaultLangageID;
            $productOptionName                                            = $ObjCart->getProductOptionTitle($items['productOptionID'], $defaultLangageID);
            $productTitle                                                 = $ObjCart->getProductTitle($items['productID'], $defaultLangageID);
            //Item details in admin and user language
            $unserializeData['itemDetails']['user']['productOptionName']  = $unserializeData['productOptionName'];
            $unserializeData['itemDetails']['user']['productTitle']       = $unserializeData['productTitle'];
            $unserializeData['itemDetails']['admin']['productTitle']      = ($productTitle != '') ? $productTitle : $unserializeData['productTitle'];
            $unserializeData['itemDetails']['admin']['productOptionName'] = ($productOptionName != '') ? $productOptionName : $unserializeData['productOptionName'];
            if (isset($unserializeData['combinationValues']['customOption']) && count($unserializeData['combinationValues']['customOption']) > 0) {
                foreach ($unserializeData['combinationValues']['customOption'] as $key => $combination) {
                    $resCustomOptionDetails                                                                  = $ObjCart->getProductCustomOptions(0, $combination['customOptionID'], $adminLamguageIDS);
                    $unserializeData['combinationValues']['customOption'][$key]['admin']['customOptionName'] = $resCustomOptionDetails['customOptionName'];
                    $resCustomOptionDetails                                                                  = $ObjCart->getProductCustomOptionVariant($combination['customOptionVariantID'], $adminLamguageIDS);
                    $unserializeData['combinationValues']['customOption'][$key]['admin']['variantValue']     = $resCustomOptionDetails['value'];
                }
            }
            if (count($unserializeData['customOptionValues']) > 0) {
                foreach ($unserializeData['customOptionValues'] as $key1 => $customOptionValues) {
                    foreach ($customOptionValues as $key2 => $customOption) {
                        $resCustomOptionDetails                                                           = $ObjCart->getProductCustomOptions(0, $customOption['customOptionID'], $adminLamguageIDS);
                        $unserializeData['customOptionValues'][$key1][$key2]['admin']['customOptionName'] = $resCustomOptionDetails['customOptionName'];
                        if ($customOption['customOptionVariantID'] > 0) {
                            $resCustomOptionDetailsAdmin = $ObjCart->getProductCustomOptionVariant($customOption['customOptionVariantID'], $adminLamguageIDS);
                            if ($resCustomOptionDetails['priceDiffType'] == 'I' && $resCustomOptionDetails['priceDiff'] > 0) {
                                $variantValue     = $this->ObjView->getFormattedCurrency($resCustomOptionDetails['priceDiff'], '', 0, $resCart['currencyID']);
                                $variantValueText = $resCustomOptionDetailsAdmin['value'] . " ( + " . $variantValue . " )";
                            } else if ($resCustomOptionDetails['priceDiffType'] == 'D' && $resCustomOptionDetails['priceDiff'] > 0) {
                                $variantValue     = $this->ObjView->getFormattedCurrency($resCustomOptionDetails['priceDiff'], '', 0, $resCart['currencyID']);
                                $variantValueText = $resCustomOptionDetailsAdmin['value'] . " ( - " . $variantValue . " )";
                            } else {
                                $variantValueText = $resCustomOptionDetailsAdmin['value'];
                            }
                            $unserializeData['customOptionValues'][$key1][$key2]['admin']['variantValue'] = $variantValueText;
                        } else {
                            if ($resCustomOptionDetails['priceDiffType'] == 'I' && $resCustomOptionDetails['priceDiff'] > 0) {
                                $variantValue     = $this->ObjView->getFormattedCurrency($resCustomOptionDetails['priceDiff'], '', 0, $resCart['currencyID']);
                                $variantValueText = $customOption['variantValueText'] . " ( + " . $variantValue . " )";
                            } else if ($resCustomOptionDetails['priceDiffType'] == 'D' && $resCustomOptionDetails['priceDiff'] > 0) {
                                $variantValue     = $this->ObjView->getFormattedCurrency($resCustomOptionDetails['priceDiff'], '', 0, $resCart['currencyID']);
                                $variantValueText = $customOption['variantValueText'] . " ( - " . $variantValue . " )";
                            } else {
                                $variantValueText = $customOption['variantValueText'];
                            }
                            $unserializeData['customOptionValues'][$key1][$key2]['variantValue']          = $variantValueText;
                            $unserializeData['customOptionValues'][$key1][$key2]['admin']['variantValue'] = $variantValueText;
                        }
                    } 
                }
            }
            
            $items['itemDetails'] = serialize($unserializeData);
            if ($productDetails['shippingSetting'] == 'admin') {
                $shippingSetting = 'admin';
            } else {
                $shippingSetting = 'business';
            }
            if ($productDetails['taxPayableToBusiness'] == 'Yes') {
                $taxSetting = 'business';
            } else {
                $taxSetting = 'admin';
            }
            $items['shippingSetting']                                                                           = $shippingSetting;
            $items['taxSetting']                                                                                = $taxSetting;
            $business_id                                                                                        = $items['businessID'];
            $finalArray['items'][$business_id]['subItem']                                                       = isset($finalArray['items'][$business_id]['subItem']) ? $finalArray['items'][$business_id]['subItem'] : array();
            $finalArray['items'][$business_id]['subItem'][count($finalArray['items'][$business_id]['subItem'])] = $items;
            $finalArray['items'][$business_id]['businessPayment']                                               = isset($finalArray['items'][$business_id]['businessPayment']) ? $finalArray['items'][$business_id]['businessPayment'] : 0;
            $finalArray['items'][$business_id]['businessPayment'] += $businessPayment;
            //Order based toals for serilized
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['subTotal'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['subTotal']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['subTotal'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['subTotal'] += $this->ObjView->convertValueCustom($items['orderItemSubtotal'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['serviceCharge'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['serviceCharge']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['serviceCharge'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['serviceCharge'] += $this->ObjView->convertValueCustom($unserializeData['orderOtherServiceCharge'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['commission'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['commission']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['commission'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['commission'] += $this->ObjView->convertValueCustom($unserializeData['orderCommissionAmount'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['ccCharge'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['ccCharge']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['ccCharge'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['ccCharge'] += $this->ObjView->convertValueCustom($unserializeData['orderPaymentGatewayCharge'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['tax'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['tax']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['tax'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['tax'] += $this->ObjView->convertValueCustom($unserializeData['orderTaxAmount'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['shippingAmount'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['shippingAmount']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['shippingAmount'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['shippingAmount'] += $this->ObjView->convertValueCustom($unserializeData['shippingAmount'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['businessPayment'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['businessPayment']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['businessPayment'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['businessPayment'] += $this->ObjView->convertValueCustom($businessPayment, $cartcurrencyId, $defaultCurrencyId);
			$finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['convenientFee'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['convenientFee']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['convenientFee'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['convenientFee'] += $this->ObjView->convertValueCustom($unserializeData['orderConvenientFee'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['orderTotalAmount'] = isset($finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['orderTotalAmount']) ? $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['orderTotalAmount'] : 0;
            $finalArray['items'][$business_id]['orderBasedUnserializedData']['amountDetails']['admin']['orderTotalAmount'] += $this->ObjView->convertValueCustom($unserializeData['orderItemTotal'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['convertedBusinessPayment'] = isset($finalArray['items'][$business_id]['convertedBusinessPayment']) ? $finalArray['items'][$business_id]['convertedBusinessPayment'] : 0;
            $finalArray['items'][$business_id]['convertedBusinessPayment'] += $this->ObjView->convertValueCustom($businessPayment, $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['convertedOrderTotalAmount'] = isset($finalArray['items'][$business_id]['convertedOrderTotalAmount']) ? $finalArray['items'][$business_id]['convertedOrderTotalAmount'] : 0;
            $finalArray['items'][$business_id]['convertedOrderTotalAmount'] += $this->ObjView->convertValueCustom($unserializeData['orderItemTotal'], $cartcurrencyId, $defaultCurrencyId);
            $finalArray['items'][$business_id]['orderItemSubtotal'] = isset($finalArray['items'][$business_id]['orderItemSubtotal']) ? $finalArray['items'][$business_id]['orderItemSubtotal'] : 0;
            $finalArray['items'][$business_id]['orderItemSubtotal'] += $items['orderItemSubtotal'];
            $finalArray['items'][$business_id]['orderQty'] = isset($finalArray['items'][$business_id]['orderQty']) ? $finalArray['items'][$business_id]['orderQty'] : 0;
            $finalArray['items'][$business_id]['orderQty'] += $items['orderItemQuantity'];
            $finalArray['items'][$business_id]['orderTaxAmount'] = isset($finalArray['items'][$business_id]['orderTaxAmount']) ? $finalArray['items'][$business_id]['orderTaxAmount'] : 0;
            $finalArray['items'][$business_id]['orderTaxAmount'] += $unserializeData['orderTaxAmount'];
            $finalArray['items'][$business_id]['orderCommissionAmount'] = isset($finalArray['items'][$business_id]['orderCommissionAmount']) ? $finalArray['items'][$business_id]['orderCommissionAmount'] : 0;
            $finalArray['items'][$business_id]['orderCommissionAmount'] += $unserializeData['orderCommissionAmount'];
            $finalArray['items'][$business_id]['orderPaymentGatewayCharge'] = isset($finalArray['items'][$business_id]['orderPaymentGatewayCharge']) ? $finalArray['items'][$business_id]['orderPaymentGatewayCharge'] : 0;
            $finalArray['items'][$business_id]['orderPaymentGatewayCharge'] += $unserializeData['orderPaymentGatewayCharge'];
            $finalArray['items'][$business_id]['orderOtherServiceCharge'] = isset($finalArray['items'][$business_id]['orderOtherServiceCharge']) ? $finalArray['items'][$business_id]['orderOtherServiceCharge'] : 0;
            $finalArray['items'][$business_id]['orderOtherServiceCharge'] += $unserializeData['orderOtherServiceCharge'];
            $finalArray['items'][$business_id]['orderTotalAmount'] = isset($finalArray['items'][$business_id]['orderTotalAmount']) ? $finalArray['items'][$business_id]['orderTotalAmount'] : 0;
            $finalArray['items'][$business_id]['orderTotalAmount'] += $unserializeData['orderItemTotal'];
            $finalArray['items'][$business_id]['shippingAmount'] = isset($finalArray['items'][$business_id]['shippingAmount']) ? $finalArray['items'][$business_id]['shippingAmount'] : 0;
            $finalArray['items'][$business_id]['shippingAmount'] += $unserializeData['shippingAmount'];
			$finalArray['items'][$business_id]['convenientFee'] = isset($finalArray['items'][$business_id]['convenientFee']) ? $finalArray['items'][$business_id]['convenientFee'] : 0;
            $finalArray['items'][$business_id]['convenientFee'] += $unserializeData['orderConvenientFee'];
            $ordersubTotal += ($items['orderItemPrice'] * $items['orderItemQuantity']);
            $serializedData = unserialize($items['itemDetails']);
            if($resCart['parentOrderID']>0) {
                $serializedData['orderConvenientFee'] = 0;
            }
            $orderCommissionAmount += $serializedData['orderCommissionAmount'];
            $orderOtherServiceCharge += $serializedData['orderOtherServiceCharge'];
            $orderItemQuantity += $serializedData['orderItemQuantity'];
            $orderShippingAmount += $serializedData['shippingAmount'];
            $orderTaxAmount += $serializedData['orderTaxAmount'];
			$orderConvenientFee+=$serializedData['orderConvenientFee'];
            $orderPromoDiscountAmount += (isset($serializedData['orderPromoDiscountAmount']) ? $serializedData['orderPromoDiscountAmount'] : 0);
            unset($items);
        }
		//for COD
        if($_POST['paymentSettingsGroupKey']!='CashOnDeliveryRedemption') {
            $orderConvenientFee = 0; 
        } 
        if($resCart['parentOrderID']>0) {
            $orderConvenientFee = 0; 
        }
        
        $orderTotal         = ($ordersubTotal + $orderOtherServiceCharge + $orderShippingAmount + $addTaxAmount+ $orderConvenientFee) - ($orderPromoDiscountAmount);
        $temptotal          = $orderTotal;
        $completeOrderTotal = ($resCart['orderSubtotal'] + $resCart['orderOtherServiceCharge'] + $resCart['shippingAmount']+$resCart['orderConvenientFee']);
        //$completeOrderTotal = $completeOrderTotal + ($this->_taxCalculationParam["inclusive_tax"]=='Yes')?0:$resCart['orderTaxAmount'];
        if($this->_taxCalculationParam["inclusive_tax"]=='Yes'){
            $completeOrderTotal = $completeOrderTotal;
        }else{
            $completeOrderTotal = $completeOrderTotal + $resCart['orderTaxAmount'];
        }
        $completeOrderTotal = $completeOrderTotal - $resCart['orderPromoDiscountAmount'];
        if ($orderType == 'sigle') {
            $userCreditAmount = $resCart['orderUserCreditAmount'];
        } else {
            $userCreditAmount = $resCart['orderUserCreditAmount'] * ($temptotal / $completeOrderTotal);
        }
        $orderUserCreditAmount    = ($userCreditAmount > $orderTotal) ? $orderTotal : $userCreditAmount;
        $tot_without_dis          = ($ordersubTotal + $orderOtherServiceCharge + $orderShippingAmount + $addTaxAmount+ $orderConvenientFee);
        $orderPromoDiscountAmount = ($orderPromoDiscountAmount > $tot_without_dis) ? $tot_without_dis : $orderPromoDiscountAmount;
        $orderTotal               = $orderTotal - $orderUserCreditAmount;
		
		 
		 $userRedemedPointAmount = 0;
		 $userRedemedPoint = 0;

	
        $orderTotal               = ((int) $orderTotal <= 0) ? 0 : $orderTotal;
        $paymentSettingsGroupKey  = (isset($_POST['paymentSettingsGroupKey']) ? $_POST['paymentSettingsGroupKey'] : '');
        if ($paymentSettingsGroupKey != '' && $resCart['orderTotalAmount'] > 0) {
            $checkPaymentMethod = $ObjPaymentgateway->checkPaymentMethod(0, 'cart', $paymentSettingsGroupKey);
            if ($checkPaymentMethod['paySetGroupID'] < 1) {
                $this->setMessage($this->getLanguageValue("errPaymentMethod"), 'error');
                $this->setRedirect("/cart/checkout/");
            }
        } else {
            $checkPaymentMethod['paySetGroupID']    = 0;
            $checkPaymentMethod['paySetGroupLabel'] = 'Account Credit';
        }
        if($paymentSettingsGroupKey == 'NetworkOnline' || $paymentSettingsGroupKey=='Ngeniusonline'){
             $minimum_order_amount   = $this->getSettingValue('product_cart_settings', 'minimum_order_amount');
             $finalArray['orderPaidAmount']  		  = $minimum_order_amount;
        }else{
            $finalArray['orderPaidAmount']  		  = 0;
        }
	$finalArray['orderConvenientFee']  		  = $orderConvenientFee;
        $finalArray['orderTotalAmount']                   = $orderTotal;
        $finalArray['convertedMasterOrderSubTotalAmount'] = $this->ObjView->convertValueCustom($ordersubTotal, $cartcurrencyId, $defaultCurrencyId);
        $finalArray['convertedMasterOrderTotalAmount']    = $this->ObjView->convertValueCustom($orderTotal, $cartcurrencyId, $defaultCurrencyId);
        $finalArray['convertedOrderPromoDiscountAmount']  = $this->ObjView->convertValueCustom($orderPromoDiscountAmount, $cartcurrencyId, $defaultCurrencyId);
        $finalArray['convertedOrderUserCreditAmount']     = $this->ObjView->convertValueCustom($userCreditAmount, $cartcurrencyId, $defaultCurrencyId);
        $finalArray['orderSubtotal']                      = $ordersubTotal;
        $finalArray['promoID']                            = $resCart['promoID'];
        $finalArray['orderPromoCode']                     = $resCart['orderPromoCode'];
        $finalArray['orderPromoDiscountAmount']           = $orderPromoDiscountAmount;
        $finalArray['userCreditAmount']                   = $userCreditAmount;
		$finalArray['redeemPoint']                        = $userRedemedPoint;
        $finalArray['redeemDiscountAmount']               = $userRedemedPointAmount;
        $finalArray['userID']                             = $resCart['userID'];
        $finalArray['currencyID']                         = $resCart['currencyID'];
        $finalArray['brandID']                            = $resCart['brandID'];
        $finalArray['paymentSettingsGroupID']             = $checkPaymentMethod['paySetGroupID'];
        $finalArray['orderPaymentMethodName']             = $checkPaymentMethod['paySetGroupLabel'];
        $finalArray['paymentType']                        = $resCart['authType'];
        $finalArray['orderStatus']                        = $resCart['orderStatus'];
        $finalArray['paymentStatus']                      = $resCart['paymentStatus'];
        $finalArray['billingAddress']                     = $this->escape(serialize($cartExtraData['userBillingAddress']), FALSE, FALSE);
        $finalArray['shippingDeliveryAddress']            = $this->escape(serialize($cartExtraData['userShippingAddress']), FALSE, FALSE);
        $finalArray['userCheckoutEmail']                  = $this->escape($cartExtraData['userCheckoutEmail'], FALSE, FALSE);
        $finalArray['netpayOrderID']                      = '0';
        $finalArray['netpayPaymentType']                  = '';
        if ($resCart['orderTotalAmount'] > 0) {
            $finalArray['orderHold'] = 'Yes';
        } else {
            $finalArray['orderHold'] = 'No';
        }
        $finalArray['userName']        = $resCart['userFirstName'];//$this->encryptDecrypt("encrypt",$resCart['userFirstName']);
        $finalArray['userEmail']       = $resCart['userEmail'];//$this->encryptDecrypt("encrypt",$resCart['userEmail']);
        //$finalArray['userName']        = $_POST['username'];
        //$finalArray['userEmail']       = $_POST['useremail'];
        $finalArray['subtitle']        = $resCart['subtitle'];
        //$finalArray['billingPhone']    = $_POST['userphone'];
        $finalArray['billingPhone']    = "+".$resCart['userPhone'];//$this->encryptDecrypt("encrypt",$resCart['userPhone']);
        $finalArray['masterOrderQty']  = $orderItemQuantity; 
        $finalArray['cityID']          = 0;
        $finalArray['parentOrderID']   = isset($resCart['parentOrderID']) ? $resCart['parentOrderID'] : 0;
        $finalArray['shippingSetting'] = $shippingSetting;
        $finalArray['taxSetting']      = $taxSetting;
        $finalArray['languageID']      = $languageIDs['Current'];
        $finalArray['platform']     = $this->ObjCommon->_platform;
        $finalArray['businessID']      = $resCart['businessID'];
        $finalArray['invoice_prefix']  = $this->getSettingValue('product_cart_settings', 'invoice_number_prefix'); 
        $finalArray['userCurrencyID']            = $resCart['userCurrencyID'];
        $finalArray['userCurrencyExcRate']      = $resCart['userCurrencyExcRate'];
        $finalArray['showroomID']          = isset($resCart['showroomID']) ? $resCart['showroomID'] : 0;
        $order_id                      = $ObjCart->createOrder($finalArray); 
        return $order_id;
    }
    // Function for server side validation of the cart
    public function checkCombinationAttribute($cartItemRow) {
        $ObjCart                     = new CartModel();
        $unserailzedData             = unserialize($cartItemRow['itemDetails']);
        $combinationHash             = $unserailzedData['combinationHash'];
        $combinationValues           = $unserailzedData['combinationValues'];
        $customOptionValues          = $unserailzedData['customOptionValues'];
        $bundleProd                  = isset($unserailzedData['bundleProduct']) ? $unserailzedData['bundleProduct'] : "";
        $languageIDs                 = $this->ObjView->languageIDs;
        $productOptionPrice          = $ObjCart->getProductOptionPrice($cartItemRow['productOptionID']);
        $extra_price                 = 0;
        $combinationCustomOption     = 0;
        $returnArray                 = array();
        $product_option_id           = $cartItemRow['productOptionID'];
        $user_group_id               = (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID;
        $params['cart_id']           = $cartItemRow['cartID'];
        $params['product_option_id'] = $product_option_id;
        $params['user_group_id']     = $user_group_id;
        $params['curr_business_id']  = $cartItemRow['businessID'];
        $result                      = $ObjCart->getCartItemPrice($params);
        $tier_price                  = $ObjCart->getVariantTiePrice($params);
        if ($combinationHash != '' && count($combinationValues['customOption']) > 0) {
            $combination = $ObjCart->getCombination($combinationHash,0,$cartItemRow['businessID']);
            if (count($combination) > 0) {
                $combinationArray = explode('_', $combination['combination']);
                $customOptionID   = $combinationArray[0];
                unset($combinationArray[0]);
                $combinationArray = array_flip($combinationArray);
                if (count($combinationArray) == count($combinationValues['customOption'])) {
                    foreach ($combinationValues['customOption'] as $key => $items) {
                        $combinationAttributes[$items['customOptionID']]       = $items['customOptionID'];
                        $combinationAttributeVariant[$items['customOptionID']] = $items['customOptionVariantID'];
                        if (isset($combinationArray[$items['customOptionVariantID']])) {
                            $combinationCustomOption++;
                        }
                    }
                    if ($combination['combinationPrice'] > 0) {
                        if ($combination['combinationPriceDiffType'] == 'I') {
                            $extra_price = $extra_price + $combination['combinationPrice'];
                        } else if ($combination['combinationPriceDiffType'] == 'D') {
                            $extra_price = $extra_price - $combination['combinationPrice'];
                        }
                    }
                    if ($combinationCustomOption == count($combinationArray)) {
                        if ($combination['combinationPrice'] > 0 && $combination['combinationPrice'] != $combinationValues['combinationPrice']) {
                            $returnArray['isError']      = 'Yes';
                            $returnArray['errorMessage'] = $this->getLanguageValue("lblCartCombinationPriceMismatch");
                        } else if ($combination['combinationPrice'] > 0 && $combination['combinationPriceDiffType'] != $combinationValues['combinationPriceDiffType']) {
                            $returnArray['isError']      = 'Yes';
                            $returnArray['errorMessage'] = $this->getLanguageValue("lblCartCombinationPriceMismatch");
                        } else {
                            $returnArray['isError']      = 'No';
                            $returnArray['errorMessage'] = $this->getLanguageValue("lblCartCombinationFound");
                        }
                    } else {
                        $returnArray['isError']      = 'Yes';
                        $returnArray['errorMessage'] = $this->getLanguageValue("lblCartCombinationMismatch");
                    }
                } else {
                    $returnArray['isError']      = 'Yes';
                    $returnArray['errorMessage'] = $this->getLanguageValue("lblCartCombinationMismatch");
                }
            } else {
                $returnArray['isError']      = 'Yes';
                $returnArray['errorMessage'] = $this->getLanguageValue("lblCartSelectedCombinationNotAvilable");
            }
        }
        $productID     = $cartItemRow['productID'];
        $customOptions = $ObjCart->getProductCustomOptions($productID);
        if (count($customOptionValues) > count($customOptions)) {
            $returnArray['isError']      = 'Yes';
            $returnArray['errorMessage'] = $this->getLanguageValue("lblCartSelectedVariantNotFound");
        } else {
            if (count($customOptions) > 0) {
                $validateFields = 0;
                foreach ($customOptions as $key => $items) {
                    $customAttributeID = $items['customOptionID'];
                    $validateRule      = $items['validateRule'];
                    $validateRuleArray = explode('~*', $validateRule);
                    $currentValue      = '';
                    if ($validateRule != '') {
                        if ($items['inputType'] == 'textbox' || $items['inputType'] == 'textarea' || $items['inputType'] == 'date' || $items['inputType'] == 'datetime' || $items['inputType'] == 'time') {
                            $currentValue = isset($customOptionValues[$customAttributeID][0]) ? $customOptionValues[$customAttributeID][0]['variantValueText'] : '';
                        } else {
                            if (isset($combinationAttributeVariant[$customAttributeID]) && count($combinationAttributeVariant) > 0) {
                                $currentValue = $combinationAttributeVariant[$customAttributeID];
                            } else if (isset($customOptionValues[$customAttributeID])) {
                                $currentValue = $customOptionValues[$customAttributeID][0]['customOptionVariantID'];
                            }
                        }
                        if ($items['inputType'] != 'file') {
                            foreach ($validateRuleArray as $key1 => $items1) {
                                $validate = $this->ObjForm->isValidField('option_' . $productID . '_' . $customAttributeID, $items1, $currentValue, 'Error');
                                if ($validate == 'Error') {
                                    $validateFields = 1;
                                }
                            }
                        }
                    }
                    if ($items['inputType'] == 'textbox' || $items['inputType'] == 'textarea' || $items['inputType'] == 'date' || $items['inputType'] == 'datetime' || $items['inputType'] == 'time' || $items['inputType'] == 'file') {
                        $priceDiff     = (isset($customOptionValues[$customAttributeID][0]['priceDiff']) ? $customOptionValues[$customAttributeID][0]['priceDiff'] : 0);
                        $priceDiffType = (isset($customOptionValues[$customAttributeID][0]['priceDiffType']) ? $customOptionValues[$customAttributeID][0]['priceDiffType'] : '');
                        if (isset($customOptionValues[$customAttributeID]) && count($customOptionValues[$customAttributeID][0]) < 0) {
                            if ($items['priceDiff'] > 0 && ($priceDiff != $items['priceDiff'] || $priceDiffType != $items['priceDiffType'])) {
                                $returnArray['isError']      = 'Yes';
                                $returnArray['errorMessage'] = $this->getLanguageValue("lblCartCustomOptionPriceMisMatch");
                            }
                        }
                        if ($items['priceDiff'] > 0 && isset($customOptionValues[$customAttributeID]) && count($customOptionValues[$customAttributeID][0]) > 0) {
                            if ($items['priceDiffType'] == 'I') {
                                $extra_price = $extra_price + $items['priceDiff'];
                            } else if ($items['priceDiffType'] == 'D') {
                                $extra_price = $extra_price - $items['priceDiff'];
                            }
                        }
                    } else {
                        $customOptionVariantArray = isset($customOptionValues[$customAttributeID]) ? $customOptionValues[$customAttributeID] : array();
                        if (count($customOptionVariantArray) > 0) {
                            foreach ($customOptionVariantArray as $key2 => $items2) {
                                $customOptionVariantID = $items2['customOptionVariantID'];
                                if ($customOptionVariantID > 0) {
                                    $variantDetails = $ObjCart->getProductCustomOptionVariant($customOptionVariantID, $languageIDs);
                                    if (count($variantDetails) > 0) {
                                        $priceDiff     = (isset($items2['priceDiff']) ? $items2['priceDiff'] : 0);
                                        $priceDiffType = (isset($items2['priceDiffType']) ? $items2['priceDiffType'] : '');
                                        if ($variantDetails['priceDiff'] > 0 && ($priceDiff != $variantDetails['priceDiff'] || $priceDiffType != $variantDetails['priceDiffType'])) {
                                            $returnArray['isError']      = 'Yes';
                                            $returnArray['errorMessage'] = $this->getLanguageValue("lblCartCustomOptionPriceMisMatch");
                                        }
                                    } else {
                                        $returnArray['isError']      = 'Yes';
                                        $returnArray['errorMessage'] = $this->getLanguageValue("lblCartSelectedVariantNotFound");
                                    }
                                }
                                if ($variantDetails['priceDiff'] > 0 && count($customOptionValues[$customAttributeID][0]) > 0) {
                                    if ($variantDetails['priceDiffType'] == 'I') {
                                        $extra_price = $extra_price + $variantDetails['priceDiff'];
                                    } else if ($variantDetails['priceDiffType'] == 'D') {
                                        $extra_price = $extra_price - $variantDetails['priceDiff'];
                                    }
                                }
                            }
                        }
                    }
                }
                if ($validateFields == 1) {
                    $returnArray['isError']      = 'Yes';
                    $returnArray['errorMessage'] = $this->getLanguageValue("lblCartRequiredFieldsMissing");
                }
            }
        }
        if($bundleProd=="Yes"){
            $offer_price	  = 	$result['productOptionProductPrice'];
            $extra_price          =     0;
        }else{
            $offer_price          =     $result['offerPrice'];
            $offer_price          =     ($tier_price > 0 && $tier_price < $offer_price) ? $tier_price : $offer_price;
        }
        
        $post_data['actualPrice'] = isset($base_price) ? $base_price : 0;
        
		
		//Deal start
		$isProductDeal             = $result['isProductDeal'];
        $dealDiscount              = $result['dealDiscount'];
        $productOptionRegularPrice = $result['productOptionRegularPrice'];
		if($isProductDeal=='Yes'){
			//$extra_price=0;
                        //$offer_price                   = $productOptionRegularPrice - $productOptionRegularPrice*$result['dealDiscount']/100;
			//$deal_price = $productOptionRegularPrice*(100-$dealDiscount)/100;
			//$offer_price                  = ($deal_price > 0 && $deal_price < $offer_price) ? $deal_price : $offer_price;
                        $offer_price                   = $result['dealPrice'];
		}
		//Deal end
		
        $price                    = $offer_price + $extra_price;
        //echo $productOptionPrice.'----'.$cartItemRow['orderItemPrice'];exit;
        if (floor($price) != floor($cartItemRow['orderItemPrice'])) {
            $returnArray['isError']      = 'Yes';
            $returnArray['errorMessage'] = $this->getLanguageValue("lblCartItemPriceMismatch");
        }
        return $returnArray;
    }
    public function ajaxUploadAction() {
        exit;
        $ObjCart = new CartModel();
        $cartID  = $this->decodeString($this->ObjSession->getSession("CARTID"));
        if (count($_FILES) > 0) {
            foreach ($_FILES as $key => $error) {
                $fileElementArray  = explode('_', $key);
                $productID         = $fileElementArray[1];
                $customAttributeID = $fileElementArray[2];
                $validateFields    = 0;
                $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) {
                        //echo '<br>Rule - '.$items1.'<br>Field-option_'.$productID.'_'.$customAttributeID.'<br>Value-'.$currentValue;
                        $validate = $this->ObjForm->isValidField('option_' . $productID . '_' . $customAttributeID, $items1, $currentValue, 'Error');
                        //echo '<br>Result-'.$validate.'<br>';
                        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[$key . "--" . $_POST['currentTime']] = $filename;
                }
            }
        } else {
            $fileNameArray['isError'] = 'No';
        }
        echo json_encode($fileNameArray);
    }
    public function updateShippingMethod($POST) {
        $group_shipping_cost = $this->getSettingValue('product_cart_settings', 'group_shipping_cost');
        $ObjCart             = new CartModel();
        $cartID              = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $postData            = substr(trim($POST['postData']), 1);
       
        $userID              = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $mainArray           = explode('-', $postData);
        if (count($mainArray) > 0) {
            foreach ($mainArray as $key => $items) {
                $elementarray   = explode('~', $items);
                $elementName    = $elementarray[0];
                $methodID       = $elementarray[1];
                $productIDArray = explode('_', $elementName);
                if ($group_shipping_cost == 'Yes') {
                    $businessID              = $productIDArray[1];
                    $resUpdateShippingMethod = $ObjCart->updateShippingMethod($cartID, 0, $methodID, $businessID);
                } else {
                    $productID               = $productIDArray[1];
                    $resUpdateShippingMethod = $ObjCart->updateShippingMethod($cartID, $productID, $methodID);
                }
            }
        }
        $shipInfo = array();
        $shipInfo['shippingFname']      = $POST['shippingFname'];
        $shipInfo['shippingLname']      = $POST['shippingLname'];
        $shipInfo['shippingAddress']    = $POST['shippingAddress'];
        $shipInfo['shippingZip']        = $POST['shippingZip'];        
        $shipInfo['shippingCountryID']  = $POST['shippingCountryID'];
        $shipInfo['shippingCountry']    = $POST['shippingCountryID'];
        $shipInfo['shippingCity']       = $POST['shippingCity'];
        $shipInfo['shippingPhone']      = $POST['shippingPhone'];
        $shipInfo['shippingStateID']    = '';
        $shipInfo['shippingStateSelectedType']   = 'province';
        $resResetCartTotals = $ObjCart->calculateShippingRate($cartID, $this->_shippingCalculationParam,$shipInfo);
        $promoResult        = $this->setPromoCodeDiscount('', '', '', 'checkout');
        $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
                        
    }
    public function ajaxUpdateShippingMethodAction() {
       
        $ObjCart             = new CartModel();
        $cartID              = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $userID              = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $group_shipping_cost = $this->getSettingValue('product_cart_settings', 'group_shipping_cost');
        $postData            = substr(trim($_POST['postData']), 1);        
        $mainArray           = explode('-', $postData);   
        
        $businessShipping          = array();
        $shippingMethodsAll        = array();
        $resCart = $ObjCart->getCartDetails($cartID, 0);
        $resCart1['cartDetails'] = unserialize($resCart['extra']);
        
        if ($group_shipping_cost == 'Yes') {
            $shippingStateSelectedType = 'state';
            if($resCart1['cartDetails']['userShippingAddress']['shippingProvince']>0)
                $shippingStateSelectedType = 'province';
            $shippsArgs          = array(
                'shippingZip' => $resCart1['cartDetails']['userShippingAddress']['shippingZip'],
                'shippingStateID' => $resCart1['cartDetails']['userShippingAddress']['shippingStateID'],
                'shippingCountryID' => $resCart1['cartDetails']['userShippingAddress']['shippingCountryID'],
                'shippingStateSelectedType' => $shippingStateSelectedType
            );
            $userDeliveryZoneIDs = $this->getUserDeliverZoneID($shippsArgs);
            $shippingMethods     = $ObjCart->listShippingMethods($cartID, 0, $languageIDs, $group_shipping_cost, $userDeliveryZoneIDs,$this->_shippingCalculationParam['shipping_cost_global']);

            $products            = array();
            $prevID = '';
            foreach ($resCart['items'] as $items) {
                //if($prevID != $items['productID']) {
                    if($items['freeProduct']!="Yes"){
                        $products[$items['businessID']][] = $items['productID'];
                    }
                //}
                $prevID = $items['productID'];
                //$prevBusID = $items['businessID'];
            }
            //$products = array_values($products);
            //echo "<pre>"; print_r($shippingMethods); exit;
            $resShippingMethods = array();
            foreach ($shippingMethods as $methods) {
                if (count($products[$methods['businessID']]) == count(array_intersect(explode(",", $methods['productIDs']), $products[$methods['businessID']]))) {
                    $resShippingMethods[] = $methods;
                }
            }
//            echo count($resShippingMethods)."<br/>";
//            echo count($products)."<br/>";
//            echo $this->_shippingCalculationParam['shipping_cost_global']."<br/>";
            if (count($resShippingMethods) < count($products) && $this->_shippingCalculationParam['shipping_cost_global']!='Yes') {
                $resShippingMethods  = $ObjCart->listShippingMethods($cartID);
                $group_shipping_cost = 'No';
            }
        }
        
        if (count($mainArray) > 0) {   
            foreach ($mainArray as $key => $items) {
                $elementarray = explode('~', $items);
                $elementName  = $elementarray[0];
                $methodID     = $elementarray[1];               
                $productIDArray  = explode('_', $elementName);                
                if ($group_shipping_cost == 'Yes') {                     // && $this->_shippingCalculationParam['shipping_cost_global']!='Yes'
                    $businessID              =  $productIDArray[1]; //($this->_shippingCalculationParam['shipping_cost_global']!='Yes')?
                    if($this->_shippingCalculationParam['shipping_cost_global'] == 'Yes')
                        $businessID    = 0;
                    //$businessID              = $productIDArray[1];
                    $resUpdateShippingMethod = $ObjCart->updateShippingMethod($cartID, 0, $methodID,$businessID);
                } else {
                    $productID               = $productIDArray[1];
                    $resUpdateShippingMethod = $ObjCart->updateShippingMethod($cartID, $productID, $methodID);
                }
            }
        }
        $resResetCartTotals = $ObjCart->calculateShippingRate($cartID, $this->_shippingCalculationParam,array(),'Y');        
        $promoResult        = $this->setPromoCodeDiscount('', '', '', 'checkout');
        $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
        $resCart            = $ObjCart->getCartDetails($cartID, 0);
        if (count($resCart['items']) > 0) {            
            foreach ($resCart['items'] as $key => $items) {
                $resCart['items'][$key]['itemDetails'] = unserialize($items['itemDetails']);
            }
        }
        $resCart['cartDetails'] = unserialize($resCart['extra']);
        if(empty($resCart['cartDetails']['userBillingAddress'])) {
            $resCart['cartDetails']['userBillingAddress'] = '';
        }   
        if(empty($resCart['cartDetails']['userShippingAddress'])) {
            $resCart['cartDetails']['userShippingAddress'] = '';
        } 
        if (is_array($resCart['cartDetails']['userBillingAddress'])) {
            $tempArray = array_slice($resCart['cartDetails']['userBillingAddress'], 0, -2);
            unset($resCart['cartDetails']['userBillingAddress']);
            $resCart['cartDetails']['userBillingAddress'] = array_values($tempArray);
        }
        unset($tempArray);
        $tempArray = $resCart['cartDetails']['userShippingAddress'];
        unset($resCart['cartDetails']['userShippingAddress']);
        if (is_array($tempArray))
            $resCart['cartDetails']['userShippingAddress'] = array_values($tempArray);
        $this->ObjView->assign('cartData', $resCart);
        $this->ObjView->assign('userID', $userID);
        $promoData             = $this->setPromoCharityBlock('cartCheckout', (isset($promoCharityArray) ? $promoCharityArray : ''));
        $html = $this->ObjView->fetch('cart/CheckoutLeftBlock.tpl');
        $summary 	= $this->ObjView->fetch('cart/CheckoutOrderSummary.tpl');
        //$summary 	= $this->ObjView->fetch('cart/CheckoutOrderDetails.tpl');
        $returnData['summary'] = $summary;
        $returnData['html']    = $html;
        $this->ObjView->assign('orderTotalAmount', $resCart['orderTotalAmount']);
        $this->ObjView->assign('shippingAmount', $resCart['shippingAmount']);
        $this->ObjView->assign('cartDatacurrencyID', $resCart['currencyID']);
        $this->ObjView->assign('cartUsercurrencyID', $resCart['userCurrencyID']);
        $returnData['htmlShipp'] = $this->ObjView->fetch('cart/CartShippingTotal.tpl');
        $returnData['totordamt'] = $resCart['orderTotalAmount'];
        echo json_encode($returnData);
        return true;
    }
    public function getFileAction() {
        $fileName = $this->getRequestValue("id");
        $this->getFile($fileName, __CORE_PUBLIC_PATH . "/uploads/user-upload/custom-option/" . $fileName);
    }
    public function sendBuyNowError($ObjMail, $orderID, $languageIDs, $ObjCart, $ObjEmailtemplate, $masterOrderDetails) {
        $languageIDs                       = $this->ObjView->languageIDs;
        $siteName                          = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl                           = $this->getSettingValue('site_settings', 'global_http_url');
        $companyLogo                       = $this->getSettingValue('company_information', 'company_logo');
        //Admin LanguageID
        $languageIDsCustomAdmin            = $languageIDs;
        $languageIDsCustomAdmin['Current'] = $languageIDs['Default'];
        //Inventory Quantity Error Checking
        $outOfStockProducts                = $ObjCart->checkProductOutOfStock($languageIDs, $orderID, 'paymentSuccess');
        if (count($outOfStockProducts) > 0) {
            $ObjCart->changeMasterOrderStatus($orderID, 'Backordered', '');
            $emailTempDetRes = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustomAdmin, '', 'product-order-error-admin');
            $emailFrom       = array(
                $emailTempDetRes['emailFromEmail'],
                $emailTempDetRes['emailFromName']
            );
            foreach ($outOfStockProducts as $key => $value) {
                $emailTempDet          = $emailTempDetRes;
                $adminMail             = $this->getSettingValue('site_settings', 'global_notification_email');
                $unseralizedBillingAdd = unserialize($getOrderDetails['billingAddress']);
                $toEmailID             = $adminMail;
                $Subject               = $emailTempDet['emailSubject'];
                $Body                  = $emailTempDet['emailHtml'];
                $outOpt                = '<ul>';
                foreach ($value as $subItem) {
                    $outOpt .= "<li>:" . $subItem['optName'] . "</li><br/>";
                }
                $outOpt .= '</ul>';
                $orderDetailPage = rtrim($siteUrl, "/") . "/manage/order/show/id/" . $orderID . "/";
                $outOpt .= "<p><a href='" . $orderDetailPage . "'>" . $orderDetailPage . "</a></p>";
                $Body = $Body . $outOpt;
                $this->ObjView->assign('emailbody', $Body);
                $this->ObjView->assign('companyLogo', $companyLogo);
                $this->ObjView->assign('siteName', $siteName);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $email_body = $this->ObjCommon->fetch('email_templates/Layout.tpl', $languageIDsCustomAdmin);
                try {
                    $ObjMail->IsHTML();
                    $ObjMail->sendMail($emailFrom, $toEmailID, $Subject, $email_body);
                    $ObjMail->Send();
                }
                catch (Exception $e) {
                    $e->getMessage();
                }
            }
        }
        //Promocode Max Usage Checking
        $promoErrors = $ObjCart->checkPomoUsage($masterOrderDetails);
        if ($promoErrors['error'] > 0) {
            $ObjCart->changeMasterOrderStatus($orderID, 'Backordered', '');
            $emailTempDetRes       = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustomAdmin, '', 'product-order-error-admin');
            $emailFrom             = array(
                $emailTempDetRes['emailFromEmail'],
                $emailTempDetRes['emailFromName']
            );
            $adminMail             = $this->getSettingValue('site_settings', 'global_notification_email');
            $unseralizedBillingAdd = unserialize($getOrderDetails['billingAddress']);
            $toEmailID             = $adminMail;
            $Subject               = $emailTempDetRes['emailSubject'];
            $Body                  = $emailTempDetRes['emailHtml'];
            $outOpt                = '<p>' . $this->getLanguageValue("lblPromoCodeLimitExcdOrder") . '</p>';
            $orderDetailPage       = rtrim($siteUrl, "/") . "/manage/order/show/id/" . $orderID . "/";
            $outOpt .= "<p><a href='" . $orderDetailPage . "'>" . $orderDetailPage . "</a></p>";
            $Body = $Body . $outOpt;
            $this->ObjView->assign('emailbody', $Body);
            $this->ObjView->assign('companyLogo', $companyLogo);
            $this->ObjView->assign('siteName', $siteName);
            $this->ObjView->assign('siteUrl', $siteUrl);
            $email_body = $this->ObjCommon->fetch('email_templates/Layout.tpl', $languageIDsCustomAdmin);
            try {
                $ObjMail->IsHTML();
                $ObjMail->sendMail($emailFrom, $toEmailID, $Subject, $email_body);
                $ObjMail->Send();
            }
            catch (Exception $e) {
                $e->getMessage();
            }
        }
    }
    public function ajaxUpdateUserEmailAction() {
        $ObjCart      = new CartModel();
        $ObjUsers     = new UserModel();
        $languageIDs                       = $this->ObjView->languageIDs;
        $resUserCount = $ObjUsers->checkUserExists($_POST['userLoginEmail']);
        if ($resUserCount['userCount'] > 0) {
            $message['code'] = 'error';
            $message['message'] = $this->getLanguageValue("errCheckoutEmailExists");
        } else {
            $cartID        = $this->decodeString($this->ObjSession->getSession("CARTID"));
            $resCartUpdate = $ObjCart->updateCartUserEmail($cartID, $_POST['userLoginEmail']);
            $resCart       = $ObjCart->getCartDetails($cartID);
            $validatedCart = $this->validateCart($resCart, 'No', 'checkout');
            if (count($validatedCart['error']) < 1) {
                $promoData = $this->setPromoCodeDiscount($resCart['orderPromoCode']);
                if (isset($promoData['promoErrorCode']) && $promoData['promoErrorCode'] > 0) {
                    $ObjCart->removeCartUserEmail($cartID);
                    $message['code']    = 'promo_error';
                    $message['message'] = $promoData['error'];
                } else {
                    $message['code'] = 'success';
                }
            } else {
                $ObjCart->removeCartUserEmail($cartID);
                $message['code']    = "cart_validation_error";
                $message['message'] = $validatedCart['error'];
            }
        }
        echo json_encode($message);
    }
    public function ajaxUpdateCouponAction() {
        $ObjCart     = new CartModel();
        $ObjUsers    = new UserModel();
        $languageIDs = $this->ObjView->languageIDs;
        $userID      = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $cartID      = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $this->ObjView->assign('userID', $userID);
        $adrsType                = (isset($_POST['adrsType']) ? $_POST['adrsType'] : '');
        $actionForm              = ($adrsType == 'Billing') ? 'formCheckoutBilling' : 'formCheckoutShipping';
        $actionButton            = ($adrsType == 'Billing') ? 'submitCheckoutBilling' : 'submitCheckoutShipping';
        $_POST[$actionButton]    = '1';
        $settingsEnablePromoCode = $this->getSettingValue('product_cart_settings', 'enable_promo_codes');
        $this->ObjView->assign('enablePromoCode', $settingsEnablePromoCode);
        $ObjGiftcoupn = new GiftcouponModel();
        $ObjCart      = new CartModel();
        $succMsg      = '';
        $errorMsg     = '';
        $couponCode   = $_REQUEST['couponCode'] = $_POST['couponCode'] = trim($_POST['couponCode']);
        $userID       = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $cartID       = $this->ObjSession->getSession("CARTID");
        $cartID       = $this->decodeString($cartID);
        $resRedeem    = $ObjGiftcoupn->redeemCoupon($couponCode, $userID);
        if ($resRedeem == 'Inactive') {
            $promoArray['promoError']  = 'Yes';
            $promoArray['promoErrMsg'] = $this->getLanguageValue("errCouponRedeemInactive");
        } elseif ($resRedeem == 'Redeemed') {
            $promoArray['promoError']  = 'Yes';
            $promoArray['promoErrMsg'] = $this->getLanguageValue("errCouponRedeemUsed");
        } elseif ($resRedeem == 'Invalid') {
            $promoArray['promoError']  = 'Yes';
            $promoArray['promoErrMsg'] = $this->getLanguageValue("errCouponRedeemInvalid");
        } elseif ($resRedeem == 'Expired') {
            $promoArray['promoError']  = 'Yes';
            $promoArray['promoErrMsg'] = $this->getLanguageValue("errCouponRedeemExpired");
        } elseif ($resRedeem == 'Cancelled') {
            $promoArray['promoError']  = 'Yes';
            $promoArray['promoErrMsg'] = $this->getLanguageValue("errCouponRedeemCancelled");
        } else {
            $updateCartItems           = $ObjCart->resetCartTotals($cartID);
            $resRedeemAmt              = $this->ObjView->getFormattedCurrency($resRedeem);
            $giftSuccMsg               = $this->getLanguageValue('msgGiftCouponRedeemSuccess');
            $promoArray['promoErrMsg'] = str_replace('{$amount}', $resRedeemAmt, $giftSuccMsg);
            $promoArray['promoError']  = 'No';
        }
        $promoData        = $promoArray;
        $userCreditAmount = $ObjUsers->getAvailableBalance($userID);
        $userCreditAmount = ($userCreditAmount > 0) ? $userCreditAmount : 0;
        $this->ObjView->assign('availableBalance', $userCreditAmount);
        $returnData['validationError'] = 'No';
        $noValidation                  = 'No';
        if ($adrsType == '' || $adrsType == 'ShippingMethod' || $_POST['applyPromo'] == 'Yes' || $_POST['removePromo'] == 'Yes') {
            $noValidation = 'Yes';
        }
        if ($noValidation == 'No') {
            if ($this->ObjForm->isValid($actionForm, $actionButton, false)) {
                if ($adrsType == 'Billing') {
                    $arrAddress = array(
                        'billingFirstName' => trim(stripslashes($_POST['billingFirstName'])),
                        'billingLastName' => trim(stripslashes($_POST['billingLastName'])),
                        'billingAddress' => trim(stripslashes($_POST['billingAddress'])),
                        'billingAddress1' => trim(stripslashes($_POST['billingAddress1'])),
                        'billingCity' => trim(stripslashes($_POST['billingCity'])),
                        'billingProvince' => trim(stripslashes($_POST['billingProvince'])),
                        'billingZip' => trim(stripslashes($_POST['billingZip'])),
                        'billingState' => trim(stripslashes($_POST['billingState'])),
                        'billingCountry' => trim(stripslashes($_POST['billingCountry'])),
                        'billingPhone' => trim(stripslashes($_POST['billingPhone'])),
                        'billingEmail' => trim(stripslashes($_POST['billingEmail']))
                    );
                } else if ($adrsType == 'Shipping') {
                    $arrAddress = array(
                        'shippingFname' => trim(stripslashes($_POST['shippingFname'])),
                        'shippingLname' => trim(stripslashes($_POST['shippingLname'])),
                        'shippingAddress' => trim(stripslashes($_POST['shippingAddress'])),
                        'shippingAddress1' => trim(stripslashes($_POST['shippingAddress1'])),
                        'shippingCity' => trim(stripslashes($_POST['shippingCity'])),
                        'shippingProvince' => trim(stripslashes($_POST['shippingProvince'])),
                        'shippingZip' => trim(stripslashes($_POST['shippingZip'])),
                        'shippingStateID' => trim(stripslashes($_POST['shippingState'])),
                        'shippingCountryID' => trim(stripslashes($_POST['shippingCountry']))
                    );
                    if ($_POST['shippingSaveToList']) {
                        $ObjCart->saveCartShippingAddressToList($arrAddress, $userID);
                    }
                }
                $resCartUpdate = $ObjCart->updateUserCartAddress($userID, $cartID, $arrAddress, $adrsType);
                // prev ship calc & tax upd
            } else {
                $returnData['validationError'] = 'Yes';
                echo json_encode($returnData);
                return true;
            }
        }
        //$ObjCart->calculateShippingRate($cartID);
        $ObjCart->updateCartItemsTax($cartID, $this->_taxCalculationParam);
        $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
        $resCart            = $ObjCart->getCartDetails($cartID, 0);
        if (count($resCart['items']) > 0) {
            foreach ($resCart['items'] as $key => $items) {
                $resCart['items'][$key]['itemDetails'] = unserialize($items['itemDetails']);
            }
        }
        $resCart['cartDetails'] = unserialize($resCart['extra']);
        if(empty($resCart['cartDetails']['userBillingAddress'])) {
            $resCart['cartDetails']['userBillingAddress'] = array();
        }
        if(empty($resCart['cartDetails']['userShippingAddress'])) {
            $resCart['cartDetails']['userShippingAddress'] = array();
        }
        if (is_array($resCart['cartDetails']['userBillingAddress'])) {
            $tempArray = array_slice($resCart['cartDetails']['userBillingAddress'], 0, -2);
            unset($resCart['cartDetails']['userBillingAddress']);
            $resCart['cartDetails']['userBillingAddress'] = array_values($tempArray);
        }
        unset($tempArray);
        $tempArray = $resCart['cartDetails']['userShippingAddress'];
        unset($resCart['cartDetails']['userShippingAddress']);
        if (is_array($tempArray))
            $resCart['cartDetails']['userShippingAddress'] = array_values($tempArray);
        $this->ObjView->assign('cartData', $resCart);
        if ($adrsType == 'Payment') {
            if ($resCart['orderTotalAmount'] > 0) {
                $expYearsValues[0] = range(date("Y"), (date("Y") + 18));
                $expYearsValues[1] = range(date("Y"), (date("Y") + 18));
                foreach (range(date("Y"), (date("Y") + 18)) as $key => $expyearValue) {
                    $years[$key][] = $expyearValue;
                    $years[$key][] = $expyearValue;
                }
                if ($this->getSettingValue("security_settings", "store_cc_info") == 'Yes') {
                    $getUserCCInfo = $ObjUsers->getUserCCInfo($userID);
                }
                $resUserDetails = $ObjUsers->getUserDetails($userID);
                if (!empty($getUserCCInfo)) {
                    $creditCardFirstName = $getUserCCInfo['firstNameonCard'];
                    $creditCardLastName  = $getUserCCInfo['lastNameonCard'];
                    $creditCardNumber    = $this->decodeString($getUserCCInfo['cardNumber']);
                    $creditCardTypeId    = $getUserCCInfo['cardType'];
                    $expMonth            = $getUserCCInfo['expMonth'];
                    $expYear             = $getUserCCInfo['expYear'];
                } else {
                    $creditCardFirstName = $resUserDetails['userFirstName'];
                    $creditCardLastName  = $resUserDetails['userLastName'];
                }
                $this->ObjView->assign('years', $years);
                $this->ObjView->assign('creditCardFirstName', $creditCardFirstName);
                $this->ObjView->assign('creditCardLastName', $creditCardLastName);
                $this->ObjView->assign('expMonth', $expMonth);
                $this->ObjView->assign('expYear', $expYear);
                $this->ObjView->assign('creditCardNumber', $creditCardNumber);
                $this->ObjView->assign('creditCardType', $creditCardTypeId);
                $this->ObjView->assign('userCardType', $creditCardTypeId);
                $ObjCountry		= new CountryModel();
                $iso2CountryFormat =   $ObjCountry->getCountryCode(unserialize($resCart['extra'])['userShippingAddress']['shippingCountryID']);
                $resPaymentGateways = $this->showPaymentTitleByLang($ObjCart->listPaymentGateways($resCart['currencyID'],'',$iso2CountryFormat));
                $this->ObjView->assign('resPaymentGateways', $resPaymentGateways);
                $this->ObjView->assign('paymentGatewaysCount', count($resPaymentGateways));
            }
            $settingsEnableTerms = $this->getSettingValue('product_cart_settings', 'enable_terms_privacy');
            $this->ObjView->assign('enableTermsPrivacy', $settingsEnableTerms);
            $this->ObjCommon->setDynamicMenuPlugin($this->ObjView);
            $html = $this->ObjView->fetch('cart/CheckoutPayment.tpl');
        } else if ($adrsType == 'ShippingMethod') {
            $needshippingMethodReset = true;
            ;
            $shippingZip               = trim(stripslashes($_POST['shippingZip']));
            $shippingStateID           = trim(stripslashes($_POST['shippingState']));
            $shippingCountryID         = trim(stripslashes($_POST['shippingCountry']));
            $shippingStateSelectedType = trim(stripslashes($_POST['shippingStateSelectedType']));
            $resShippingMethods        = $ObjCart->listShippingMethods($cartID);
            $shippingFreeEnable        = $this->getSettingValue('shipping_settings', 'shipping_free_enable');
            $freeShippingAmount        = $this->getSettingValue('shipping_settings', 'free_shipping_amount');
            $freeShippingQty           = $this->getSettingValue('shipping_settings', 'free_shipping_qty');
            if (count($resShippingMethods) > 0) {
                $shippingParams['shippingZip']               = $shippingZip;
                $shippingParams['shippingStateID']           = $shippingStateID;
                $shippingParams['shippingCountryID']         = $shippingCountryID;
                $shippingParams['shippingStateSelectedType'] = $shippingStateSelectedType;
                $shippingParams['cartID']                    = $cartID;
                $shippingParams['shippingTaxable']           = $this->_shippingCalculationParam['shippingTaxable'];
                foreach ($resShippingMethods as $key => $method) {
                    $itemDetails = unserialize($method['itemDetails']);
                    if ($method['settingsGroupID'] > 0) {
                        $shippingMethodsdeliveryZones = $ObjCart->listShippingMethodsDeliveryZones($method['shippingtoproductID'], $method['productID']);
                    }
                    $deliveryZoneFound = false;
                    $shippingAvilable  = true;
                    $shippingCharge    = 99999999;
                    unset($ObjShippingLib);
                    unset($ObjShipping);
                    if (count($shippingMethodsdeliveryZones) > 0) {
                        foreach ($shippingMethodsdeliveryZones as $key1 => $zone) {
                            $deliveryZoneDetails = $ObjCart->getDeliveryZoneDetails($languageIDs, $zone['deliveryZoneID']);
                            if (count($deliveryZoneDetails) > 0) {
                                foreach ($deliveryZoneDetails as $key1 => $zoneReg) {
                                    if ($zoneReg['countryID'] == $shippingCountryID && $shippingCountryID > 0) {
                                        if ($zoneReg['StateID'] == $shippingStateID && $shippingStateID > 0) {
                                            if ($zoneReg['zipCodes'] != '' && $shippingZip != '') {
                                                $zipArray = explode(',', $zoneReg['zipCodes']);
                                                if (in_array($shippingZip, $zipArray)) {
                                                    $deliveryZoneFound = true;
                                                    break;
                                                }
                                            } else if ($zoneReg['zipCodes'] == '') {
                                                $deliveryZoneFound = true;
                                                break;
                                            }
                                        } else if ($shippingStateSelectedType == 'province' && $zoneReg['zipCodes'] != '' && $shippingZip != '') {
                                            $zipArray = explode(',', $zoneReg['zipCodes']);
                                            if (in_array($shippingZip, $zipArray)) {
                                                $deliveryZoneFound = true;
                                                break;
                                            }
                                        } else if ($zoneReg['zipCodes'] == '' && $zoneReg['StateID'] < 1) {
                                            $deliveryZoneFound = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            if ($deliveryZoneFound)
                                break;
                        }
                        if ($method['settingsGroupID'] > 0 && $deliveryZoneFound) {
                            if ($method['settingsGroupKey'] == 'free_shipping' || $method['settingsGroupParent'] == 1) {
                                $paramsArray     = array(
                                    'tableName' => 'cart_items',
                                    'fieldName' => 'sum(orderItemQuantity) as orderItemQuantity',
                                    'conditionField' => 'productID',
                                    'condition' => '=',
                                    'conditionValue' => $method['productID'],
                                    'conditionField1' => 'cartID',
                                    'condition1' => '=',
                                    'conditionValue1' => $cartID,
                                    'conditionFieldType' => ''
                                );
                                $resOrderItemQty = $ObjCart->getFieldValue($paramsArray);
                                if ($resOrderItemQty['orderItemQuantity'] >= $method['maxQtyPerShipping']) {
                                    $shippingCharge = 0;
                                    $shippingtype   = 'Free';
                                } else {
                                    $shippingAvilable = false;
                                }
                            } else if ($shippingFreeEnable != 'No') {
                                if ($shippingFreeEnable == 'Globally') {
                                    $defaultCurrencyId = $this->ObjView->_defaultCurrency;
                                    $cartcurrencyId    = $resCart['currencyID'];
                                    $cartAmount        = $this->ObjView->convertValueCustom($resCart['orderSubtotal'], $cartcurrencyId, $defaultCurrencyId);
                                    $cartQty           = $resCart['orderQty'];
                                    if (($cartAmount > $freeShippingAmount && $freeShippingAmount > 0) || ($cartQty > $freeShippingQty && $freeShippingQty > 0)) {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingCharge = 0;
                                            $shippingtype   = 'Free';
                                        } else {
                                            $shippingAvilable = false;
                                        }
                                    } else {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingtype = 'Paid';
                                        } else {
                                            $shippingCharge   = 100;
                                            $shippingtype     = 'Paid';
                                            $shippingAvilable = false;
                                        }
                                    }
                                } else if ($shippingFreeEnable == 'Business wise') {
                                    $businesswiseDetails = $ObjCart->getBusinessWiseCartDetails($method['productID'], $cartID);
                                    $defaultCurrencyId   = $this->ObjView->_defaultCurrency;
                                    $cartcurrencyId      = $resCart['currencyID'];
                                    $cartAmount          = $this->ObjView->convertValueCustom($businesswiseDetails['orderItemSubtotal'], $cartcurrencyId, $defaultCurrencyId);
                                    $cartQty             = $businesswiseDetails['orderItemQuantity'];
                                    if (($cartAmount > $freeShippingAmount && $freeShippingAmount > 0) || ($cartQty > $freeShippingQty && $freeShippingQty > 0)) {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingCharge = 0;
                                            $shippingtype   = 'Free';
                                        } else {
                                            $shippingAvilable = false;
                                        }
                                    } else {
                                        if ($method['isRealTimeCalculation'] == 'No') {
                                            $shippingtype = 'Paid';
                                        } else {
                                            $shippingCharge   = 100;
                                            $shippingtype     = 'Paid';
                                            $shippingAvilable = false;
                                        }
                                    }
                                }
                            } else {
                                if ($method['isRealTimeCalculation'] == 'No') {
                                    $shippingtype = 'Paid';
                                } else {
                                    $shippingCharge   = 100;
                                    $shippingtype     = 'Paid';
                                    $shippingAvilable = false;
                                }
                            }
                            if ($shippingAvilable) {
                                $subArray                                                                   = array(
                                    'methodName' => $method['settingsGroupXmlLabel'],
                                    'methodID' => $method['settingsGroupID'],
                                    'shippingCharge' => $shippingCharge,
                                    'shippingtype' => $shippingtype,
                                    'settingsGroupKey' => $method['settingsGroupKey'],
                                    'settingsGroupParent' => $method['settingsGroupParent']
                                );
                                $shippingArray[$method['productID']]['methods'][$method['settingsGroupID']] = $subArray;
                            }
                        }
                    }
                    $shippingArray[$method['productID']]['itemName']         = $itemDetails['productOptionName'];
                    $shippingArray[$method['productID']]['shippingMethodID'] = $itemDetails['shippingMethod']['methodID'];
                }
            }
            if (count($shippingArray) > 0) {
                foreach ($shippingArray as $key => $method) {
                    if (count($method['methods']) > 0) {
                        foreach ($method['methods'] as $key1 => $shippingMethod) {
                            $shippingParams['productID']       = $key;
                            $shippingParams['settingsGroupID'] = $shippingMethod['methodID'];
							$shippingParams['globalBaseCharge'] = $this->_shippingParam['global_shipping_baseCharge'];
                            if ($shippingMethod['settingsGroupKey'] != '' && $shippingMethod['shippingtype'] == 'Paid') {
                                $paramsArray           = array(
                                    'tableName' => 'shipping_methods',
                                    'fieldName' => 'settingsGroupKey',
                                    'conditionField' => 'settingsGroupID',
                                    'condition' => '=',
                                    'conditionValue' => $shippingMethod['settingsGroupParent'],
                                    'conditionFieldType' => 'int'
                                );
                                $resshippingGateWayKey = $ObjCart->getFieldValue($paramsArray);
                                $shippingGateWayKey    = $resshippingGateWayKey['settingsGroupKey'];
                                $ObjShippingLib        = new Shipping($shippingGateWayKey);
                                $ObjShipping           = $ObjShippingLib->getShippingObject();
                                if (!is_object($ObjShipping)) {
                                    continue;
                                } else {
                                    list($shippingTax, $shippingCharge) = $ObjShipping->getShippingRate($shippingParams);
                                    $needshippingMethodReset = false;
                                }
                                if ($shippingCharge == 'error') {
                                    unset($shippingArray[$key]['methods'][$key1]);
                                } else {
                                    $shippingArray[$key]['methods'][$key1]['shippingCharge'] = $shippingCharge;
                                    $shippingArray[$key]['methods'][$key1]['shippingTax']    = $shippingTax;
                                }
                            }
                        }
                    }
                }
            } else {
                //Double checking
                //If address not matching for shiping method need to reset
                $ObjCart->resetShippingMethod($cartID);
            }
            $this->ObjView->assign('shippingMethods', $shippingArray);
            $html = $this->ObjView->fetch('cart/CheckoutShippingMethod.tpl');
        } else {
            $html    = $this->ObjView->fetch('cart/CheckoutLeftBlock.tpl');
            $summary = $this->ObjView->fetch('cart/CheckoutOrderSummary.tpl');
            //$summary = $this->ObjView->fetch('cart/CheckoutOrderDetails.tpl');
        }
        $returnData['html']      = $html;
        $returnData['summary']   = $summary;
        $returnData['promoData'] = $promoData;
        echo json_encode($returnData);
        return true;
    }

    //Set Promo Discount
    private function setPromoCodeDiscount($promo_code = '', $remove = '', $reset_total = '', $section = 'cart') {
        $ObjCart                           = new CartModel();
        $promoArray['promoError']          = 'No';
        $promoArray['promoErrMsg']         = '';
        $cartID                            = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $languageIDs                       = $this->ObjView->languageIDs;
        $params['debug']                   = 'Yes';
        $params['promoApp'] = 'Web';
        $params['language_id']             = $languageIDs['Default'];
        $params['current_language_id']     = $languageIDs['Current'];
        $params['currency_id']             = $this->ObjView->_defaultCurrency;
        $params['cart_id']                 = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $params['user_group_id']           = ($this->ObjCommon->REGISTERED_USER_GROUP_ID > 0) ? $this->ObjCommon->REGISTERED_USER_GROUP_ID : 0;
        $params['user_email']              = $this->ObjSession->getSession("REGISTERED_USER_EMAIL");
        $params['user_id']                 = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $cart                              = $ObjCart->getCartDetails($params['cart_id'],0, 'paid','Wt');
        $cart['extra']                     = isset($cart['extra']) ? unserialize($cart['extra']) : '';
        $params['currency_decimal_places'] = $this->ObjView->_currencies[$this->ObjView->_defaultCurrency]['currencyDecimalPlaces'];
        $params['coupon_code']             = ($promo_code != '' || $remove == 'remove') ? $promo_code : (isset($cart['orderPromoCode']) ? $cart['orderPromoCode'] : '');
        //echo $section;
      
        list($promo_error_code, $free_products) = $ObjCart->fn_promotion_apply($params, $cart);
        //print_r($free_products);
        if ($section == 'cart' || count($free_products) == 0)
            $ObjCart->deleteFreeProducts($cartID);
        //print_r($free_products);exit;
        if ($section == 'cart') {
            if (count($free_products) > 0) {
                foreach ($free_products as $key => $subItem) {
                    $str     = '';
                    $com_str = '';
                    $result  = $ObjCart->getFreeProductDetails(array(
                        "language_id" => $languageIDs['Default'],
                        "product_id" => $subItem['productID'],
                        "product_option_id" => $subItem['variants']
                    ));
                    if (count($subItem['customOptions']) > 0) {
                        foreach ($subItem['customOptions'] as $key1 => $custom_options) {
                            if ($custom_options['inputtype'] == 'select') {
                                $params['custom_option_variant_id'] = $custom_options['value'];
                                $params['custom_option_id']         = $custom_options['id'];
                                $params['language_id']              = $languageIDs['Current'];
                                $c_o_v_d                            = $ObjCart->getCustomOptionVariantDeatils($params);
                                $c_o_d                              = $ObjCart->getCustomOptionDeatils($params);
                                $str .= '->customOptionID~*' . $custom_options['id'] . '~:customOptionName~*' . $c_o_d['customOptionName'] . '~:customOptionVariantID~*' . $custom_options['value'] . '~:variantValue~*' . $c_o_v_d['value'] . '~:inputType~*' . $custom_options['inputtype'];
                                if ($c_o_v_d['priceDiff'] > 0)
                                    $str .= '~:priceDiff~*' . $c_o_v_d['priceDiff'] . '~:priceDiffType~*' . $c_o_v_d['priceDiffType'];
                            } else if ($custom_options['inputtype'] == 'multiselect') {
                                $value_array = explode(',', $custom_options['value']);
                                if (count($value_array) > 0) {
                                    foreach ($value_array as $key2 => $value) {
                                        $params['custom_option_variant_id'] = $value;
                                        $params['custom_option_id']         = $custom_options['id'];
                                        $params['language_id']              = $languageIDs['Current'];
                                        $c_o_v_d                            = $ObjCart->getCustomOptionVariantDeatils($params);
                                        $c_o_d                              = $ObjCart->getCustomOptionDeatils($params);
                                        $str .= '->customOptionID~*' . $custom_options['id'] . '~:customOptionName~*' . $c_o_d['customOptionName'] . '~:customOptionVariantID~*' . $value . '~:variantValue~*' . $c_o_v_d['value'] . '~:inputType~*' . $custom_options['inputtype'];
                                        if ($c_o_v_d['priceDiff'] > 0)
                                            $str .= '~:priceDiff~*' . $c_o_v_d['priceDiff'] . '~:priceDiffType~*' . $c_o_v_d['priceDiffType'];
                                    }
                                }
                            } else {
                                $params['custom_option_id'] = $custom_options['id'];
                                $params['language_id']      = $languageIDs['Current'];
                                $c_o_d                      = $ObjCart->getCustomOptionDeatils($params);
                                $str .= '->customOptionID~*' . $custom_options['id'] . '~:customOptionName~*' . $c_o_d['customOptionName'] . '~:customOptionVariantID~*0~:variantValueText~*' . $custom_options['value'] . '~:variantValue~*' . $custom_options['value'] . '~:inputType~*' . $custom_options['inputtype'];
                                if ($c_o_d['priceDiff'] > 0)
                                    $str .= '~:priceDiff~*' . $c_o_d['priceDiff'] . '~:priceDiffType~*' . $c_o_d['priceDiffType'];
                            }
                        }
                    }
                    if ($subItem['combinations'] != '') {
                        $params['combination_hash'] = $subItem['combinations'];
                        $comb_det                   = $ObjCart->getCombinationDeatils($params);
                        $value_array                = explode('_', $comb_det['combination']);
                        $tmp                        = array_shift($value_array);
                        $com_str                    = '->combinationSKU~*--->combinationPrice~*0->combinationPriceDiffType~*N';
                        if (count($value_array) > 0) {
                            foreach ($value_array as $key2 => $value) {
                                $params['custom_option_variant_id'] = $value;
                                $params['language_id']              = $languageIDs['Current'];
                                $c_o_v_d                            = $ObjCart->getCustomOptionVariantDeatils($params);
                                $params['custom_option_id']         = $c_o_v_d['customOptionID'];
                                $c_o_d                              = $ObjCart->getCustomOptionDeatils($params);
                                $com_str .= '->customOptionID~*' . $c_o_v_d['customOptionID'] . '~:customOptionName~*' . $c_o_d['customOptionName'] . '~:customOptionVariantID~*' . $value . '~:variantValue~*' . $c_o_v_d['value'];
                                if ($c_o_v_d['priceDiff'] > 0)
                                    $com_str .= '~:priceDiff~*' . $c_o_v_d['priceDiff'] . '~:priceDiffType~*' . $c_o_v_d['priceDiffType'];
                            }
                        }
                    }
                    $post_data['productID']              = $subItem['productID'];
                    $post_data['productOptionID']        = $result['productOptionID'];
                    $post_data['combinationHash']        = $subItem['combinations'];
                    $post_data['quantity']               = $subItem['quantity'];
                    $post_data['freeShipping']           = $subItem['freeShipping'];
                    $post_data['sameItem']               = 'No';
                    $post_data['optionsHash']            = '';
                    $post_data['customOptionValues']     = $str;
                    $post_data['strcombinationValues']   = $com_str;
                    $post_data['productDefaultCurrency'] = $this->ObjView->_defaultCurrency;
                    $post_data['giveAsGift']             = 'No';
                    //$post_data['productServiceFee']		= $result['productServiceFee'];
                    $post_data['productServiceFee']      = 0;
                    $post_data['productTitle']           = $result['productTitle'];
                    $post_data['productOptionName']      = $result['productTitle'];
                    $post_data['productImage']           = $result['productImage'];
                    $post_data['businessKey']            = $result['businessKey'];
                    $post_data['currbusinessid']         = $result['businessID'];
                    $post_data['freeProduct']            = 'Yes';
                    $this->ajaxAddItemAction($post_data);
                }
                //$ObjCart->updateFreeProductDiscount($cartID);
            }
        }
        //ajaxAddItem
        if (isset($remove) && $remove == 'remove') {
            $campaignID     = $this->ObjCookie->distroyCookie("EMAIL_CAMPAIGN_ID");
            $campaignEmail  = $this->ObjCookie->distroyCookie("EMAIL_CAMPAIGN_USER");
            $notificationID = $this->ObjCookie->distroyCookie("EMAIL_NOTIFICATION_ID");
            $this->setMessage($this->getLanguageValue("lblPromoCodeRemoved"));
        }
        $campaignEmail  = $this->ObjCookie->getCookie("EMAIL_CAMPAIGN_USER");
        $notificationID = $this->ObjCookie->getCookie("EMAIL_NOTIFICATION_ID");
        $campaignID     = $this->ObjCookie->getCookie("EMAIL_CAMPAIGN_ID");
        if ($campaignEmail != '' || $notificationID > 0) {
            $reg_email   = $this->ObjSession->getSession("REGISTERED_USER_EMAIL");
            $reg_userid  = $this->ObjSession->getSession("REGISTERED_USER_ID");
            $promoType   = "CAMP_" . $campaignID;
            $promoCode   = $promoType . "_" . date('d') . '_' . date('m') . '_' . date('Y');
            $usage_count = $ObjCart->getCampaignUsageCount($reg_userid, $reg_email, $promoCode, $this->decodeString($this->ObjSession->getSession("CARTID")));
            //echo $usage_count;
            //exit;
            if ($usage_count > 0) {
                $campaignID    = $this->ObjCookie->distroyCookie("EMAIL_CAMPAIGN_ID");
                $campaignEmail = $this->ObjCookie->distroyCookie("EMAIL_CAMPAIGN_USER");
            }
        }
        $campaignEmail  = $this->ObjCookie->getCookie("EMAIL_CAMPAIGN_USER");
        $notificationID = $this->ObjCookie->getCookie("EMAIL_NOTIFICATION_ID");
        if ($campaignEmail != '' || $notificationID > 0) {
            $setDiscount = $ObjCart->setSpecialCampaignDiscount($this->decodeString($this->ObjSession->getSession("CARTID")));
        }
        if ($reset_total == 'reset') {
            $resResetCartTotals = $ObjCart->resetCartTotals($this->decodeString($this->ObjSession->getSession("CARTID")), false);
        }
        if ($promo_error_code > 0) {
            $promoArray['error']          = $this->setPromoErrorMessages($promo_error_code);
            $promoArray['promoError']     = 'Yes';
            $promoArray['promoErrorCode'] = $promo_error_code;
        }
        return $promoArray;
    }
    //Set promo Error Messages
    private function setPromoErrorMessages($promoErrorCode) {
        $promoErrMsg = '';
        if ($promoErrorCode > 0) {
            //Invalid Promocode
            if ($promoErrorCode == 1) {
                $promoErrMsg = $this->getLanguageValue("lblPromoCodeNotApplied");
            } elseif ($promoErrorCode == 2) // Maximum Usage Per User	
                {
                $promoErrMsg = $this->getLanguageValue("lblPromoCodeNotProduct");
            } elseif ($promoErrorCode == 3) // Maximum Usage
                {
                $promoErrMsg = $this->getLanguageValue("lblPromoCodeLimitExcd");
            } elseif ($promoErrorCode == 5) //Not assigned to the selected Product(s)
                {
                $promoErrMsg = $this->getLanguageValue("lblPromoCodeNotProduct");
            }
        }
        return $promoErrMsg;
    }
    public function validatePromoUsage($resCart) {
        $ObjCart = new CartModel();
        if (!empty($resCart['items'])) {
            $processedPromos = array();
            $cartExtra       = isset($resCart['extra']) ? unserialize($resCart['extra']) : '';
            if ($resCart['userID'] > 0) {
                $userEmail = $this->ObjSession->getSession("REGISTERED_USER_EMAIL");
            } else // guest user
                {
                $userEmail = isset($cartExtra['extra']['userCheckoutEmail']) ? $cartExtra['extra']['userCheckoutEmail'] : '';
            }
            //Iterate cart items
            foreach ($resCart['items'] as $key => $value) {
                $itemDetails = unserialize($value['itemDetails']);
                if (isset($itemDetails['promotions']) && !empty($itemDetails['promotions'])) {
                    //Iterate each promotion
                    foreach ($itemDetails['promotions'] as $cartPromotions) {
                        $currentRuleID = $cartPromotions['ruleID'];
                        if (!in_array($currentRuleID, $processedPromos)) {
                            //Push to processed promo array
                            $processedPromos[] = $currentRuleID;
                            //Promos with usage restriction will be selected & checked
                            $promoUsageDetails = $ObjCart->getCartPromoUsageDetails($currentRuleID);
                            if (!empty($promoUsageDetails)) {
                                $errorFound = 0;
                                //Total usage including temp usage
                                $totalUsage = $promoUsageDetails['timesUsed'] ;//+ $promoUsageDetails['timesInUse'];
                                if($currentRuleID==$resCart['promoID'] && $resCart['orderPromoCode']!='') {
                                    $totalUsage = $ObjCart->getRuleUsageCount($currentRuleID,'',$resCart['orderPromoCode'],'C');
                                }
                                if ($promoUsageDetails['maxUsageCount'] > 0 && $totalUsage >= $promoUsageDetails['maxUsageCount']) //max usage error
                                    {
                                    $errorFound = 1;
                                }
                                if ($promoUsageDetails['maxUsagePerPerson'] > 0) //per user checking
                                    {
                                    if ($userEmail != '') {
                                        //Total usage including temp usage
                                        $totalUsage = $ObjCart->getRuleUsageCount($currentRuleID, $userEmail,$resCart['orderPromoCode']) ;//+ $promoUsageDetails['timesInUse'];
                                        if ($totalUsage >= $promoUsageDetails['maxUsagePerPerson']) //per user error
                                            {
                                            $errorFound = 1;
                                        }
                                    }
                                }
                                if ($errorFound == 1) {
                                    if (count($processedPromos) > 1) {
                                        //Remove current/last pushed rule id that caused error
                                        array_pop($processedPromos);
                                        // decrement temp usage count for then processed rules
                                        $ObjCart->updatecartPromoTempUsage(implode(",", $processedPromos), $action = 'decrement');
                                    }
                                    $this->setRedirect("/cart/checkout/");
                                    exit;
                                }
                                // increment temp usage count
                                $ObjCart->updatecartPromoTempUsage($currentRuleID, $action = 'increment');
                            }
                        }
                    }
                }
            }
        }
    }
    //Reupdate Promo Usage
    public function reupdateCartPromoUsage() {
        $ObjCart = new CartModel();
        $cartID  = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $resCart = $ObjCart->getCartDetails($cartID);
        if (!empty($resCart['items'])) {
            $processedPromos = array();
            //Iterate cart items
            foreach ($resCart['items'] as $key => $value) {
                $itemDetails = unserialize($value['itemDetails']);
                if (isset($itemDetails['promotions']) && !empty($itemDetails['promotions'])) {
                    //Iterate each promotion
                    foreach ($itemDetails['promotions'] as $cartPromotions) {
                        $currentRuleID = $cartPromotions['ruleID'];
                        if (!in_array($currentRuleID, $processedPromos)) {
                            //Push to processed promo array
                            $processedPromos[] = $currentRuleID;
                            //Promos with usage restriction will be selected & checked
                            $promoUsageDetails = $ObjCart->getCartPromoUsageDetails($currentRuleID);
                            if (!empty($promoUsageDetails)) {
                                // decrement temp usage count
                                $ObjCart->updatecartPromoTempUsage($currentRuleID, $action = 'decrement');
                            }
                        }
                    }
                }
            }
        }
    }

    /*
         * checking is shipping available for given address
         */
        public function isShippingAvailable($cartID,$productID,$shippingAddress)
        {       //print_r($availableShippingMethods);
                $ObjCart	= new CartModel();
                $needshippingMethodReset = true;
                $shippingZip 		= $shippingAddress['shippingZip'];
                $shippingStateID	= $shippingAddress['shippingStateID'];
                $shippingCountryID 	= $shippingAddress['shippingCountryID'];
                $shippingCity           = $shippingAddress['shippingCity']; //05-03-15
                $shippingStateSelectedType= 'state'; //05-03-15
                $resShippingMethods	= $ObjCart->listShippingMethodsByProductID($cartID,$productID);
                //24-04-15 Start
                $languageIDs       = $this->ObjView->languageIDs;
                $shippingArray = array();
                
                $shippingFreeEnable = $this->getSettingValue('shipping_settings', 'shipping_free_enable');
                $freeShippingAmount = $this->getSettingValue('shipping_settings', 'free_shipping_amount');
                $freeShippingQty 	= $this->getSettingValue('shipping_settings', 'free_shipping_qty');
                //echo "<pre>"; print_r($resShippingMethods);
                
                if(count($resShippingMethods)>0)
                {
                        $shippingParams['shippingZip']			= $shippingZip;
                        $shippingParams['shippingStateID']		= $shippingStateID;
                        $shippingParams['shippingCountryID']	= $shippingCountryID;
                        $shippingParams['shippingStateSelectedType']	= $shippingStateSelectedType;
                        $shippingParams['cartID']				= $cartID;
                        $shippingParams['shippingTaxable']		= $this->_shippingCalculationParam['shippingTaxable'];
                        $shippingParams['shippingCity']	= $shippingCity; //05-03-15
                        $shippingMethodsdeliveryZones = array();
                        foreach ($resShippingMethods as $key => $method)
                        {
                                $itemDetails = unserialize($method['itemDetails']);
                                if($method['settingsGroupID']>0)
                                {
                                        $shippingMethodsdeliveryZones = $ObjCart->listShippingMethodsDeliveryZones($method['shippingtoproductID'],$method['productID']);
                                }
                                $deliveryZoneFound 	= false;
                                $shippingAvilable	= true;
                                $shippingReason = "";
                                $shippingCharge 	= 99999999;
                                unset($ObjShippingLib); 
                                unset($ObjShipping);
                              
                                if(count($shippingMethodsdeliveryZones)>0)
                                {
                                        foreach ($shippingMethodsdeliveryZones as $key1 => $zone)
                                        {
                                                $deliveryZoneDetails = $ObjCart->getDeliveryZoneDetails($languageIDs,$zone['deliveryZoneID']);
                                                if(count($deliveryZoneDetails)>0)
                                                {
                                                        foreach ($deliveryZoneDetails as $key1 => $zoneReg)
                                                        {
                                                                if($zoneReg['countryID']==$shippingCountryID &&  $shippingCountryID>0 )
                                                                {
                                                                        if($zoneReg['StateID']==$shippingStateID && $shippingStateID>0)
                                                                        {
                                                                                if($zoneReg['zipCodes']!='' && $shippingZip!='')
                                                                                {
                                                                                        $zipArray = explode(',',$zoneReg['zipCodes']);
                                                                                        if(in_array($shippingZip,$zipArray))
                                                                                        {
                                                                                                $deliveryZoneFound=true;
                                                                                                break;
                                                                                        }
                                                                                }
                                                                                else if($zoneReg['zipCodes']=='')
                                                                                {
                                                                                        $deliveryZoneFound=true;
                                                                                        break;
                                                                                }
                                                                        }
                                                                        else if($shippingStateSelectedType=='province' && $zoneReg['zipCodes']!='' && $shippingZip!='')
                                                                        {
                                                                                $zipArray = explode(',',$zoneReg['zipCodes']);
                                                                                if(in_array($shippingZip,$zipArray))
                                                                                {
                                                                                        $deliveryZoneFound=true;
                                                                                        break;
                                                                                }
                                                                        }
                                                                        else if($zoneReg['zipCodes']=='' && $zoneReg['StateID']<1)
                                                                        {
                                                                                $deliveryZoneFound=true;
                                                                                break;
                                                                        }
                                                                }
                                                        }
                                                }
                                                if($deliveryZoneFound)
                                                    break;
                                                else{
                                                    $shippingReason = $this->getLanguageValue("lblNoShippingMethodAvilable");
                                                }
                                        }

                                        if($method['settingsGroupID']>0 && $deliveryZoneFound)
                                        {
                                                if($method['settingsGroupKey']=='free_shipping' || $method['settingsGroupParent']==1)
                                                {
                                                        $paramsArray	= array('tableName'=>'cart_items',
                                                        'fieldName'=>'sum(orderItemQuantity) as orderItemQuantity',
                                                        'conditionField'=>'productID',
                                                        'condition'=>'=',
                                                        'conditionValue'=>$method['productID'],
                                                        'conditionField1'=>'cartID',
                                                        'condition1'=>'=',
                                                        'conditionValue1'=>$cartID,
                                                        'conditionFieldType'=>''
                                                        );
                                                        $resOrderItemQty = $ObjCart->getFieldValue($paramsArray);
                                                        if($resOrderItemQty['orderItemQuantity'] >= $method['maxQtyPerShipping'])
                                                        {
                                                                $shippingCharge =0;
                                                                $shippingtype	='Free';
                                                        }
                                                        else
                                                        {
                                                                $shippingAvilable=false;
                                                                $shippingReason = $this->getLanguageValue("lblShipMinQty");
                                                        }
                                                }
                                                else if($shippingFreeEnable !='No')
                                                {
                                                        $resCart          = $ObjCart->getCartDetails($cartID);                                                        
                                                        if($shippingFreeEnable=='Globally')
                                                        {
                                                                $defaultCurrencyId	= $this->ObjView->_defaultCurrency;
                                                                $cartcurrencyId		= $resCart['currencyID'];
                                                                $cartAmount	=	$this->ObjView->convertValueCustom($resCart['orderSubtotal'],
                                                                $cartcurrencyId,$defaultCurrencyId);
                                                                $cartQty	=	$resCart['orderQty'];
                                                                if(($cartAmount > $freeShippingAmount && $freeShippingAmount>0) || ($cartQty > $freeShippingQty && $freeShippingQty>0))
                                                                {
                                                                        if($method['isRealTimeCalculation']=='No')
                                                                        {
                                                                                $shippingCharge =0;
                                                                                $shippingtype	='Free';
                                                                        }
                                                                        else
                                                                        {
                                                                                $shippingAvilable=false;
                                                                                $shippingReason = $this->getLanguageValue("lblNoShippingMethodAvilable");
                                                                        }
                                                                }
                                                                else
                                                                {
                                                                        if($method['isRealTimeCalculation']=='No')
                                                                        {
                                                                                $shippingtype	='Paid';
                                                                        }

                                                                        else
                                                                        {
                                                                                $shippingCharge =100;
                                                                                $shippingtype	='Paid';
                                                                                $shippingAvilable=false;
                                                                                $shippingReason = $this->getLanguageValue("lblNoShippingMethodAvilable");
                                                                        }	
                                                                }
                                                        }
                                                        else if($shippingFreeEnable=='Business wise')
                                                        {
                                                                $businesswiseDetails = $ObjCart->getBusinessWiseCartDetails($method['productID'],$cartID);
                                                                $defaultCurrencyId	= $this->ObjView->_defaultCurrency;
                                                                $cartcurrencyId		= $resCart['currencyID'];
                                                                $cartAmount	=	$this->ObjView->convertValueCustom($businesswiseDetails['orderItemSubtotal'],
                                                                $cartcurrencyId,$defaultCurrencyId);
                                                                $cartQty	=	$businesswiseDetails['orderItemQuantity'];
                                                                if(($cartAmount > $freeShippingAmount && $freeShippingAmount>0) || ($cartQty > $freeShippingQty && $freeShippingQty>0))
                                                                {
                                                                        if($method['isRealTimeCalculation']=='No')
                                                                        {
                                                                                $shippingCharge =0;
                                                                                $shippingtype	='Free';
                                                                        }
                                                                        else
                                                                        {
                                                                                $shippingAvilable=false;
                                                                                $shippingReason = $this->getLanguageValue("lblNoShippingMethodAvilable");
                                                                        }
                                                                }
                                                                else
                                                                {
                                                                        if($method['isRealTimeCalculation']=='No')
                                                                        {
                                                                                $shippingtype	='Paid';
                                                                        }

                                                                        else
                                                                        {
                                                                                $shippingCharge =100;
                                                                                $shippingtype	='Paid';
                                                                                $shippingAvilable=false;
                                                                                $shippingReason = $this->getLanguageValue("lblNoShippingMethodAvilable");
                                                                        }	
                                                                }
                                                        }
                                                }
                                                else
                                                {
                                                        if($method['isRealTimeCalculation']=='No')
                                                        {
                                                                $shippingtype	='Paid';
                                                        }
                                                        else
                                                        {
                                                                $shippingCharge =100;
                                                                $shippingtype	='Paid';
                                                                $shippingAvilable=false;
                                                                $shippingReason = $this->getLanguageValue("lblNoShippingMethodAvilable");
                                                        }	
                                                }
                                                if($shippingAvilable)
                                                {
                                                        $subArray=array(
                                                        'methodName'=>$method['settingsGroupXmlLabel'],
                                                        'methodID'=>$method['settingsGroupID'],
                                                        'shippingCharge'=>$shippingCharge,
                                                        'shippingtype'=>$shippingtype,
                                                        'settingsGroupKey'=>$method['settingsGroupKey'],
                                                        'settingsGroupParent'=>$method['settingsGroupParent']
                                                        );
                                                        //$shippingArray[$method['productID']]['methods'][$method['settingsGroupID']]=$subArray;
                                                        
                                                        $shippingArray[$key][0] =$method['settingsGroupID'];
                                                        $shippingArray[$key]['shippingServiceID'] = $method['settingsGroupID'];
                                                        $shippingArray[$key][1] = $method['settingsGroupXmlLabel'];
                                                        $shippingArray[$key]['settingsGroupXmlLabel'] = $method['settingsGroupXmlLabel'];
                                                }
                                        }
                                }	
                                else{
                                    $shippingReason = $this->getLanguageValue("lblNoShippingMethodAvilable");
                                }
                              //  $shippingArray[$method['productID']]['itemName']=$itemDetails['productOptionName'];
                               // $shippingArray[$method['productID']]['shippingMethodID']=$itemDetails['shippingMethod']['methodID'];

                        }
                }
                //print_r($shippingArray);
                if(count($shippingArray)> 0)
                { //shipping available assign shipmethod
//                        foreach ($shippingArray as $key => $method)
//                        {
//                                if(count($method['methods'])>0)
//                                {
//                                        foreach ($method['methods'] as $key1 => $shippingMethod)
//                                        {
//                                                $shippingParams['productID']				= $key;
//                                                $shippingParams['settingsGroupID']		= $shippingMethod['methodID'];
//                                                if($shippingMethod['settingsGroupKey']!='' && $shippingMethod['shippingtype']=='Paid')
//                                                {
//                                                        $paramsArray	= array('tableName'=>'shipping_methods',
//                                                        'fieldName'=>'settingsGroupKey',
//                                                        'conditionField'=>'settingsGroupID',
//                                                        'condition'=>'=',
//                                                        'conditionValue'=>$shippingMethod['settingsGroupParent'],
//                                                        'conditionFieldType'=>'int'
//                                                        );
//                                                        $resshippingGateWayKey = $ObjCart->getFieldValue($paramsArray);
//
//                                                        $shippingGateWayKey  = $resshippingGateWayKey['settingsGroupKey'];
//                                                        $ObjShippingLib 	= new Shipping($shippingGateWayKey);
//                                                        $ObjShipping		= $ObjShippingLib->getShippingObject();
//                                                        if(!is_object($ObjShipping))
//                                                        {
//                                                                continue;
//                                                        }
//                                                        else
//                                                        {
//                                                                list($shippingTax,$shippingCharge) =$ObjShipping->getShippingRate($shippingParams);
//                                                                $needshippingMethodReset = false;
//                                                        }
//                                                        $shippingArray[$key]['methods'][$key1]['shippingCharge']=$shippingCharge;
//                                                        $shippingArray[$key]['methods'][$key1]['shippingTax']=$shippingTax;
//                                                }
//
//                                        }	
//                                }
//                        }
                    $result = array($shippingArray,"success");
//                    return $shippingArray;
                    return $result;
                }
                else{
                    $result = array(array(),$shippingReason);
                    return $result;
                }
//                else
//                {
//
//                        $ObjCart->resetShippingMethod($cartID);
//                }
        }
            // FUNCTION FOR CART PAGE SHIPPING METHOD SAVE
        public function ajaxSaveShipMethodAction() {
            $ObjCart	= new CartModel();
            $cartID=$_POST['cartId'];
            $productID=$_POST['productId'];
            if(isset($_POST['currentPage'])){
                $curpage = $_POST['currentPage'];
            }
            $methodID=($_POST['methodId']>0)?$_POST['methodId']:0;
            if($cartID > 0 && $productID > 0 && $methodID > 0)  {
                //$resUpdateShippingMethod		=	$ObjCart->updateShippingMethod($cartID,$productID,$methodID);
                //24-04-15 Start
                $languageIDs                            = $this->ObjView->languageIDs;
                $resUpdateShippingMethod		=	$ObjCart->updateShippingMethod($cartID,$productID,$methodID);
                $userID			= $this->ObjSession->getSession("REGISTERED_USER_ID");
                if($userID > 0){
                    //for checkout page consider the filled shipping info
                    if($curpage == 'checkout')
                    {
                       $resCart 	= $ObjCart->getCartDetailsAll($languageIDs,$cartID,0);
                       $resCart['cartDetails']= unserialize($resCart['extra']);
                       $adrsType = 'Shipping';
                       $arrAddress	= $resCart['cartDetails']['userShippingAddress'];
                    }
                    else
                    {
                        $shippingAddress = $ObjCart->getUserDefaultShippingAddress($userID);
                        if(count($shippingAddress) > 0){ 
                           //update cart item shipping address with default address
                            $adrsType = 'Shipping';
                            $arrAddress	= array(
                                                                   'shippingFname' 	=> $shippingAddress['shippingFname'],
                                                                   'shippingLname' 	=> $shippingAddress['shippingLname'],
                                                                   'shippingAddress' 	=> $shippingAddress['shippingAddress1'],
                                                                   'shippingAddress2' 	=> $shippingAddress['shippingAddress2'],
                                                                   'shippingCity' 		=> $shippingAddress['shippingCity'],
                                                                   'shippingProvince' 	=> (isset($shippingAddress['shippingProvince'])?$shippingAddress['shippingProvince']:''),
                                                                   'shippingZip' 		=> $shippingAddress['shippingZip'],
                                                                   'shippingStateID' 	=> (isset($shippingAddress['shippingStateID'])?$shippingAddress['shippingStateID']:0),
                                                                   'shippingCountryID' => $shippingAddress['shippingCountryID']
                                                           );
                        }
                    }
                    $resCartUpdate	= $ObjCart->updateUserCartAddress($userID,$cartID,$arrAddress,$adrsType);
                    $resResetCartTotals		= $ObjCart->calculateShippingRate($cartID,$this->_shippingCalculationParam,'from');
                }else{
                    $resResetCartTotals		= $ObjCart->calculateShippingRate($cartID,$this->_shippingCalculationParam);
                }
                //$returnData['status']="Shipping Method Changed";
                // $resShippingCalc	= $ObjCart->calculateShippingRate($cartID,$this->_shippingCalculationParam);
            }else if($cartID > 0 && $productID > 0)  {
                $resUpdateShippingMethod		=	$ObjCart->deleteShippingMethod($cartID,$productID);
                //$returnData['status']="Shipping Method Removed";
                 //$resShippingCalc	= $ObjCart->calculateShippingRate($cartID,$this->_shippingCalculationParam);
            }else{
                $returnData['status']="Not Change";
            }
            
            //$resResetCartTotals		= $ObjCart->calculateShippingRate($cartID,$this->_shippingCalculationParam,'cart_shipping_chaege');
            $promoResult    		= $this->setPromoCodeDiscount('','','','checkout');

            $resResetCartTotals 	= $ObjCart->resetCartTotals($cartID);
            $resCart 	= $ObjCart->getCartDetails($cartID,0);
            if(count($resCart['items'])>0) {
                    foreach ($resCart['items'] as $key => $items) {
                    $resCart['items'][$key]['itemDetails']=unserialize($items['itemDetails']);
                    }	
            }
            $this->ObjView->assign('cartData', $resCart);
            if($curpage == 'checkout')
            {
                $settingsEnablePromoCode = $this->getSettingValue('product_cart_settings', 'enable_promo_codes');
		$this->ObjView->assign('enablePromoCode', $settingsEnablePromoCode);
                $settingsApplyAfterDiscount = $this->getSettingValue('product_cart_settings', 'apply_after_discount');
                $this->ObjView->assign('enableApplyAfterDiscount', $settingsApplyAfterDiscount);
                $this->ObjView->assign('userID', $userID);
                $html = $this->ObjView->fetch('cart/CheckoutOrderSummary.tpl');
                //$html = $this->ObjView->fetch('cart/CheckoutOrderDetails.tpl');
                //17-04-15 START
                $this->ObjView->assign('orderTotalAmount', $resCart['orderTotalAmount']);
                $this->ObjView->assign('shippingAmount', $resCart['shippingAmount']);
                $this->ObjView->assign('cartDatacurrencyID', $resCart['currencyID']);
                $this->ObjView->assign('cartUsercurrencyID', $resCart['userCurrencyID']);
                $returnData['htmlShipp'] = $this->ObjView->fetch('cart/CartShippingTotal.tpl');
                $returnData['totordamt'] = $resCart['orderTotalAmount'];
                //17-04-15                
            }else{
                $html = $this->ObjView->fetch('cart/CartTotal.tpl');
            }
            
            $returnData['html'] = $html;
            echo json_encode($returnData);
            return true;

           // echo json_encode($returnData);
            //return true;
        }

    public function ajaxAddItemCartAction() {
        $ObjProductList                      = new ProductListModel();
        $ObjCart                             = new CartModel();
        $ObjProduct                          = new ProductModel();
        $languageIDs                         = $this->ObjView->languageIDs;	
        $cartID                              = $this->ObjSession->getSession("CARTID");	
        $cartID                  			 = $this->decodeString($cartID);	
			
			//print_r($_POST['bundleProduct']);	//exit;
		/* $_POST['quantity']               = 1;
		$postArray[0]['product_id']=290;
		$postArray[0]['productOptionID']=372;	
		$postArray[0]['quantityBox']=1;
		$postArray[1]['product_id']=43;
		$postArray[1]['productOptionID']=50;
		$postArray[1]['quantityBox']=1;
		$postArray[2]['product_id']=286;
		$postArray[2]['productOptionID']=367;
		$postArray[2]['quantityBox']=1;	 */	
		foreach($_POST['bundleProduct'] as $key=>$record){
			  $bundleProduct         = explode("-", $record);
			 
		 $productID=$_POST['productID']  = $bundleProduct[0];
		$_POST['productOptionID'] =$bundleProduct[1] ;
		$_POST['quantityBox']=(!empty($record['quantityBox']) && isset($record['quantityBox']) && ($record['quantityBox']))>0? $record['quantityBox']  :1;			
			$product_id 		  = $productID;
			$productOptionID 	 = $bundleProduct[1];
			$quantity 		 	  = $_POST['quantityBox'];
			$_POST['sameItem']=	$sameItem			  =	'No';
			
        $productType          = array(
            'productTypeID' => 1,
            'productTypeKey' => 'product_product',
            'productTypeUrlKey' => '',
            'isFeatured' => 1,
            'limitMainListing' => '',
            'limitDefListing' => '',
            'productTypeName' => $this->getLanguageValue('lblProducts')
        );			
        $args                 = array(
            'requestedBy' => 'customer',
            'requestPage' => 'product_detail',
            'limitFrom' => 0,
            'limitTo' => 1,
            'languageIDs' => $languageIDs,
            'productType' => $productType,
            'selectedProductID' => $product_id,
            'selectProductOpID' => $productOptionID,
            'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID,
            'productStatus' => 'Active',
            'bundleProd' => 'Yes'
        );
        $currProductProduct = $ObjProduct->getProductDetails($args);
        //echo "<pre>"; print_r($currProductProduct); exit;

    
            $optionQuantityUnlimited = $currProductProduct[0]['productQuantityUnlimited']     = ($currProductProduct[0]['productQuantityUnlimited'] == "") ? 0 : $currProductProduct[0]['productQuantityUnlimited'];	
			
            $currProductProduct[0]['productOptionQuantitySum']     = ($currProductProduct[0]['productOptionQuantitySum'] == "") ? 0 : $currProductProduct[0]['productOptionQuantitySum'];
			
            $optionQuantity=$currProductProduct[0]['productOptionQuantity']           = ($currProductProduct[0]['productOptionQuantity'] == "") ? 0 : $currProductProduct[0]['productOptionQuantity'];
			
			
            $minBuyLimit	= $currProductProduct[0]['productMinBuyLimit']           = ($currProductProduct[0]['productMinBuyLimit'] == "") ? 0 : $currProductProduct[0]['productMinBuyLimit'];
			

           $maxBuyLimit= $currProductProduct[0]['productMaxBuyLimit']           = ($currProductProduct[0]['productMaxBuyLimit'] == "") ? 0 : $currProductProduct[0]['productMaxBuyLimit'];
		   
			$productDefaultCurrency		=   $currProductProduct[0]['productDefaultCurrency'];
                if (isset($productOptionID) && $productOptionID > 0) {
                    $params                        = array(
                        'languageIDs' => $languageIDs,
                        'productID' => $product_id,
                        'productOptionID' => $productOptionID,
                        'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
                    );
                    $currProductProduct['options'] = $ObjProductList->fetchProductOptionsInfo($params);
                }			

			if($cartID>0)
			{
				$itemParams['cartID'] 		= $cartID;
				$itemParams['productOptionID'] 	= $productOptionID;
                        $itemParams['bundleID'] 	= $_POST['bundleID'];
				$itemExistsArray = $this->checkItemAlreadyExists($itemParams);
				if($itemExistsArray['sameItem']=="Yes")
				{
					$items = $itemExistsArray['existingItemArray'];
					$sameItem='Yes';
					$quantity = $quantity + $items['orderItemQuantity'];
					$cartItemID = $items['cartItemID'];
					$itemDetails 		= 	unserialize($items['itemDetails']);	
					
					
					if ($productDefaultCurrency != $itemDetails['productDefaultCurrency']) {
                        					$resArray = array(
						'isError'	=>	'Yes',
						'error'	    =>	$this->getLanguageValue("lblCartCurrencyNotMatching")
						);
						echo json_encode($resArray);
						exit;

					} else if ($optionQuantityUnlimited < 1 && $optionQuantity - ($items['orderItemQuantity']) < $_POST['quantityBox']) {
					$resArray = array(
						'isError'	=>	'Yes',
						'error'	    =>	$this->getLanguageValue("lblCartStockNotAvailable")
					);
					echo json_encode($resArray);
					exit;	
         
        }				
				}	
			 
			}	
        if ($quantity < $minBuyLimit) {
			$quantity =$minBuyLimit;
        } 
		if ($optionQuantityUnlimited < 1 && $optionQuantity < $quantity) {
					$resArray = array(
						'isError'	=>	'Yes',
						'error'	    =>	$this->getLanguageValue("lblCartStockNotAvailable")
					);
					echo json_encode($resArray);
					exit;		
       
    } else {

        if (( $quantity) > $maxBuyLimit && $maxBuyLimit > 0 ) {
            					$resArray = array(
						'isError'	=>	'Yes',
						'error'	    =>	$this->getLanguageValue("lblCartYouHaveExceededLimit")
					);
					echo json_encode($resArray);
					exit;	
           
        }

        if ($productDefaultCurrency < 1) {
            					$resArray = array(
						'isError'	=>	'Yes',
						'error'	    =>	$this->getLanguageValue("lblCartInvalidCurrencyConfig")
					);
					echo json_encode($resArray);
					exit;
            
        }

	}	
		$_POST['businessKey']			=	$currProductProduct[0]['businessKey'];
		$_POST['productImage']	   	    =	$currProductProduct[0]['productImage'];
		$_POST['productOptionName']     =	$currProductProduct['options'][0]['productOptionName'];
		$_POST['productTitle']		    =	$currProductProduct[0]['productTitle'];
		$_POST['productDefaultCurrency']=	$currProductProduct[0]['productDefaultCurrency'];
		$_POST['quantity']				=	$quantity;
		$_POST['giveAsGift']			=	'No';
		$_POST['bundleProduct']			=       'Yes';
                $_POST['existItemID']			=       0;
                $_POST['currbusinessid']=	$currProductProduct[0]['businessID'];
                
			if($sameItem=='No')
			{
				$this->ajaxAddItemAction();
			}
			else
			{
                        
                        $_POST['existItemID']		=       $itemExistsArray['existingItemArray']['cartItemID'];
				$this->ajaxUpdateQuantityAction();
			}			
		}			
                    //  $this->setRedirect("/cart/"); 		
		
	}	
	private function checkItemAlreadyExists($params=array())
	{
		extract($params);
		
		$ObjCart   			= new CartModel();
		$cartID    			= isset($cartID)?$cartID:0;
		$productOptionID    		= isset($productOptionID)?$productOptionID:0;
		$returnArray['sameItem'] = 'No';
		$returnArray['existingItemArray'] = array();
		
		if($cartID>0)
		{
			$existingItemQuantity = 0;
			$cart_items = $ObjCart->getCartItems($cartID);
			foreach($cart_items as $items)
			{
                                $extra          =   unserialize($items['itemDetails']);
                                
				if($items['productOptionID'] == $productOptionID && $extra['bundleID']==$bundleID && $bundleID>0)
				{
					$_POST['sameItem'] =$returnArray['sameItem'] = 'Yes';
					$returnArray['existingItemArray'] = $items;
					break;
					
				}
			}
		}
		return $returnArray;
	}
        public function ajaxSetGotItAction() {
            $this->ObjCookie->setCookie('BUYGOTIT', 'Yes');
            echo '1';exit;
        }
        public function sendsmsToUser($getOrderDetails) {
            $ObjOrder   			= new OrderModel();
            $ObjCurrency = new CurrencyModel();
            $purchasedCurrencyDetails = $ObjCurrency->getCurrencyByCurrencyID($getOrderDetails['userCurrencyID']);
            $currencyCode             = $purchasedCurrencyDetails['currencyCode'];
            $billingInfo     = unserialize($getOrderDetails['billingAddress']);
            $username=$this->getSettingValue('sms_api_settings','sms_username');
            $password=$this->getSettingValue('sms_api_settings','sms_password');
            $senderID=$this->getSettingValue('sms_api_settings','sms_sender_id');
            $ApiUrl=$this->getSettingValue('sms_api_settings','api_url');
            $number=$billingInfo['billingPhone'];
            $value=$getOrderDetails['orderNumber'];
            $price=$getOrderDetails['orderTotalAmount'];
            $PCJStatus ='Order_Place'; 
            $template_id=1;
            $smsTemplate=$ObjOrder->getSmsTemplate($template_id);
            $msg = $smsTemplate['smsText'];
            $price=round($price,2);
            $price=$currencyCode.' '.$this->ObjView->getFormattedCurrencyReport($price, '',  $getOrderDetails['purchasedCurrency'],$getOrderDetails['userCurrencyID']);
            $msg = str_replace("#Price",$price,$msg);	
            $msg = str_replace("#OrderId",$value,$msg);
            $msg=str_replace(" ","+",$msg);
            if(trim($username) && trim($password) && trim($ApiUrl))
            {
             $page =$ApiUrl."mobnum=".$number."&apiuid=".$username."&apipswd=".$password."&apiflag=".$PCJStatus."&order_number=".$value."&price=".$price;
             $sms = new Sms();
            $result = $sms->curlUsingGet($page);
            }
           
        }
        function curlUsingGet($url,$query_string)
        {

            $Curl_Session = curl_init($url);
            curl_setopt ($Curl_Session, CURLOPT_POST, 1);
            curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, $query_string);
            curl_setopt ($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($Curl_Session, CURLOPT_RETURNTRANSFER,1);
            $result=curl_exec ($Curl_Session);
            return $result;
        }
        
        //Signup Process
    public function signupProcess($params = array()) {
        $isAjax                       = true; //For Handling AJAX and Direct page Request
        $returnArray['error']         = 'No';
        $returnArray['errorMessage']  = '';
        $returnArray['formSubmitted'] = 0;
        $isFacebook = 0;
        if (!empty($params)) {
            if (isset($params['ajaxRequest']) && $params['ajaxRequest'] == "0") {
                $isAjax = false;
            }
        }
        $ObjUser          = new UserModel();
        $ObjEmailtemplate = new EmailtemplateModel();
        $ObjCart          = new CartModel();
        $languageIDs      = $this->ObjView->languageIDs;
        
            //Form Submitted
            $returnArray['formSubmitted'] = 1;
            //if (!$isFacebook) {
                $cartID				= $this->decodeString($this->ObjSession->getSession("CARTID"));
                $arrExtraData = $ObjCart->getUnserializedCartData($cartID);
                $params['userCheckoutEmail'] = $arrExtraData['userCheckoutEmail'];
                $isValidEmail = $this->validateEmail($params['userCheckoutEmail'], $isAjax);
                if ($isValidEmail['error'] == "Yes") {
                    $returnArray['error']        = 'Yes';
                    $returnArray['errorMessage'] = $isValidEmail['errorMessage'];
                    return $returnArray;
                }
                $params['userCurrentLanguage'] = $languageIDs['Current'];
                $params['userDefaultLanguage'] = $languageIDs['Current'];
                
                $params['userFirstName'] = trim(stripslashes($params['shippingFname']));
                $params['userLastName'] = trim(stripslashes($params['shippingLname']));
                $params['userEmail'] = $params['userCheckoutEmail'];
                //$params['userPassword'] = $params['userPassword']
                $params['userPhone'] = $params['shippingPhone'];
                $params['userAdress1'] = trim(stripslashes($params['shippingAddress']));
                $params['userAdress2'] = trim(stripslashes($params['shippingAddress1']));
                $params['userCity'] = trim(stripslashes($params['shippingCity']));
                $params['userGroupID'] = 0;
                $params['countryID'] = trim(stripslashes((isset($params['shippingCountry']) ? $params['shippingCountry'] : 0)));
                $params['stateID'] = trim(stripslashes((isset($params['shippingState']) ? $params['shippingState'] : 0)));
                $params['userProvince'] = trim(stripslashes((isset($params['shippingProvince']) ? $params['shippingProvince'] : '')));
                $params['userZip'] = trim(stripslashes($params['shippingZip']));
//                $params['stateSelectedType'] = $params['shippingFname'];
//                $params['userEmailNewsLetter'] = $params['shippingFname'];
//                $params['userNewsLetterMode'] = $params['shippingFname'];
                $params['userStatus'] = 'Active';
                $user                         = $ObjUser->saveUserDetails($params, ''); 
                
            /*} else //Facebook
                {
                $user = $ObjUser->saveFbUserDetails($facebookUserData);
            }*/
            if ($user) {
                 
                //set cookie
                $resUserDetails = $ObjUser->getBasicUserDetails($user, array(
                    "userID",
                    "userGroupID",
                    "userFirstName",
                    "userLastName",
                    "userEmail",
                    "userDefaultLanguage"
                ));
                $userID         = $resUserDetails['userID'];
                $userGroupID    = $resUserDetails['userGroupID'];
                $userName       = $resUserDetails['userFirstName'] . " " . $resUserDetails['userLastName'];
                //Set User Session
                $sessionParams  = array(
                    "userID" => $userID,
                    "userGroupID" => $userGroupID,
                    "userEmail" => $resUserDetails['userEmail'],
                    "userName" => $userName,
                    "userDefaultLanguage" => $resUserDetails['userDefaultLanguage']
                );
                $this->setUserSessions($sessionParams);
                
                $ObjCart->linkOrderToUser($userID, $resUserDetails['userEmail']);
                $this->ObjSession->unsetSession("GUEST_ORDER_ID");
                $this->ObjSession->unsetSession("GUEST_EMAIL_ID");
                if (__ANALYTICS_MODULE || __AFFILIATE_MODULE) {
                    $this->signUpTracking($userID);
                }
                //MIC
                
                $cartID = $this->decodeString($this->ObjSession->getSession("CARTID"));
                if ($cartID > 0) {
                    $ObjCart->updateCartUserID($cartID, $userID);
                    $ObjCart->resetCartItemsTierPrice($cartID, $userGroupID);
                }
                
                $siteName    = $this->getSettingValue('site_settings', 'site_name');
                $siteUrl     = $this->getSettingValue('site_settings', 'global_http_url');
                $companyLogo = $this->getSettingValue('company_information', 'company_logo');
                $this->ObjView->assign('companyLogo', $companyLogo);
                //TO ADMIN
                $languageIDsCustom            = $languageIDs;
                $languageIDsCustom['Current'] = $languageIDs['Default'];
                $emailbody                    = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustom, '', 'new-user-signup');
                $from                         = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                $to                           = $this->getSettingValue('site_settings', 'global_notification_email');
                $userName                     = $params['userFirstName'] . ' ' . $params['userLastName'];
                //email body
                $bodytag                      = str_replace('{$userEmailID}', $params['userEmail'], $emailbody['emailHtml']);
                $bodytag                      = str_replace('{$name}', $params['userFirstName'] . " " . $params['userLastName'], $bodytag);
                $bodytag                      = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $body                           = $this->ObjCommon->fetch('email_templates/Layout.tpl', $languageIDsCustom);
                $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, $to, $emailbody['emailSubject'], $body);
                if ($ObjMail->Send()) {
                }
                //TO USER
                $emailbody = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-login-details');
                $from      = array(
                    $emailbody['emailFromEmail'],
                    $emailbody['emailFromName']
                );
                //email body
                if (!$isFacebook) {
                    $bodytag = str_replace('{$userEmailID}', $params['userEmail'], $emailbody['emailHtml']);
                    $bodytag = str_replace('{$userPassword}', $params['userPassword'], $bodytag);
                } else {
                    $bodytag           = $emailbody['emailHtml'];
                    //Remove Login details for facebook
                    $extractedTemplate = $this->getTemplateDetails('SITE_USER', $bodytag);
                    $bodytag           = str_replace($extractedTemplate, '', $bodytag);
                }
                $bodytag = str_replace('{$userName}', $userName, $bodytag);
                $this->ObjView->assign('emailbody', $bodytag);
                $this->ObjView->assign('siteUrl', $siteUrl);
                $this->ObjView->assign('siteName', $siteName);
                $body                           = $this->ObjCommon->fetch("email_templates/Layout.tpl");
                $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, $_POST['userEmail'], $emailbody['emailSubject'], $body);
                if ($ObjMail->Send()) {
                    
                }*/
                if ($isAjax && !$isFacebook) {
                        //echo "success";
                        return $returnArray;
                        exit;
                    } else {
                        return $returnArray;
                    }
            } else {
                if (!$isFacebook) {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errLoginExists");
                } else //Facebook
                    {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errorSignup");
                }
                $returnArray['error'] = 'Yes';
                return $returnArray;
            }
        
        ////////////////////////
        return $returnArray;
    }
    
    //Function for Validating Email
    public function validateEmail($email, $ajax = true) {
        $returnArray['error']        = "No";
        $returnArray['errorMessage'] = "";
        if ($this->getSettingValue('security_settings', 'verify_email_using') != "disabled" && $email != '') {
            $security_settings = $this->getSettingValue('security_settings');
            $validateEmail     = new Validateemail($security_settings);
            $valid             = $validateEmail->validate($email, $this->getSettingValue('site_settings', 'global_notification_email'));
            if (!$valid) {
                if ($ajax) {
                    echo $this->getLanguageValue("errValidEmail");
                    exit;
                } else {
                    $returnArray['error']        = "Yes";
                    $returnArray['errorMessage'] = $this->getLanguageValue("errValidEmail");
                }
            }
        }
        return $returnArray;
    }
    
    public function signUpTracking($userID) {
        $ObjLog            = new AnalyticsModel();
        $visitorID         = $this->ObjCookie->getCookie("GT_VISITORID");
        $resVisitorDetails = $ObjLog->getDetails($visitorID);
        //Fetching Current Visitor Details										
        $userIDDb          = $resVisitorDetails['userID'];
        if (!$userIDDb || ($userIDDb == $userID)) {
            if (__ANALYTICS_MODULE) {
                //===================FLAG==============
                $updateVisitorInfo = $ObjLog->updateVisitorType($visitorID, $userID, "user");
                //===================FLAG==============
            }
        }
        if ($visitorID) {
            $ObjLog->updateVisitorActions($visitorID, 'signup');
        }
        //############# Affiliate Registration Commission #########################//
        
        $this->saveAffiliateRegCommission($userID, $visitorID);
        //############# Affiliate Registration Commission #########################//
        $campaignID = $this->ObjCookie->getCookie("EMAIL_CAMPAIGN_ID");
        if ($campaignID > 0) {
            $ObjLog->updateCampaignDetails($campaignID, 'signup');
        }
    }
    
    //Function to save Affiliate Commission
    public function saveAffiliateRegCommission($userID, $visitorID) {
        
        if (__AFFILIATE_MODULE) {
            $ObjAffiliate         = new AffiliateModel();
            $affiliateUserID      = $this->ObjCookie->getCookie("affiliateUserID");
            $affiliate_active     = $ObjAffiliate->getAffiliateStatus($affiliateUserID);
            $resVisitorID         = $ObjAffiliate->getAffVisitorID($visitorID);
            $individualCommission = $ObjAffiliate->getAffCommissionSettings($affiliateUserID, 'signup');
            $affVisitorID         = $resVisitorID['affVisitorID'];
            if (($affiliate_active['affiliateStatus'] == 'Active') && (__AFFILIATE_ENABLE) && ($this->getSettingValue('affiliate_settings', 'affiliate_registeration_commission') == 'Yes') && ($individualCommission['registrationCommission'] == 'Yes') && $individualCommission['registrationCommissionAmount'] > 0) {
                $registrationAmount     = $individualCommission['registrationCommissionAmount'];
                $resAffiliateCommission = $ObjAffiliate->saveCommissionDetails($affVisitorID, $affiliateUserID, $registrationAmount, 'Registration', $userID);
            }
            //save Aff Performance
            $ObjAffiliate->saveAffiliatePerformance($visitorID, $userID, 'Registration');
        }
        
    }
    
    public function setUserSessions($params = array()) {
        extract($params);
        $this->ObjSession->setSession("REGISTERED_USER_ID", $userID);
        $this->ObjSession->setSession("REGISTERED_USER_GROUP_ID", $userGroupID);
        $this->ObjSession->setSession("REGISTERED_USER_EMAIL", $userEmail);
        $this->ObjSession->setSession("REGISTERED_USER_NAME", $userName);
        $this->ObjSession->setSession("REGISTERED_USER_LANG_ID", $userDefaultLanguage);
        //Timeout
        $timeout = trim($this->getSettingValue('security_settings', 'security_user_timeout'));
        if ($timeout != '') {
            $this->ObjSession->setSession("TIMEOUT", time());
        }
		
    }
	public function ajaxgetpincodeAction()
        {
            $languageIDs  =   $this->ObjView->languageIDs;
            $ObjPincode   =   new PincodeModel(); 
            $pincode      =   $_POST['pincode'];   
            
            $resCheck     =   $ObjPincode->checkPincodeAvailability($languageIDs,$pincode,'','','Y');			
            echo json_encode($resCheck);exit;
        }
    public function ajaxGetMidTransTokenAction()
    {
        $order_id   = trim($_POST['order_id']);
        $payby = trim($_POST['payby']);
        $ObjPaymentgateway = new PaymentgatewayModel();
        $ObjCurrency = new CurrencyModel();  
        $ObjCart = new CartModel();
        
        if($payby!='') {
        //============================================================
            $paramsArray             = array(
                'tableName' => 'payment_settings_group',
                'fieldName' => 'paySetGroupID',
                'conditionField' => 'paySetGroupKey',
                'condition' => '=',
                'conditionValue' => $payby,
                'conditionFieldType' => ''
            );
            $resPaymentSettings      = $ObjCart->getFieldValue($paramsArray);
            $paySetkeys = array('payment_currency','payment_gateway_url','server_key');
            $settingsVars      = $ObjPaymentgateway->listPaymentSettingsValueByGroupId($resPaymentSettings['paySetGroupID'],  $paySetkeys);
        }
        $order      = $ObjCart->getOrderMasterDetailsByOrderID($order_id);
       // $orderItems = $ObjCart->getOrderItemDetailsByParentOrderID($order_id);
        $currencyArr     = '';
        $paymentCurrency = $settingsVars["payment_currency"];
        if ($paymentCurrency != '') {
            $paymentCurrency = str_replace(", ", ",", $paymentCurrency);
            $currencyArr     = explode(",", $paymentCurrency);
        }
        if (count($currencyArr) < 1) {
                 $resArray = array(
                    'isError'	=>	'Yes',
                    'errorMessage'	    =>	"Currency not configured , Please contact the site admin"
                    );
                    echo json_encode($resArray);
                    exit;
        } else {
            $currencyFlag             = false;
            $purchasedCurrencyDetails = $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
            $currencyCode             = $purchasedCurrencyDetails['currencyCode'];
            $systemCurrencies         = $ObjCurrency->listCurrencyCodes();
            if (!in_array($purchasedCurrencyDetails['currencyCode'], $currencyArr)) {
                foreach ($systemCurrencies as $key => $currency) {
                    if (in_array($currency['currencyCode'], $currencyArr)) {
                        $currencyFlag          = true;
                        $supportedCurrencyCode = $currency['currencyCode'];
                        $supportedCurrencyID   = $currency['currencyID'];
                        break;
                    }
                }
                if ($currencyFlag == true) {
                    $payAmount    = $ObjCurrency->convertValueCustom($payAmount, $order["purchasedCurrency"], $supportedCurrencyID);
                    $currencyCode = $supportedCurrencyCode;
                } else {
                    $resArray = array(
                    'isError'	=>	'Yes',
                    'errorMessage'	    =>	"Currency not configured , Please contact the site admin"
                    );
                    echo json_encode($resArray);
                    exit;
                }
            }
        }
       // $payment_url            = $settingsVars["payment_gateway_url"];
        $auth_key = base64_encode($settingsVars["server_key"].':');
        $order['billingAddress']  = unserialize($order['billingAddress']);
        $order['shippingAddress'] = unserialize($order['shippingAddress']);
        $customer_email       	= $order['billingAddress']['billingEmail'];
        $curl = curl_init();
        //$ord_json ='';
//        foreach($orderItems as $key => $orderItem){
//                if($key>0)$ord_json .= ',';
//                $ord_json .= '{
//                    "id": "'.$orderItem['orderItemID'].'",
//                    "price": '.(int)$orderItem['orderItemSubtotal'].',
//                    "quantity": '.$orderItem['orderItemQuantity'].',
//                    "name": "'.$orderItem['productOptionName'].'",
//                    "brand": "Midtrans",
//                    "category": "Toys",
//                    "merchant_name": "'.$settingsVars['merchant_identifier'].'"
//                  }';
//            }
            //"item_details": ['.$ord_json.'],
            if($payby=='midtransnetbanking'){
                $json_type = ',
"enabled_payments": ["bank_transfer"] ';
            } else {
                $json_type = ',
"enabled_payments": ["credit_card"],
"credit_card": {
"save_card": true,
"secure": true,
"channel": "migs",
"bank": "maybank",
"installment": {
"required": false,
"terms": {
"bni": [3, 6, 12],
"mandiri": [3, 6, 12],
"cimb": [3],
"bca": [3, 6, 12],
"offline": [6, 12]
}
}
}';
            }
$json = '{
  "transaction_details": {
    "order_id": "'.$order_id.'",
    "gross_amount": '.(int)$order['orderTotalAmount'].'
  },  
  "customer_details": {
    "first_name": "'.$order['billingAddress']['billingFirstName'].'",
    "last_name": "'.$order['billingAddress']['billingLastName'].'",
    "email": "'.$customer_email.'",
    "phone": "'.$order['billingAddress']['billingPhone'].'",
    "billing_address": {
      "first_name": "'.$order['billingAddress']['billingFirstName'].'",
      "last_name": "'.$order['billingAddress']['billingLastName'].'",
      "email": "'.$order['billingAddress']['billingEmail'].'",
      "phone": "'.$order['billingAddress']['billingPhone'].'",
      "address": "'.str_replace(array("\r\n","\r"),"",$order['billingAddress']['billingAddress']).'",
      "city": "'.$order['billingAddress']['billingCity'].'",
      "postal_code": "'.$order['billingAddress']['billingZip'].'",
      "country_code": "IDN"
    },
    "shipping_address": {
      "first_name": "'.$order['shippingAddress']['shippingFname'].'",
      "last_name": "'.$order['shippingAddress']['shippingLname'].'",
      "email": "'.$customer_email.'",
      "phone": "'.$order['shippingAddress']['shippingPhone'].'",
      "address": "'.str_replace(array("\r\n","\r"),"",$order['shippingAddress']['shippingAddress']).'",
      "city": "'.$order['shippingAddress']['shippingCity'].'",
      "postal_code": "'.$order['shippingAddress']['shippingZip'].'",
      "country_code": "IDN"
    }
  }'.$json_type.'}';
curl_setopt_array($curl, array(
              CURLOPT_URL => $settingsVars['payment_gateway_url'],
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => "",
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 30,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => "POST",
              CURLOPT_POSTFIELDS => $json,
              CURLOPT_HTTPHEADER => array(
                "accept: application/json",
                "authorization: Basic ".$auth_key,
                "cache-control: no-cache",
                "content-type: application/json",
                "postman-token: bd952ccb-ec4e-e314-cec2-a41364b9c9b2"
              ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);
            if ($err) {
              echo "cURL Error #:" . $err;
            } else {
                $res =  json_decode(($response), TRUE);
                if($res['error_messages']){
                    $resArray = array(
                    'isError'	=>	'Yes',
                    'errorMessage'	    =>	$res['error_messages'][0]
                    );
                    echo json_encode($resArray);
                    exit;                  
                }
              echo $response;
            }
            exit;
			
    } 
   
    
            public function ajaxReOrderAction() {
            $masterOrderID = $_POST['id'];
            $ObjCart       = new CartModel();
            $ObjProduct    = new ProductModel();
            $ObjProductList= new ProductListModel();
            $languageIDs   = $this->ObjView->languageIDs;
            $cartID        = $this->decodeString($this->ObjSession->getSession("CARTID"));
            $userID        = $this->ObjSession->getSession("REGISTERED_USER_ID");
            $orderItems    = $ObjCart->getOrderItemDetailsByParentOrderID($masterOrderID,array(),'','Yes',$userID);
            $post          = array();
            $user_group_id = (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID;
            if(!empty($orderItems)) {
                if($cartID>0) {
                    //clear cart
                    $ObjCart->clearCart($cartID);
                    $this->ObjSession->setSession("CARTID",'');
                }
                foreach($orderItems as $item) {
                        $post['productID']          = $item['productID'];
                        $post['productOptionID']    = $item['productOptionID'];
                        $post['quantity']           = $item['orderItemQuantity'];
                        $post['reorder']            = 'Y';
                        $post['userID']             = $this->ObjSession->getSession("REGISTERED_USER_ID");
                        $extra                      = unserialize($item['extra']);
                        $bundleProd                 = isset($extra['bundleProduct']) ? $extra['bundleProduct'] : "";
                        $result                     = $itemDetails = $ObjCart->getCartProductDetails($post['productID'], $post['productOptionID'],$languageIDs);
                        $post['productCommissionRate'] = $result['productCommissionRate'];
                        $post['productServiceFee']     = (isset($post['freeProduct']) && $post['freeProduct'] == 'Yes') ? 0 : $result['productServiceFee'];
                        $productDispatchString         = $ObjProduct->getDispatchTimeByID($result['productDispatchTime']);
                        $productDispatchPeriod         = explode("-", $productDispatchString);
                        $post['productDispatchTime']   = isset($productDispatchPeriod[1]) ? $productDispatchPeriod[1] : '';
                        $post['productTitle']       = $extra['productTitle'];
                        $post['productOptionName']  = $extra['productOptionName'];
                        $post['productImage']       = $extra['imagePath'];
                        $post['businessKey']        = $extra['businessKey'];
                        $post['productDefaultCurrency']        = $extra['productDefaultCurrency'];
                        
                        $combination_hash                   = isset($extra['combinationHash']) ?$extra['combinationHash']:'';
                        $post['combinationHash']            = $combination_hash;
                        $product_option_id                  = $post['productOptionID'];
       
                        $current_quantity                   = $post['quantity'];
                        $params['cart_id']                  = $cartID;
                        $params['combination_hash']         = $combination_hash;
                        $params['product_option_id']        = $product_option_id;
                        $params['user_group_id']            = $user_group_id;
                        $params['current_quantity']         = $current_quantity;
                        $params['language_id']              = $this->ObjView->languageIDs['Current'];
                        $params['curr_business_id']         = $item['businessID'];
                        $result                             = $ObjCart->getCartItemPrice($params);
                        $tier_price                         = $ObjCart->getVariantTiePrice($params);
                        $customOptionValueDet               = isset($extra['customOptionValues']) ?$extra['customOptionValues']:'';
                       
                        $customOptionValues                 = '';
                        if(!empty($customOptionValueDet)) {
                            foreach ($customOptionValueDet as $keycustom=>$customOptionValue) {
                                    $appendValue        = '->customOptionID~*'.$keycustom.'~:customOptionName~*'.$customOptionValue['0']['customOptionName'].'~:customOptionVariantID~*'.$customOptionValue['0']['customOptionVariantID'];
                                    $appendValue        .= '~:variantValue~*'.$customOptionValue['0']['variantValue'].'~:priceDiff~*'.$customOptionValue['0']['priceDiff'].'~:priceDiffType~*'.$customOptionValue['0']['priceDiffType'].'~:inputType~*'.$customOptionValue['0']['inputType'];
                                    $customOptionValues = ($customOptionValues!='')?$customOptionValues.$appendValue:$appendValue;
                            }
                            $extra_string                       = substr(trim($this->decodeSplChar($customOptionValues)), 2);
                            $custom_option_values               = explode('->', $extra_string);
                        } else {
                            $custom_option_values               = array();
                        }
                        $price_change                       = 0;
                        if (count($custom_option_values) > 0) {
                            $custom_option_details = $this->getCustomOptionStringAndPriceDiff($custom_option_values, $params);
                            $custom_option_string  = $custom_option_details['custom_option_string'];
                            $price_change += $custom_option_details['price_change'];
                        }
                        $strcombinationValues                 = isset($extra['combinationValues']) ?$extra['combinationValues']:'';
                        $combinationString                    = '';
                        $combination_values                   = array();
                        if(!empty($strcombinationValues) && !empty($strcombinationValues['customOption'])) {
                            $combinationString                = '->combinationSKU~*'.$strcombinationValues['cimbinationSKU'].'->combinationPrice~*'.$strcombinationValues['combinationPrice'].'->combinationPriceDiffType~*'.$strcombinationValues['combinationPriceDiffType'];                            
                            foreach ($strcombinationValues['customOption'] as $customOptionValue) {                                
                                $combinationString = $combinationString .'->customOptionID~*' . $customOptionValue['customOptionID'] . '~:customOptionName~*' . $customOptionValue['customOptionName'];                                
                                $combinationString = $combinationString.'~:customOptionVariantID~*' .$customOptionValue['customOptionVariantID']. '~:variantValue~*' .$customOptionValue['variantValue']. '~:inputType~*' .$customOptionValue['inputType'];
                            }                            
                            $combination_values = explode('->', $combinationString);
                        }   
                       
                        if (count($combination_values) > 0) {
                            $combination_details = $this->getCombinationStringAndPriceDiff($combination_values, $params);
                            $combination_string  = $combination_details['combination_string'];                            
                            $price_change += $combination_details['price_change'];
                        }
                        
                        $base_price                        = $result['actualPrice'];  
                        if($bundleProd=="Yes"){
                            $offer_price                   = $result['productOptionProductPrice'];
                            $extra_price                   = 0;
                        }else{
                            if($result['isProductDeal']!="Yes")
                                $offer_price               = $result['offerPrice'];
                            else
                                $offer_price               = $result['productOptionRegularPrice'] - $result['productOptionRegularPrice']*$result['dealDiscount']/100;
                            $offer_price                   = ($tier_price > 0 && $tier_price < $offer_price) ? $tier_price : $offer_price;
                            $extra_price                   = $price_change;
                        }
                        $post['actualPrice']               = $base_price + $extra_price;
                        $post['offerPrice']                = $offer_price;
                        $post['tierPrice']                 = $tier_price;
                        $post['strcombinationValues']      = $combination_string;
                        $post['customOptionValues']        = $custom_option_string;
                        $post['measurementLength']         = $itemDetails['measurementLength'];
                        $post['measurementWeight']         = $itemDetails['measurementWeight'];
                        $post['packageWeight']             = $itemDetails['packageWeight'];
                        $post['packageLength']             = $itemDetails['packageLength'];
                        $post['packageWidth']              = $itemDetails['packageWidth'];
                        $post['packageHeight']             = $itemDetails['packageHeight'];
                        $post['price']                     = $offer_price + $extra_price;
                        $post['price']                     = (isset($post['freeProduct']) && $post['freeProduct'] == 'Yes') ? 0 : $post['price'];
                        $post['giveAsGift']			=	'No';
                        $post['currbusinessid']            = $item['businessID'];
                        $post['businessKey']            = $result['businessKey'];
                        $this->ajaxAddItemAction($post);
                        unset($post);
                }
            }
            echo 1;
        }
		
	 private function setRedeemPoints($section = 'cartEdit', $params = '') {
        $ObjCart                 = new CartModel();
        $languageIDs             = $this->ObjView->languageIDs;
        $cartID                  = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $userID         = $this->ObjSession->getSession("REGISTERED_USER_ID");
        
        if ($section == 'cartCheckout') {
            $promoArray['promoError']  = 'No';
            $promoArray['promoErrMsg'] = '';
            $params['userID'] = $userID;
            $params['applyRedeemPoint']      = (isset($params['applyRedeemPoint']) ? $params['applyRedeemPoint'] : '');
            $params['removeRedeemPoint']     = (isset($params['removeRedeemPoint']) ? $params['removeRedeemPoint'] : '');
            $params['redeemPoint']       = (isset($params['redeemPoint']) ? $params['redeemPoint'] : '');
            if($params['redeemPoint']>0){
                $pointsToAmount                   =       $this->getSettingValue('reward_point_settings', 'amount_per_point');
                $params['redeemDiscountAmount']   = $params['redeemPoint']*$pointsToAmount;
            }
           
            if ((isset($params['applyRedeemPoint']) && $params['applyRedeemPoint'] == 'Yes') || (isset($params['removeRedeemPoint']) && $params['removeRedeemPoint'] == 'Yes')) {
                if (isset($params['applyRedeemPoint']) && $params['applyRedeemPoint'] == 'Yes' && (trim($params['redeemPoint']) == '' || !is_numeric($params['redeemPoint']))) {
                    $promoArray['promoError']  = 'Yes';
                    $promoArray['promoErrMsg'] = $this->getLanguageValue("lblRedeemPointNull");
                    return $promoArray;
                }				
				 if($orderID){
					$redID	    = $orderID ;
					$section    ='Order';
				 }else{
					$redID	    = $cartID ;
					$section    = 'Cart';				 
				 }
                if (isset($params['removeRedeemPoint']) && $params['removeRedeemPoint'] == 'Yes') {
                    $params['promoCode']       = '';
                    $promoArray['promoErrMsg'] = $this->getLanguageValue("msgRedeemPointRemoved");                    
                        $promoData                 = $ObjCart->setRedeemPointDiscount($params,(int)$cartID, 'remove',$section,(int)$redID);                
                } else if ($params['applyRedeemPoint'] == 'Yes') {                    
                        $promoData                 = $ObjCart->setRedeemPointDiscount($params,(int)$cartID,'apply',$section,(int)$redID);                  
                    $promoArray['promoErrMsg'] = $this->getLanguageValue("msgRedeemPointApplied");
                }                
                    $resResetCartTotals = $ObjCart->resetCartTotals($cartID);              
                if (isset($promoData['promoErrorCode']) && $promoData['promoErrorCode'] > 0) {
                    $promoArray['promoErrMsg'] = $promoData['error'];
                    $promoArray['promoError']  = 'Yes';
                } else {
                    if ($params['applyPromo'] == 'Yes') {
                        $promoArray['promoErrMsg'] = "Redeem Points Applied";
                    }
                }
                return $promoArray;
            }
        }
    }
    
    public function getCartPageSummary($cartID){
        $ObjCart                    = new CartModel();
        $languageIDs                = $this->ObjView->languageIDs;
        $resCart = $ObjCart->getCartDetails($cartID, 0);
        if (count($resCart['items']) > 0) {
            foreach ($resCart['items'] as $key => $items) {
                $resCart['items'][$key]['itemDetails'] = unserialize($items['itemDetails']);
                $resProductOptions = $ObjCart->listCartItemOptions($languageIDs, $items['productID'],'Active');
                if(count($resProductOptions)==1)
                {
                        $resCart['items'][$key]['hasOption']='No';
                }
                else
                {
                        $resCart['items'][$key]['hasOption']='Yes';
                        $resCart['items'][$key]['options']=$resProductOptions;
                }
                if($userID > 0){
                        $shippingAddress = $ObjCart->getUserDefaultShippingAddress($userID);
                        if(count($shippingAddress) > 0){
                            //checking available shipping methods match with saved address
                            list($shippingMethods, $shippingReason) =$this->isShippingAvailable($cartID,$items['productID'],$shippingAddress);
                            $resCart['items'][$key]['shippingMethods'] = $shippingMethods;
                            $resCart['items'][$key]['shippingReason'] = $shippingReason;
                        }else{                            
                            $resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
                            $resCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
                        }
                    }else{
                         //get all assigned shipping methods for a product, user not logged on or                         
                         $resCart['items'][$key]['shippingMethods'] = $ObjCart->listAllShippingMethods($items['productID']); //24-04-15
                        $resCart['items'][$key]['shippingReason'] = $this->getLanguageValue("lblNoShippingMethodAvilable");
                    }
                    $resCart['items'][$key]['productoptin']=$resProductOptions;
                    unset($resProductOptions);
            }
        }
        $resCart['cartDetails'] = unserialize($resCart['extra']);
        if (isset($resCart['cartDetails']['userBillingAddress']) && is_array($resCart['cartDetails']['userBillingAddress'])) {
            $tempArray = array_slice($resCart['cartDetails']['userBillingAddress'], 0, -2);
            unset($resCart['cartDetails']['userBillingAddress']);
            $resCart['cartDetails']['userBillingAddress'] = array_values($tempArray);
        }
        unset($tempArray);
        $tempArray = (isset($resCart['cartDetails']['userShippingAddress'])) ? $resCart['cartDetails']['userShippingAddress'] : '';
        unset($resCart['cartDetails']['userShippingAddress']);
        if (is_array($tempArray))
            $resCart['cartDetails']['userShippingAddress'] = array_values($tempArray);
        $this->ObjView->assign('cartData', $resCart);
        $html    = $this->ObjView->fetch('cart/CartTotal.tpl');
        return $html;
    }
    
    public function getBankCodeForCard($cardNumber){
            $firstnumber = substr($cardNumber, 0, 1);
		// Make sure it is the correct amount of digits. Account for dashes being present.
		switch ($firstnumber)
		{
			case 3:
				return "AMER";
				break;
			case 4:
				return "VISA";
				break;
			case 5:
				return "MAST";
				break;
			case 6:
				return "DISC";
				break;
			default:
				return "VISA";
				return false;
		}
        }
		
	public function loadingCartSummaryAction(){
		$ObjCart                    = new CartModel();
        $cartID                     = $this->decodeString($this->ObjSession->getSession("CARTID"));
        $cartData                   = array();
        $cartData['items']          = array();
        $resCart                    = $ObjCart->getCartDetails($cartID);
		$resProductSummaryImages   =   $this->loadingProductImages(implode('_',$imagesetarr),'extr',30);
		$this->ObjView->assign('resProductSummaryImages', $resProductSummaryImages);
	}
        
        public function cartbroucherconfirmationAction($orderID){
            $filename   =   'invoice_'.$orderID.'_'.date('YmdHis'). ".pdf";
            $filepath   =   __CORE_PUBLIC_PATH . "/uploads/invoice/";
            $ObjCart    =   new CartModel();
            $ObjUrl                     =   new UrlrewriteModel();
            $languageIDs                = $this->ObjView->languageIDs;
            $getOrderDetails   = $ObjCart->getOrderMasterDetails($orderID);
            $orderItems    = $ObjCart->getOrderItemDetailsByParentOrderID($orderID,array(),'','Yes');
            $emailbody  =   '';
            
            $resSpecificationSummary    =   $this->getrequiredparams($orderItems[0]['productID'],unserialize($orderItems[0]['extra']));
            for($i=0;$i<count($resSpecificationSummary['selectedvariants']);$i++){
                $this->ObjView->assign($resSpecificationSummary['selectedvariants'][$i]['optionName'], $resSpecificationSummary['selectedvariants'][$i]['variantName']); 
            }
            $urlparams      =   array();
            $urlparams['language_ids']   = $languageIDs;
            $urlparams['objectID']      = $orderItems[0]['productID'];
            $urlparams['type']          = 'product';
            $urldet         =   $ObjUrl->getRewriteUrl($urlparams); 
            $urlpath =   $urldet['requestPath'];
            $siteUrl     = $this->getSettingValue('site_settings', 'global_http_url');
            $ObjQr             = new QrModel();
            $redemptionUrl          = $siteUrl. "/public/uploads/invoice/".$filename;
            $shortnedUrl			=	$redemptionUrl;	
            $formattedURl = $ObjQr->getFormattedLink($shortnedUrl); //For Formatting The Url            
            $imageSrc     = $ObjQr->getQrLink($formattedURl); //For Fetching The Qr Code Image
            $resSpecificationSummary['qrimage'] =   $imageSrc;
            $brandID = $this->ObjCommon->brandID;
            $pdfLib = new Pdf();
            ob_end_clean();
            $emailbody= "";
            $this->ObjView->assign('resSpecificationSummary', $resSpecificationSummary); 
            $getOrderDetails['billingFirstName'] =  $getOrderDetails['billingFirstName'];//$this->encryptDecrypt("decrypt",$getOrderDetails['billingFirstName']);
            $getOrderDetails['billinglastName']  =  $getOrderDetails['billinglastName'];//$this->encryptDecrypt("decrypt",$getOrderDetails['billinglastName']);
            $getOrderDetails['customer_email']   =  $getOrderDetails['customer_email'];//$this->encryptDecrypt("decrypt",$getOrderDetails['customer_email']);
            $getOrderDetails['billingPhone']     =  $getOrderDetails['billingPhone'];//$this->encryptDecrypt("decrypt",$getOrderDetails['billingPhone']);
            $this->ObjView->assign('resOrderDetails', $getOrderDetails); 
            $ObjPaymentgateway = new PaymentgatewayModel();
            $paymentGateWayDetails = $ObjPaymentgateway->getPaymentSettingGroupDetails($getOrderDetails['paymentSettingsGroupID']);
            $paySetGroupKey                     = $paymentGateWayDetails['paySetGroupKey'];
            $this->ObjView->assign('paySetGroupKey', $paySetGroupKey); 
            $pdftext    = $this->ObjView->fetch('catalog/default/DownloadProductConfirmationInfo.tpl');
            
            $pdf = new TCPDF('P', PDF_UNIT, array(  235,  322), true, 'UTF-8', false);
            if($languageIDs['Current'] != 3){
                if($brandID=='2'){
					$pdf->SetFont('miniserif', '', 10, '', false);
				}else{
					$pdf->SetFont('bmwtypewebboldall', '', 10, '', false);
				}
            }
            else{
                // set some language dependent data:
                $lg = Array();
                $lg['a_meta_charset'] = 'UTF-8';
                $lg['a_meta_dir'] = 'rtl';
                $lg['a_meta_language'] = 'fa';
                $lg['w_page'] = 'page';
                // set some language-dependent strings (optional)
                // ---------------------------------------------------------
                // set font
                $pdf->setRTL(true);
                $pdf->SetFont('dejavusans', '', 10, '', false);//bmwtypewebboldallarabic
            }
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('');
            $pdf->SetTitle($this->getLanguageValue('lblBookingConfirmation'));
            $pdf->SetSubject('');
            $pdf->SetKeywords('');
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);
            $pdf->setLanguageArray($lg);
            // add a page
            $pdf->AddPage();
           
            // output the HTML content			
            $pdf->WriteHTML($pdftext);
            
            $pdf->Output($filepath.$filename, 'F');
            /*$ObjImage   = new ImageModel();
            $ObjImage->copy_file($filepath.$filename, '/' . __UPLOADS_FOLDER . 'uploads/invoice/' .$filename);*/
            return $filename;
            exit;
        }
        
        function getrequiredparams($productID,$extraData){
            
			$ObjCart                    = new CartModel();
			$ObjProduct					= new ProductModel();
			$ObjCustomOption                     = new CustomOptionModel();
			$ObjShowroom				=	new ShowroomsModel();
			$languageIDs                         = $this->ObjView->languageIDs;
			$cartData                   = array();
			$cartData['items']          = array();

			$productType          = array(
				'productTypeID' => 1,
				'productTypeKey' => 'product_product',
				'productTypeUrlKey' => '',
				'isFeatured' => 1,
				'limitMainListing' => '',
				'limitDefListing' => '',
				'productTypeName' => $this->getLanguageValue('lblProducts')
			);
                        $args                 = array(
				'requestedBy' => 'customer',
				'requestPage' => 'product_detail',
				'limitFrom' => 0,
				'limitTo' => 1,
				'productType' => $productType,
				'languageIDs' => $languageIDs,
				'selectedProductID' => $productID,
				'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID,
				'productStatus' => 'Active'
			);
			$resultProductProduct = $ObjProduct->getProductDetails($args);
			$selectedvariants	=	array();
                       
			$imagesetarr	=	explode('-',$resultProductProduct[0]['optionSKU']);
			$itemDetails				=	$extraData;
			foreach ($itemDetails['customOptionValues'] as $values) {    
                                $customOptionVariantID	=	$values[0]['customOptionVariantID'];
				$variantdetails	=	$ObjCustomOption->getVariantDetails($customOptionVariantID);
                               
				if($values[0]['customOptionName']!='Wheel' && $values[0]['customOptionName']!='Trim')
					$imagesetarr[]	=	$variantdetails['variantCode'];
				$selectedvariants[]	=	array('optionName'=>$values[0]['customOptionName'],'variantName'=>$values[0]['variantValue'],'variantCode'=>$variantdetails['variantCode'],'variantImage'=>$variantdetails['variantThumbImage']);
                        }
			//$sortarr    =   array('Color','Wheel','Upholstery','Trim','Stripe','Roof');
			 $sortarr    =   array('Color','Wheel','Stripe','Roof','Upholstery','Trim');
                        $sortedarr = array();
                        foreach($sortarr as $sortId) {
                            foreach ($selectedvariants as $subKey => $subArray) {
                                if ($subArray['optionName'] == $sortId) {
                                    $sortedarr[] = $selectedvariants[$subKey];
                                    break;
                                }
                            }
                        }
			$res['selectedvariants']	=	$sortedarr;
			//$res['selectedvariants']	=	$selectedvariants;
                         
			$resProductSummaryImages  =   $ObjProduct->getProductImages(implode('_',$imagesetarr),'extr','yes',30);
			$res['summaryImage']	=	$resProductSummaryImages[0]['Imageslist'];
                        $resProductIntrImages   =   $this->loadingProductImages(implode('_',$imagesetarr),'intr');
                        $res['summaryIntrImage']	=	$resProductIntrImages[0]['vehicleImage'];
                        $resProductTrimImages   =   $this->loadingProductImages(implode('_',$imagesetarr),'trim');
                        $res['summaryTrimImage']	=	$resProductTrimImages[0]['vehicleImage'];
                        $resProductStripeImages   =   $this->loadingProductImages(implode('_',$imagesetarr),'bonnet');
                        $res['summaryStripeImage']	=	$resProductStripeImages[0]['vehicleImage'];
                        $resProductRoofImages   =   $this->loadingProductImages(implode('_',$imagesetarr),'stripe');
                        $res['summaryRoofImage']	=	$resProductRoofImages[0]['vehicleImage'];
			
			$productModelArr    =   explode('-',$resultProductProduct[0]['optionSKU']);
                        $res['specificationDetails']  =   $ObjProduct->selectProductSpecification($productModelArr[0],$productModelArr[1]);
            
			$languageIDs                         = $this->ObjView->languageIDs;
			$languageIDs['Content'] = $languageIDs['Current'];
			$psarr	=	array('showroomID'=>$itemDetails['showroom'],'languageIDs'=>$languageIDs,'brandID' => $this->ObjCommon->brandID);
			$resShowroomDets	=	$ObjShowroom->getShowroom($psarr);
                        $res['productTitle']    =   $resultProductProduct[0]['productTitle'];
                        $res['monthlyInstallment']    =   $resultProductProduct[0]['monthlyInstallment'];
                        $res['leasePrice']    =   $resultProductProduct[0]['leasePrice'];
						
						$resShowroomDets['codedPhone'] = stripslashes(preg_replace('/\s+/', '', $resShowroomDets['phone']));
                        $res['showroomDetails'] =   $resShowroomDets;
						
						//Service & Repair package details
						$serviceCode = explode('-',$resultProductProduct[0]['optionSKU']);
						$serviceCode = $serviceCode[0];
						$serviceDetails = '';
						$serviceDetails = $ObjProduct->getServicePackage($serviceCode);
						$res['serviceDetails'] = (!empty($serviceDetails['longDescription'])) ? $serviceDetails['longDescription'] : '';						
						//
						
                        return $res; 
		
        }
        
        /*Getting Product Imgaes*/
        public function loadingProductImages($image_code,$imageType='extr',$angle=''){
            $ObjProduct                          = new ProductModel();
            $resImages  =   $ObjProduct->getProductImages($image_code,$imageType,'no',$angle);
            return $resImages;
        }
        
        /*Getting Product Imgaes*/
        public function loadingProductImagesAction(){
            $image_code =   $_POST['imagecode'];
            $imageType  =   $_POST['imagetype'];
            $isAjax =   'yes';
            $ObjProduct                          = new ProductModel();
            $resImages  =   $ObjProduct->getProductImages($image_code,$imageType,$isAjax);
            echo implode(',', array_map(function ($entry) {  return $entry['Imageslist'];}, $resImages));
            exit;
        }
        
        public function broucherconfirmationAction(){
            $ObjCart    =   new CartModel();
            $ObjUrl                     =   new UrlrewriteModel();
            $languageIDs                = $this->ObjView->languageIDs;
            $orderID    =   $this->getRequestValue('id');
            $orderID    =   (int)base64_decode($orderID);
            $getOrderDetails   = $ObjCart->getOrderMasterDetails($orderID);
            $orderItems    = $ObjCart->getOrderItemDetailsByParentOrderID($orderID,array(),'','Yes');
            $emailbody  =   '';
            $resSpecificationSummary    =   $this->getrequiredparams($orderItems[0]['productID'],unserialize($orderItems[0]['extra']));
            $urlparams      =   array();
            $urlparams['language_ids']   = $languageIDs;
            $urlparams['objectID']      = $orderItems[0]['productID'];
            $urlparams['type']          = 'product';
            $urldet         =   $ObjUrl->getRewriteUrl($urlparams); 
            $urlpath =   $urldet['requestPath'];
            $siteUrl     = $this->getSettingValue('site_settings', 'global_http_url');
            $ObjQr             = new QrModel();
            $redemptionUrl          = $siteUrl.'/cart/broucherconfirmation/id/'.base64_encode($orderID);
            $shortnedUrl			=	$redemptionUrl;	
            $formattedURl = $ObjQr->getFormattedLink($shortnedUrl); //For Formatting The Url            
            $imageSrc     = $ObjQr->getQrLink($formattedURl); //For Fetching The Qr Code Image
            $resSpecificationSummary['qrimage'] =   $imageSrc;
            $brandID = $this->ObjCommon->brandID;
            $pdfLib = new Pdf();
            ob_end_clean();
            $emailbody= "";
            $this->ObjView->assign('resSpecificationSummary', $resSpecificationSummary); 
            $getOrderDetails['billingFirstName'] =  $getOrderDetails['billingFirstName'];//$this->encryptDecrypt("decrypt",$getOrderDetails['billingFirstName']);
            $getOrderDetails['billinglastName']  =  $getOrderDetails['billinglastName'];//$this->encryptDecrypt("decrypt",$getOrderDetails['billinglastName']);
            $getOrderDetails['customer_email']   =  $getOrderDetails['customer_email'];//$this->encryptDecrypt("decrypt",$getOrderDetails['customer_email']);
            $getOrderDetails['billingPhone']     =  $getOrderDetails['billingPhone'];//$this->encryptDecrypt("decrypt",$getOrderDetails['billingPhone']);
            $this->ObjView->assign('resOrderDetails', $getOrderDetails); 
            $ObjPaymentgateway = new PaymentgatewayModel();
            $paymentGateWayDetails = $ObjPaymentgateway->getPaymentSettingGroupDetails($getOrderDetails['paymentSettingsGroupID']);
            $paySetGroupKey                     = $paymentGateWayDetails['paySetGroupKey'];
            $this->ObjView->assign('paySetGroupKey', $paySetGroupKey); 
            $pdftext    = $this->ObjView->fetch('catalog/default/DownloadProductConfirmationInfo.tpl');
            $pdf = new TCPDF('P', PDF_UNIT, array(  235,  322), true, 'UTF-8', false);
            if($languageIDs['Current'] != 3){
                if($brandID=='2'){
					$pdf->SetFont('miniserif', '', 10, '', false);
				}else{
					$pdf->SetFont('bmwtypewebboldall', '', 10, '', false);
				}
			}else{
                $pdf->SetFont('bmwtypewebboldallarabic', '', 10, '', false);
			}
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('');
            $pdf->SetTitle($this->getLanguageValue('lblBookingConfirmation')); 
            $pdf->SetSubject('');
            $pdf->SetKeywords('');
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);
            $pdf->setLanguageArray($l);
            // add a page
            $pdf->AddPage();
            // output the HTML content			
            $pdf->WriteHTML($pdftext);
            $filename   =   'invoice_'.$orderID.'_'.date('YmdHis'). ".pdf";
            $filepath   =   __CORE_PUBLIC_PATH . "/uploads/invoice/";
            $pdf->Output($filepath.$filename, 'F');
            /*$ObjImage   = new ImageModel();
            $ObjImage->copy_file($filepath.$filename, '/' . __UPLOADS_FOLDER . 'uploads/invoice/' .$filename);*/
            return $filename;
            exit;
        }
		
		function containsBlockedWords($value, $blockedWords) {
			foreach ($blockedWords as $word) {
				if (stripos($value, $word) !== false) {
					return $word; // return the matched word
				}
			}
			return false;
		}
}
