<?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: LoginController.php, v 1.0 2013/06/14 11:47:11
//
class LoginController extends Controller {
    public function __construct() {
        parent::__construct();
        $this->ObjView->assign('statPageName', 'login');
    }
    //Dont remove this function : required for affiliate imported users
    public function indexAction() {
        if (!isset($_SERVER['HTTP_REFERER'])) {
            $this->setRedirect('/');
        }
        $userID = $this->ObjCommon->REGISTERED_USER_ID;
        if ($userID) {
            $this->setRedirect('user/account/');
        }
        $hasValidSession = $this->affiliateImportUserConfirmation();
        if ($hasValidSession) {
            $params   = array(
                "ajaxRequest" => "0",
                "validatEmail" => "1",
                "hasValidSession" => true
            );
            $validate = $this->loginProcess($params);
            if ($validate['error'] == "No") {
                $this->setRedirect('user/account/');
            } else {
                $this->setMessage($validate['errorMessage'], 'error', 'Login', 'invalid_login');
                $this->setRedirect('referral/affuser/');
            }
        }
    }
    //END OF FUNCTION
    //FACEBOOK
    public function facebookAction() { 
        $ObjUser       = new UserModel();
        $enableFBlogin = $this->getSettingValue('social_media_settings', 'facebook_enable_login');
        $languageIDs   = $this->ObjView->languageIDs;
	$otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
        $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
        $isSignup                     = 'login';
        $parentUrl     = (isset($_GET['parenturl'])) ? trim($_GET['parenturl']) : '';
        if ($enableFBlogin == 'Yes') {
            $appID     = $this->getSettingValue('social_media_settings', 'facebook_application_id');
            $secret    = $this->getSettingValue('social_media_settings', 'facebook_application_secret_key');
            $regUserID = $this->ObjCommon->REGISTERED_USER_ID;
            if (!$regUserID) {
                $facebook = new Facebook($appID, $secret);
                if ($facebook->loggedIn) {
                    $facebookUser = $facebook->userData();	
                    
                    if (isset($facebookUser['email']) && $facebookUser['email'] != '') {
                        $loginParams = array(
                            "userEmail" => $facebookUser['email']
                        );
                        $userDetails = $ObjUser->getUserDetailsForLogin($loginParams);
                        //Signup 
                        if ($userDetails['userID'] < 1) {
                            $facebookUser['languageID'] = $languageIDs['Current'];
                            $_POST['userFirstName'] = $facebookUser['first_name'];
                            $_POST['userLastName']  = $facebookUser['last_name'];
                            $_POST['userEmail']     = $facebookUser['email'];
                            $signupParams           = array(
                                "isFacebook" => "1",
                                "facebookUserData" => $facebookUser
                            );
                           $validateSignup = $this->signupProcess($signupParams);
                            $validate['parentUrl'] = $parentUrl;
							  echo json_encode($validateSignup);exit;
                            //$this->fbPageRedirect($validate);
                        } else // Login 
                            {
                                if($userDetails['isverify']=='N'){
                                    //normal login
                                    if($_POST['checkoutLogin']==''){// NORMAL LOGIN
                                        if($otpEnableRegistration == 'Yes'){
                                             $this->ObjSession->setSession("TEMP_USER_ID", $userDetails['userID']);
                                                $returnArray['error']        = 'Yes';
                                                $returnArray['isverify']        = 'No';
                                                $returnArray['userPhoneVerify']       = $userDetails['userPhone'];
                                                  $this->verifyMobileAction();
                                                  echo json_encode($returnArray);exit;
                                        } else {
                                            $this->signupProcessComplete($userDetails['userID'],'',$isSignup);
                                           $userDetails = $ObjUser->getUserDetailsForLogin($loginParams);
                                        }
                                            
                                    }else{
                                       //CHECKOUT LOGIN
                                    if($_POST['checkoutLogin']!='' && $otpEnableCheckout == 'Yes'){
                                                  $this->ObjSession->setSession("TEMP_USER_ID", $userDetails['userID']);
                                                 $returnArray['error']        = 'Yes';
                                                 $returnArray['isverify']        = 'No';
                                                 $returnArray['userPhoneVerify']       = $userDetails['userPhone'];
                                                  $this->verifyMobileAction();
                                                  echo json_encode($returnArray);exit;
                                    } else{
                                           $this->signupProcessComplete($userDetails['userID'],'',$isSignup);
                                            $userDetails = $ObjUser->getUserDetailsForLogin($loginParams);
                                    }
                                   
                                }
                                }
                            $userID = $userDetails['userID'];
                            //update fb user id in user table
                            if (isset($userDetails['userName']) && $userDetails['userName'] == '') {
                                $ObjUser->updateFbUserID($userID, $facebookUser['id']);
                            }
                            $_POST['userLoginEmail'] = $facebookUser['email'];
                            $loginParams             = array(
                                "isFacebook" => "1",
                                "ajaxRequest" => "0"
                            );
                            $validate                = $this->loginProcess($loginParams);
                            if ($validate['error'] == "No") {
                                $validate['parentUrl'] = $parentUrl;
                                $validate['userPhoneVerify'] = $userDetails['userPhone'];
                                $this->fbPageRedirect($validate);
                            } else {
                                $this->setMessage($validate['errorMessage'], 'error', 'Login', 'common_fb_message');
                                $global_http_url = (rtrim($this->getSettingValue('site_settings', 'global_http_url'), '/')) . "/";
                                $this->FbRedirectType($global_http_url);
                            }
                        }
                    } else {
                        $this->FbRedirectType($parentUrl);
                    }
                } else {
                    $this->FbRedirectType($parentUrl);
                }
            } else {
                $enableSSLCheckout = $this->getSettingValue('site_settings', 'enable_ssl_checkout');
                $global_http_url   = (rtrim($this->getSettingValue('site_settings', 'global_http_url'), '/')) . "/";
                $popup_iframe_url  = ($enableSSLCheckout == 'Enable') ? (rtrim($this->getSettingValue('site_settings', 'global_https_url'), '/')) . "/" : $global_http_url;
				$returnArray['error']        = 'No';
				$returnArray['isverify']        = 'Yes';
				$returnArray['redirectURL']        = 'user/purchases/';
             //   echo "<script>window.top.location.href = '" . $popup_iframe_url . "user/account/';</script>";
                	echo json_encode($returnArray);exit;	
            }
             $checkoutLogin     =  $_POST['checkoutLogin'];
             $this->ObjView->assign('otpEnableRegistration', $otpEnableRegistration);
             $this->ObjView->assign('otpEnableCheckout', $otpEnableCheckout);
             $this->ObjView->assign('checkoutLogin', $checkoutLogin);
            
            
        } else {
            $this->FbRedirectType($parentUrl);
        }
         $this->ObjView->assign('isSignup ', $isSignup );
    }
    //END OF FUNCTION
    private function FbRedirectType($url = "") {
        if (isset($url) && !empty($url)) {
			$returnArray['error']        = 'No';
			$returnArray['isverify']        = 'Yes';
			echo json_encode($returnArray);exit;		
          //  echo "<script>window.top.location.href = '" . $url . "';</script>";
            exit;
        } else {
			$returnArray['error']        = 'No';
			$returnArray['isverify']        = 'Yes';
			echo json_encode($returnArray);exit;			
            //$this->setRedirect('/');
        }
    }
    //FUNCTION FOR LOGIN TRACKING...RELATES TO LOG TRACKING
    public function loginTracking($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"); //FUNCTION FOR UPDATING USER DETAILS TO CORRESPONDING VISITOR DETAILS	
                //========================================FLAG=====================================================
            }
        }
    }
    //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');
        }
    }
    //Function to save new aff visitor record for new visitor
    public function saveAffVisitorInfo($visitorID) {
        if (__AFFILIATE_MODULE) {
            $ObjAffiliate       = new AffiliateModel();
            $affiliateUserID    = $this->ObjCookie->getCookie("affiliateUserID");
            $affiliateVisitorID = $this->ObjCookie->getCookie("affiliateVisitorID");
            if ($affiliateUserID != '' && $affiliateVisitorID != '') {
                $affVisitorInfo = $ObjAffiliate->getAffVisitorInfo($affiliateVisitorID);
                if (!empty($affVisitorInfo)) {
                    $settingsReferralExpire = $this->getSettingValue('affiliate_settings', 'affiliate_cookie_expiry_time');
                    //Save Aff Visitor Details	
                    $affVisitorID           = $ObjAffiliate->saveAffVisitorDetails($affiliateUserID, $visitorID, $affVisitorInfo['widgetID'], $affVisitorInfo['visitType']);
                    $this->ObjCookie->setCookie("affiliateVisitorID", $affVisitorID, $cookie_expire_minute, "/"); //Setting affiliateVisitorID Cookie
                }
            }
        }
    }
    // FUNCTION TO CHECK THE USER IS IMPORTED USER - FROM AFFILATE USER IMPORT
    private function affiliateImportUserConfirmation() {
        if (__AFFILIATE_MODULE && $this->ObjSession->getSession("LOGIN_KEY") == 'KEY_:_LOGIN_FROM_CONFIRM_USER') {
            $_POST['userLoginEmail']    = $this->ObjSession->getSession("CONFIRM_USER_NAME");
            $_POST['userLoginPassword'] = $this->ObjSession->getSession("CONFIRM_USER_PASSWORD");
            $this->ObjSession->unsetSession("CONFIRM_USER_NAME");
            $this->ObjSession->unsetSession("CONFIRM_USER_PASSWORD");
            $this->ObjSession->unsetSession("LOGIN_KEY");
            return true;
        } else {
            return false;
        }
    }
    //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');
        }
    }
    //Popup Login
    public function ajaxPopupLoginAction() {
        if ($this->ObjSession->getSession("REGISTERED_USER_ID")) {  
            $this->setRedirect('/index/');
            echo '<script>window.top.location.href = document.referrer.substr(0,document.referrer.indexOf("login/ajaxPopupLogin"));</script>';
            exit;
        }
        //redirect URL
        $reUrl          = (isset($_GET['reurl'])) ? trim($_GET['reurl']) : '';
        $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
        $otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
        
        //Signup Section
        $signupParams   = array(
            "ajaxRequest" => "0"
        );
       
        $validateSignup = $this->signupProcess($signupParams); 
        if ($validateSignup['formSubmitted'] == "1") {
            $validateSignup['redirectUrl'] = $reUrl;
          echo json_encode($validateSignup);
		  // $this->ObjView->display('account/AjaxLoginDetails.tpl');
           exit;
			}
        //Login Section
        $loginParams   = array(
            "ajaxRequest" => "0"
        );
        $validateLogin = $this->loginProcess($loginParams);
        if ($validateLogin['formSubmitted'] == "1") {
            $validateLogin['redirectUrl'] = $reUrl;
            echo json_encode($validateLogin);
            exit;
        }
        if ($reUrl != '') {
            $this->ObjView->assign('redirectUrl', '?reurl=' . $reUrl . '/');
            $this->ObjView->assign('__redirect_URL', $reUrl);
        } else {
            $this->ObjView->assign('redirectUrl', '');
        }
        if (isset($_SERVER['HTTP_REFERER'])) {
            if ($reUrl != '')
                $parenturl = '&parenturl=' . $_SERVER['HTTP_REFERER'];
            else
                $parenturl = '?parenturl=' . $_SERVER['HTTP_REFERER'];
        } else
            $parenturl = '';
        $this->ObjView->assign('parentUrl', $parenturl);
        $this->ObjView->assign('otpEnableRegistration', $otpEnableRegistration);
        $this->ObjView->assign('otpEnableCheckout', $otpEnableCheckout);
        $this->ObjCommon->setDynamicMenuPlugin($this->ObjView);

        if (!empty($_POST))
            $this->ObjView->display('account/AjaxLoginDetails.tpl');
        else
            $this->ObjView->display('account/AjaxPopupLogin.tpl');
    }
    private function mapUserCart($cartID, $userID) {
        $ObjCart                  = new CartModel();
        $productOptionIDArray     = array();
        $productOptionHashArray   = array();
        $cartItemOptionPriceArray = array();
        $cartItemHashPriceArray   = array();
        $persistShoppingCart      = $this->getSettingValue('product_cart_settings', 'persist_shopping_cart');
        $persistLifetime          = $this->getSettingValue('product_cart_settings', 'persist_lifetime');
        if ($persistShoppingCart == 'Yes') {
            $resUSerCartItems = $ObjCart->getUserCartItems($userID, $persistLifetime);
            if (count($resUSerCartItems) > 0) {
                foreach ($resUSerCartItems as $key => $items) {
                    if ($cartID < 1) {
                        $cartID = $items['cartID'];
                    }
                    if (isset($productOptionIDArray[$items['productOptionID']]) && $productOptionIDArray[$items['productOptionID']] != '' && isset($productOptionHashArray[$items['optionsHash']]) && $productOptionHashArray[$items['optionsHash']] != '' && isset($items['optionsHash']) && $items['optionsHash'] != '') {
                        $price                                       = $cartItemHashPriceArray[$items['optionsHash']];
                        $actualPrice                                 = $cartItemOptionActualPrice[$items['productOptionID']];
                        $offerPrice                                  = $cartItemOptionOfferPrice[$items['productOptionID']];
                        $tierPrice                                   = $cartItemOptionTierPrice[$items['productOptionID']];
                        $exquantity                                  = $cartItemHashQtyArray[$items['optionsHash']];
                        $quantity                                    = $items['orderItemQuantity'] + $exquantity;
                        $currentCartItemID                           = $items['cartItemID'];
                        $existingCartItemID                          = $productOptionHashArray[$items['optionsHash']];
                        $cartItemHashQtyArray[$items['optionsHash']] = $quantity;
                        $current_serializedData                      = unserialize($items['itemDetails']);
                        $serializedData                              = $ObjCart->getUnserializedCartItemData($existingCartItemID);
                        $product_service_fee                         = $current_serializedData['orderOtherServiceCharge'] / $items['orderItemQuantity'];
                        $currentAdminCommision                       = $price * ($serializedData['productCommissionRate'] / 100) * $quantity;
                        $currentServiceFee                           = $product_service_fee * $quantity;
                        $currentTotalAmount                          = ($price * $quantity) + $currentAdminCommision + $currentServiceFee;
                        $serializedData['orderItemQuantity']         = $quantity;
                        $serializedData['orderItemSubtotal']         = number_format($price * $quantity, 2, '.', '');
                        $serializedData['orderItemTotal']            = number_format($currentTotalAmount, 2, '.', '');
                        $serializedData['unitPrice']                 = number_format($price, 2, '.', '');
                        $serializedData['orderOtherServiceCharge']   = number_format($currentServiceFee, 2, '.', '');
                        $serializedData                              = $this->escape(serialize($serializedData), false, false);
                        $postData['orderItemPrice']                  = $price;
                        $postData['orderItemQuantity']               = $quantity;
                        $postData['actualPrice']                     = $actualPrice;
                        $postData['offerPrice']                      = $offerPrice;
                        $postData['tierPrice']                       = $tierPrice;
                        $postData['orderItemSubtotal']               = $price * $quantity;
                        $postData['itemDetails']                     = $serializedData;
                        if(empty($postData['dealDiscount'])) {
                            $postData['dealDiscount'] = 0;
                        }
                        $resUpdateCartItem                           = $ObjCart->updateCartItem(0, $existingCartItemID, $postData);
                        if ((int) $items['cartID'] != (int) $cartID) {
                            $resUpdateCartItem = $ObjCart->updateCartItemCartID($existingCartItemID, $cartID);
                            $resUpdateCartItem = $ObjCart->deleteCartItem(0, $currentCartItemID);
                            $resUpdateCartItem = $ObjCart->deleteCart($items['cartID']);
                        }
                    } else if (isset($productOptionIDArray[$items['productOptionID']]) && $productOptionIDArray[$items['productOptionID']] != '' && $items['optionsHash'] == '') {
                        $price                                             = $cartItemOptionPriceArray[$items['productOptionID']];
                        $actualPrice                                       = $cartItemOptionActualPrice[$items['productOptionID']];
                        $offerPrice                                        = $cartItemOptionOfferPrice[$items['productOptionID']];
                        $tierPrice                                         = $cartItemOptionTierPrice[$items['productOptionID']];
                        $exquantity                                        = $cartItemOptionQtyArray[$items['productOptionID']];
                        $quantity                                          = $items['orderItemQuantity'] + $exquantity;
                        $currentCartItemID                                 = $items['cartItemID'];
                        $existingCartItemID                                = $productOptionIDArray[$items['productOptionID']];
                        $cartItemOptionQtyArray[$items['productOptionID']] = $quantity;
                        $current_serializedData                            = unserialize($items['itemDetails']);
                        $serializedData                                    = $ObjCart->getUnserializedCartItemData($existingCartItemID);
                        $product_service_fee                               = $current_serializedData['orderOtherServiceCharge'] / $items['orderItemQuantity'];
                        $currentAdminCommision                             = $price * ($serializedData['productCommissionRate'] / 100) * $quantity;
                        $currentServiceFee                                 = $product_service_fee * $quantity;
                        $currentTotalAmount                                = ($price * $quantity) + $currentAdminCommision + $currentServiceFee;
                        $serializedData['orderItemQuantity']               = $quantity;
                        $serializedData['orderItemSubtotal']               = number_format($price * $quantity, 2, '.', '');
                        $serializedData['orderItemTotal']                  = number_format($currentTotalAmount, 2, '.', '');
                        $serializedData['unitPrice']                       = number_format($price, 2, '.', '');
                        $serializedData['orderOtherServiceCharge']         = number_format($currentServiceFee, 2, '.', '');
                        $serializedData                                    = $this->escape(serialize($serializedData), false, false);
                        $postData['orderItemPrice']                        = $price;
                        $postData['orderItemQuantity']                     = $quantity;
                        $postData['orderItemSubtotal']                     = $price * $quantity;
                        $postData['actualPrice']                           = $actualPrice;
                        $postData['offerPrice']                            = $offerPrice;
                        $postData['tierPrice']                             = $tierPrice;
                        $postData['itemDetails']                           = $serializedData;
                        $resUpdateCartItem                                 = $ObjCart->updateCartItem(0, $existingCartItemID, $postData);
                        if ((int) $items['cartID'] != (int) $cartID) {
                            $resUpdateCartItem = $ObjCart->updateCartItemCartID($existingCartItemID, $cartID);
                            $resUpdateCartItem = $ObjCart->deleteCartItem(0, $currentCartItemID);
                            $resUpdateCartItem = $ObjCart->deleteCart($items['cartID']);
                        }
                    } else {
                        if ((int) $items['cartID'] != (int) $cartID) {
                            $resUpdateCartItem = $ObjCart->updateCartItemCartID($items['cartItemID'], $cartID);
                            $resUpdateCartItem = $ObjCart->deleteCart($items['cartID']);
                        }
                        $productOptionIDArray[$items['productOptionID']]     = $items['cartItemID'];
                        $cartItemOptionPriceArray[$items['productOptionID']] = isset($cartItemOptionPriceArray[$items['productOptionID']]) ? $cartItemOptionPriceArray[$items['productOptionID']] : 0;
                        if ($cartItemOptionPriceArray[$items['productOptionID']] == '') {
                            $cartItemOptionPriceArray[$items['productOptionID']]  = $items['orderItemPrice'];
                            $cartItemOptionQtyArray[$items['productOptionID']]    = $items['orderItemQuantity'];
                            $cartItemOptionActualPrice[$items['productOptionID']] = $items['actualPrice'];
                            $cartItemOptionOfferPrice[$items['productOptionID']]  = $items['offerPrice'];
                            $cartItemOptionTierPrice[$items['productOptionID']]   = $items['tierPrice'];
                        }
                        if ($items['optionsHash'] != '') {
                            $productOptionHashArray[$items['optionsHash']] = $items['cartItemID'];
                            $cartItemHashPriceArray[$items['optionsHash']] = (isset($cartItemHashPriceArray[$items['optionsHash']]) ? $cartItemHashPriceArray[$items['optionsHash']] : '');
                            if ($cartItemHashPriceArray[$items['optionsHash']] == '') {
                                $cartItemHashPriceArray[$items['optionsHash']] = $items['orderItemPrice'];
                                $cartItemHashQtyArray[$items['optionsHash']]   = $items['orderItemQuantity'];
                            }
                        }
                    }
                }
            }
            if ($cartID > 0) {
                $resResetCartTotals = $ObjCart->resetCartTotals($cartID);
                $this->ObjSession->setSession("CARTID", $this->encodeString($cartID));
            }
        }
    }
    //checkout signup
    public function ajaxCheckoutSignupAction() {
	$otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
        $otpEnableRegistration  = $this->getSettingValue('sms_settings', 'enable_sms_otp');
        $signupParams   = array(
            "ajaxRequest" => "0"
        );
		$_POST['checkoutLogin'] ='Yes';
        $validateSignup = $this->signupProcess($signupParams);
        if ($validateSignup['formSubmitted'] == "1") {
             if($validateSignup['error']=='No' && $validateSignup['errorMessage']=='') {
			  $validateSignup['otpEnable'] =$otpEnableCheckout ;
                   echo json_encode($validateSignup);
                } else {
                    echo json_encode($validateSignup);
                }
		exit;
                }else{
              // echo json_encode($validateSignup);
            
        }
        $this->ObjView->assign('otpEnableCheckout', $otpEnableCheckout );
        $this->ObjView->assign('otpEnableRegistration', $otpEnableRegistration );
        $this->ObjView->assign('ajaxValidation', 'Yes');
        $this->ObjView->display('cart/AjaxCheckoutSignup.tpl');
    }
    //Login process
    public function loginProcess($params = array()) {
        $isAjax                       = true;
        $returnArray['error']         = 'No';
        $returnArray['errorMessage']  = '';
        $returnArray['formSubmitted'] = 0;
        $validSubmission              = false;
        $isFacebook                   = false;
        $validatEmail                 = false;
        $isSignup                     = 'login';
        if (!empty($params)) {
            //For Handling AJAX and Direct page Request
            if (isset($params['ajaxRequest']) && $params['ajaxRequest'] == "0") {
                $isAjax = false;
            }
            //Affiliate imported users
            if (isset($params['hasValidSession'])) {
                $validSubmission = true;
            }
            //Validate Email
            if (isset($params['validatEmail']) && $params['validatEmail'] == "1") {
                $validatEmail = true;
            }
            //For Facebook Login
            if (isset($params['isFacebook']) && $params['isFacebook'] == "1") {
                $isFacebook      = true;
                $validSubmission = true;
            }
        }
        $languageIDs = $this->ObjView->languageIDs;
        $this->ObjView->assign('isSignup ', $isSignup );
        if ($this->ObjForm->isValid('formLogin', 'submitLogin', false) || $validSubmission) {
            //Form Submitted
            $returnArray['formSubmitted']          = 1;
            $ObjLanguage                           = new LanguageModel();
            $ObjAdmin                              = new AdminuserModel();
            $ObjUser                               = new UserModel();
            $ObjCart                               = new CartModel();
            $blockingPeriod                        = $this->getSettingValue('security_settings', 'blocking_period');
            $settingsSecurityAdminBlockingAttempts = $this->getSettingValue('security_settings', 'security_account_blocking_attempts');
	    $otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
            $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
            $userEmail                             = $_POST['userLoginEmail'];
            $userPassword                          = '';
            //Password not required for facebook
            if (!$isFacebook) {
                $userPassword = $this->escape($_POST['userLoginPassword']);
            }
            if ($validatEmail) {
                //Validate Email
                $isValidEmail = $this->validateEmail($_POST['userLoginEmail'], $isAjax);
                if ($isValidEmail['error'] == "Yes") {
                    $returnArray['error']        = 'Yes';
                    $returnArray['errorMessage'] = $isValidEmail['errorMessage'];
                    return $returnArray;
                }
            }
            $loginParams    = array(
                "userEmail" => $userEmail
            );
            $resUserDetails = $ObjUser->getUserDetailsForLogin($loginParams);
            if (!$isFacebook) {
                $hashedPassword = $resUserDetails['userPassword'];
                $pwd_exists     = $ObjUser->verify($userPassword, $hashedPassword);
            } else
                $pwd_exists = 1;			
			if($resUserDetails['isverify']=='N' && !$isFacebook &&  ($pwd_exists)){
                            if($_POST['checkoutLogin']==''){// NORAMAL LOGIN
                                if($otpEnableRegistration=='Yes'){
                                    
                                    $this->ObjSession->setSession("TEMP_USER_ID", $resUserDetails['userID']);
                                    $this->ObjSession->setSession("TEMP_USER_PASSWORD", $userPassword);
                                    $returnArray['error']        = 'Yes';
                                    $returnArray['isverify']        = 'No';
                                    $returnArray['userPhoneVerify']        = $resUserDetails['userPhone'];
                                    $returnArray['countryCodeVerify']      = $resUserDetails['userPhoneCountryID'];
                                    $this->verifyMobileAction();
                                    return $returnArray;
                                } else {
                                    $this->signupProcessComplete($resUserDetails['userID'],'',$isSignup);
                                    $resUserDetails = $ObjUser->getUserDetailsForLogin($loginParams);
                                }
                            }else if($_POST['checkoutLogin']!=''){
                                if($otpEnableCheckout == 'Yes' || $otpEnableRegistration=='Yes'){
                                    $this->ObjSession->setSession("TEMP_USER_ID", $resUserDetails['userID']);
                                    $this->ObjSession->setSession("TEMP_USER_PASSWORD", $userPassword);
                                    $returnArray['error']        = 'Yes';
                                    $returnArray['isverify']        = 'No';
                                    $returnArray['userPhoneVerify']        = $resUserDetails['userPhone'];
                                    $returnArray['countryCodeVerify']      = $resUserDetails['userPhoneCountryID'];
                                    return $returnArray;
                                }else {
                                    $this->signupProcessComplete($resUserDetails['userID'],'',$isSignup);
                                    $resUserDetails = $ObjUser->getUserDetailsForLogin($loginParams);
                                }
			 }
			}			

            $msgAccountIs    = $this->getLanguageValue("msgAccountIs");
            $msgFor          = $this->getLanguageValue("msgFor");
            $msgBlockedFor   = $this->getLanguageValue("msgBlockedFor");
            $msgMinutes      = $this->getLanguageValue("msgMinutes");
            $msgContactAdmin = $this->getLanguageValue("msgContactAdmin");
            if ($resUserDetails['userID'] > 0 && ($pwd_exists)) {
                $userStatus                = $resUserDetails['userStatus'];
                $resCheckLoginAttemptCount = $ObjUser->updateInvalidLoginAttemptCount($userEmail, $settingsSecurityAdminBlockingAttempts, $resUserDetails['userID']);
                if ($userStatus == 'Active' && ($resCheckLoginAttemptCount <= $settingsSecurityAdminBlockingAttempts || $settingsSecurityAdminBlockingAttempts < 1)) {
                    $updateLastAccess = $ObjUser->updateUserLastAccess($resUserDetails['userID']);
                }
                if ($userStatus == 'Locked' && $resCheckLoginAttemptCount != 99) {
                    $lockedTime  = strtotime($resUserDetails['userLockedDate']);
                    $currentTime = strtotime(date("Y-m-d H:i:s"));
                    $diff        = abs($currentTime - $lockedTime);
                    $years       = floor($diff / (365 * 60 * 60 * 24));
                    $months      = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
                    $days        = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
                    $hours       = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));
                    $diff_minuts = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);
                    $diff_minuts = $diff / 60;
                    if ($diff_minuts > $blockingPeriod) {
                        $resActivateUserAccount = $ObjUser->activateUserAccount($userEmail);
                         $resUserDetails = $ObjUser->getUserDetailsForLogin($loginParams);
                        $userStatus             = $resUserDetails['userStatus'];
                    } else {
                        //echo "blockadmin";
                        $msgAccountIsStatusContactAdmin = $msgAccountIs . $userStatus . $msgFor . $blockingPeriod . $msgMinutes;
                        if ($isAjax) {
                            echo $msgAccountIsStatusContactAdmin;
                            exit;
                        } else {
                            $returnArray['error']        = 'Yes';
                            $returnArray['errorMessage'] = $msgAccountIsStatusContactAdmin;
                            return $returnArray;
                        }
                    }
                }
                if ($userStatus != "Locked" && $userStatus != "Inactive" && $userStatus != "Deleted") {
                    $ObjUser->activateUserAccount($userEmail, $resUserDetails['userID']);
                    $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");
                    //###############LOG TRACKING SECTION###########//
                    if (__ANALYTICS_MODULE || __AFFILIATE_MODULE) {
                        $this->loginTracking($userID);
                    }
                    //##############LOG TRACKING SECTION############//
                    //MIC
                    $cartID = $this->decodeString($this->ObjSession->getSession("CARTID"));
                    if ($cartID > 0) {
                        $ObjCart->updateCartUserID($cartID, $userID);
                        $ObjCart->resetCartItemsTierPrice($cartID, $userGroupID);
						$returnArray['redirectURL']        = 'cart/checkout/';
                    }
                    $this->mapUserCart($cartID, $userID);
                    if ($isAjax) {
                        echo "success";
                        exit;
                    } else {
                        return $returnArray;
                    }
                } elseif ($userStatus == "Inactive") {
                    if ($isAjax) {
                        echo $this->getLanguageValue("msgAccountInactive");
                        exit;
                    } else {
                        $returnArray['error']        = 'Yes';
                        $returnArray['errorMessage'] = $this->getLanguageValue("msgAccountInactive");
                        return $returnArray;
                    }
                } else {
                    if ($resCheckLoginAttemptCount == 99) {
                        $msgAccountIs                   = $this->getLanguageValue("msgAccountIs");
                        $msgContactAdmin                = $this->getLanguageValue("msgContactAdmin");
                        $msgAccountIsStatusContactAdmin = $msgAccountIs . " blocked " . $msgContactAdmin;
                        if ($isAjax) {
                            echo $msgAccountIsStatusContactAdmin;
                            exit;
                        } else {
                            $returnArray['error']        = 'Yes';
                            $returnArray['errorMessage'] = $msgAccountIsStatusContactAdmin;
                            return $returnArray;
                        }
                    } else {
                        if ($isAjax) {
                            echo $this->getLanguageValue("msgAccountBlocked");
                            exit;
                        } else {
                            $returnArray['error']        = 'Yes';
                            $returnArray['errorMessage'] = $this->getLanguageValue("msgAccountBlocked");
                            return $returnArray;
                        }
                    }
                }
            } else {
                $resGetUserDetails = $ObjUser->getUserDetails('', $userEmail, '', '', '');
                if ($resGetUserDetails['userStatus'] == "Inactive") {
                    if ($isAjax) {
                        echo $this->getLanguageValue("msgAccountInactive");
                        exit;
                    } else {
                        $returnArray['error']        = 'Yes';
                        $returnArray['errorMessage'] = $this->getLanguageValue("msgAccountInactive");
                        return $returnArray;
                    }
                } else {
                    if ($this->getSettingValue('security_settings', 'security_account_blocking') == 'Yes' && !empty($resGetUserDetails)) {
                        if ($resGetUserDetails['userStatus'] == 'Locked' && $resGetUserDetails['userInvalidAccessCount'] != 99) {
                            $lockedTime  = strtotime($resGetUserDetails['userLockedDate']);
                            $currentTime = strtotime(date("Y-m-d H:i:s"));
                            $diff        = abs($currentTime - $lockedTime);
                            $years       = floor($diff / (365 * 60 * 60 * 24));
                            $months      = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
                            $days        = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
                            $hours       = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));
                            $diff_minuts = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);
                            $diff_minuts = $diff / 60;
                            if ($diff_minuts > $blockingPeriod) {
                                $ObjUser->activateUserAccount($userEmail);
                                $ObjUser->updateInvalidLoginAttemptCount($userEmail, $settingsSecurityAdminBlockingAttempts);
                                if ($isAjax) {
                                    echo $this->getLanguageValue("msgInvalidUnameOrPaswd");
                                    exit;
                                } else {
                                    $returnArray['error']        = 'Yes';
                                    $returnArray['errorMessage'] = $this->getLanguageValue("msgInvalidUnameOrPaswd");
                                    return $returnArray;
                                }
                            } else {
                                if ($isAjax) {
                                    echo $this->getLanguageValue("msgAccountBlocked");
                                    exit;
                                } else {
                                    $returnArray['error']        = 'Yes';
                                    $returnArray['errorMessage'] = $this->getLanguageValue("msgAccountBlocked");
                                    return $returnArray;
                                }
                            }
                        }
                        $resCheckLoginAttemptCount = $ObjUser->updateInvalidLoginAttemptCount($userEmail, $settingsSecurityAdminBlockingAttempts);
                        if ($resCheckLoginAttemptCount == 99) {
                            $msgAccountIs                   = $this->getLanguageValue("msgAccountIs");
                            $msgContactAdmin                = $this->getLanguageValue("msgContactAdmin");
                            $msgAccountIsStatusContactAdmin = $msgAccountIs . " blocked " . $msgContactAdmin;
                            if ($isAjax) {
                                echo $msgAccountIsStatusContactAdmin;
                                exit;
                            } else {
                                $returnArray['error']        = 'Yes';
                                $returnArray['errorMessage'] = $msgAccountIsStatusContactAdmin;
                                return $returnArray;
                            }
                        } elseif ($resCheckLoginAttemptCount == $settingsSecurityAdminBlockingAttempts) {
                            $msgAccountIsStatusContactAdmin = $msgAccountIs . $msgBlockedFor . $blockingPeriod . $msgMinutes;
                            if ($isAjax) {
                                echo $msgAccountIsStatusContactAdmin;
                                exit;
                            } else {
                                $returnArray['error']        = 'Yes';
                                $returnArray['errorMessage'] = $msgAccountIsStatusContactAdmin;
                                return $returnArray;
                            }
                        } elseif ($resCheckLoginAttemptCount > $settingsSecurityAdminBlockingAttempts) {
                            if ($isAjax) {
                                echo $this->getLanguageValue("msgAccountBlocked");
                                exit;
                            } else {
                                $returnArray['error']        = 'Yes';
                                $returnArray['errorMessage'] = $this->getLanguageValue("msgAccountBlocked");
                                return $returnArray;
                            }
                        } else {
                            if ($isAjax) {
                                echo $this->getLanguageValue("msgInvalidUnameOrPaswd");
                                exit;
                            } else {
                                $returnArray['error']        = 'Yes';
                                $returnArray['errorMessage'] = $this->getLanguageValue("msgInvalidUnameOrPaswd");
                                return $returnArray;
                            }
                        }
                    } else {
                        if ($isAjax) {
                            echo $this->getLanguageValue("msgInvalidUnameOrPaswd");
                            exit;
                        } else {
                            $returnArray['error']        = 'Yes';
                            $returnArray['errorMessage'] = $this->getLanguageValue("msgInvalidUnameOrPaswd");
                            return $returnArray;
                        }
                    }
                }
            }
            $_POST['userEmail']         = '';
            $_POST['userLoginPassword'] = "";
        }
        return $returnArray;
    }
   //Signup Process
    public function signupProcess($params = array()) {
        $isAjax                       = true; //For Handling AJAX and Direct page Request
        $isFacebook                   = false;
        $facebookUserData             = array();
        $returnArray['error']         = 'No';
        $returnArray['errorMessage']  = '';
        $returnArray['formSubmitted'] = 0;
        $isSignup                     = 'signup';
        if (!empty($params)) {
            if (isset($params['ajaxRequest']) && $params['ajaxRequest'] == "0") {
                $isAjax = false;
            }
            //For Facebook Login
            if (isset($params['isFacebook']) && $params['isFacebook'] == "1") {
                $isFacebook = true;
            }
            //For Facebook
            if (!empty($params['facebookUserData'])) {
                $facebookUserData = $params['facebookUserData'];
            }
        }
        
        $ObjUser          = new UserModel();
        $ObjCountry          = new CountryModel();
        $ObjEmailtemplate = new EmailtemplateModel();
        $ObjCart          = new CartModel();
        $languageIDs      = $this->ObjView->languageIDs;
		$otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
		 
		$resListCountryCode        = $ObjUser->loadAllCountryCode($languageIDs); 
               $resCountryCode= $ObjCountry->getAllCountryCode($languageIDs);
			 //  echo "<pre>";print_r($resCountryCode);exit;
               $this->ObjView->assign('resCountryCode', $resCountryCode);
		  $this->ObjView->assign('resListCountryCode', $resListCountryCode);
                
       $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
	$otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
	$this->ObjView->assign('otpEnableCheckout ', $otpEnableCheckout );
        $this->ObjView->assign('otpEnableRegistration ', $otpEnableRegistration );
        $this->ObjView->assign('isSignup ', $isSignup );
        if ($this->ObjForm->isValid('formUserSignup', 'submit') || $isFacebook) {
           
		//$returnArray['userPhoneVerify'] =$_POST['userPhone'];
		$returnArray['countryCodeVerify'] =$_POST['userCountrycode'];
                $returnArray['userPhoneVerify'] = ltrim($_POST['userPhone'], '0');
                $_POST['userEmail'] = $_POST['userEmail'];
                $_POST['userFirstName'] = $_POST['userFirstName'];
                $_POST['userCountrycode'] = $_POST['userCountrycode'];
            if (isset($_POST['ajaxSubmit']) && $_POST['ajaxSubmit'] >0)
            {
                $isAjax = true;
            }
            //Form Submitted
            $returnArray['formSubmitted'] = 1;
            if (!$isFacebook) {
                $isValidEmail = $this->validateEmail($_POST['userEmail'], $isAjax);
                if ($isValidEmail['error'] == "Yes") {
                    $returnArray['error']        = 'Yes';
                    $returnArray['errorMessage'] = $isValidEmail['errorMessage'];
                    return $returnArray;
                }
                $_POST['userCurrentLanguage'] = $languageIDs['Current'];
                $_POST['userDefaultLanguage'] = $languageIDs['Current'];
              // $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
                $_POST['userStatus'] = 'Inactive';//Inactive;//CHNAGE ON NXT COMMIT
                $spliName = explode(' ', $_POST['userFirstName'], 2);
               $_POST['userFirstName']  =  $spliName[0];
               $_POST['userLastName']  =  $spliName[1];
               $_POST['userSourceOfReg']  =  $this->ObjCommon->_platform;
                $user                         = $ObjUser->saveUserDetails($_POST, '');
				 
				   if ($user) {
                                      
				  if($_POST['checkoutLogin']==''){
                                      
                                        if($otpEnableRegistration=='Yes'){
                                          
                                         $this->ObjSession->setSession("TEMP_USER_ID", $user);
					 $this->ObjSession->setSession("TEMP_USER_PASSWORD", $_POST['userPassword']);
                                           $returnArray['otpVerfdReg'] = 'Yes';
					 $this->verifyMobileAction();
                                          }
                                         else{
                                              $returnArray['otpVerfdReg'] = 'No';
                                              $this->signupProcessComplete($user,'',$isSignup);
                                         }
                                         
                                        return $returnArray;
					}else if ($_POST['checkoutLogin']!='')
                                        {
                                        if($otpEnableCheckout == 'Yes'){
                                      
                                         $this->ObjSession->setSession("TEMP_USER_ID", $user);
					 $this->ObjSession->setSession("TEMP_USER_PASSWORD", $_POST['userPassword']);
					 $this->verifyMobileAction();
                                         return $returnArray;
					}else{
					  $this->signupProcessComplete($user,'',$isSignup);			
					}
                                        }else{
					  $this->signupProcessComplete($user,'',$isSignup);			
					} 
				   }
            } else //Facebook
                {
                $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
                 if($otpEnableRegistration=='Yes' && $_POST['checkoutLogin']==''){
                     $_POST['userStatus'] ='Inactive'; 
                 }
                 else if($otpEnableCheckout =='Yes' && $_POST['checkoutLogin']=='Yes'){
                      $_POST['userStatus'] = 'Inactive';
                 }
                 else{
                      $_POST['userStatus'] = 'Active';
                 }
                $user = $ObjUser->saveFbUserDetails($facebookUserData);
				$this->ObjSession->setSession("TEMP_USER_ID", $user);
				$returnArray['error']='Yes';
				$returnArray['isverify']='No';
                                
                                 if($otpEnableRegistration=='Yes' && $_POST['checkoutLogin']!='Yes'){
                                      $returnArray['otpVerfdReg'] = 'Yes';
                                 }
                                else if($otpEnableCheckout =='Yes' && $_POST['checkoutLogin']=='Yes'){
                                        $returnArray['otpVerfdReg'] = 'Yes';
                                 }
                                 else{
                                      $returnArray['otpVerfdReg'] = 'No';
                                 }
                                 if($otpEnableRegistration!='Yes' && $_POST['checkoutLogin']==''){
                                     $this->signupProcessComplete($user,'',$isSignup);
                                 }
                                 if($_POST['checkoutLogin']!='' && $otpEnableCheckout!='Yes'){
                                     $this->signupProcessComplete($user,'',$isSignup);
                                 }
				 return $returnArray;
				//$this->signupProcessComplete($user);
            }
           if (!$user) {
                if (!$isFacebook) {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errLoginExists");
                } else //Facebook
                    {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errorSignup");
                }
                $returnArray['error'] = 'Yes';
                return $returnArray;
            }
        }
        return $returnArray;
    }    
    //Set User Sessions
    public function setUserSessions($params = array()) {
       // session_regenerate_id();        
        $setCartID  = '';
        $oldCartID  =   $this->decodeString($this->ObjSession->getSession("CARTID"));
        if($oldCartID>0) {
            $ObjCart                    = new CartModel();
            $resCart                    = $ObjCart->getCartDetails($oldCartID);        
            if(!empty($resCart['items'])) {            
                $setCartID = $oldCartID;
            }
        }
        $this->ObjSession->resetSession();        
        if($setCartID!='') {
            $this->ObjSession->setSession("CARTID", $this->encodeString($setCartID));
        }
        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());
        }
    }
    //Page Redirection for facebook
    public function fbPageRedirect($resultArray = array()) {
        
        $reUrl = (isset($_GET['reurl'])) ? trim($_GET['reurl']) : '';        
        if ($reUrl != '') {
            if(substr($reUrl,0, 1)=='/') {
                $reUrl  = substr($reUrl,1);
                $reUrl  = rtrim($reUrl, '/');
            }
            $global_http_url = (rtrim($this->getSettingValue('site_settings', 'global_http_url'), '/')) . "/";
			$returnArray['error']        = 'No';
			$returnArray['isverify']        = 'Yes';
			echo json_encode($returnArray);exit;				
           // echo "<script>window.top.location.href = '" . $global_http_url . $reUrl . "/';</script>";
           // exit;
        }
        if (isset($resultArray['parentUrl']) && !empty($resultArray['parentUrl'])) {
            echo "<script>window.top.location.href = '" . $resultArray['parentUrl'] . "';</script>";
            exit;
        } else {
            $previousUrl = $_SERVER['HTTP_REFERER'];
            header('location:'.$previousUrl);
        }
    }
    //to get template details between given comments
    function getTemplateDetails($template, $string) {
        $beginTxt      = '<!--' . $template . '_BEGIN-->';
        $endTxt        = '<!--' . $template . '_END-->';
        $otherTemplate = substr($string, strlen($beginTxt) + strpos($string, $beginTxt), (strlen($string) - strpos($string, $endTxt)) * (-1));
        return $otherTemplate;
    }
    public function ajaxPopupHomePageAction()
    {
        $ObjContent    	   = new ContentModel();	
        $languageIDs       = $this->ObjView->languageIDs;        
        $resContent    	   = $ObjContent->getContentDetails($languageIDs, '','subscription-popup','','publish','','yes','');        
        $this->ObjView->assign('contentDesc', $resContent['content']);
        $this->ObjView->display('account/PopupHomePage.tpl');
    }
     public function googlePlusAction() {            
        $this->checkgPlusLogin($this->ObjView, $this->ObjSession, $this->ObjCookie);        
    }
    public function checkgPlusLogin($ObjView, $ObjSession, $ObjCookie) {
        $ObjUser = new UserModel();
        $registeredUserID = $this->ObjSession->getSession("REGISTERED_USER_ID");
        if ($registeredUserID) {
            $this->setRedirect('/user/account/');
        }        
        $ObjLanguage = new LanguageModel();
        //$languageIDs = $ObjLanguage->getLanguageID();
        $languageIDs      = $this->ObjView->languageIDs;
        $userCurrentLanugage  =  $languageIDs['Current'];
        
        $resLanguageDetails = $ObjLanguage->getLanguageByLCID($userCurrentLanugage);
        $currLanguageID = $resLanguageDetails['languageID'];
        
        $userInfo = unserialize(base64_decode($this->getRequestValue(2)));
        $userInfo['languageID'] = $userCurrentLanugage;
        
        $ObjSession->setSession("GPLUS_USER_ID", $userInfo['id']);
        $userAccessDateTime = date("l, F d, Y- h:m A");
        $userIPAddress = $_SERVER['REMOTE_ADDR'];
        $userCurrentLanugage = $ObjCookie->getCookie($this->ObjView->_section . '_CurrentLanguageCode');
        if ($userCurrentLanugage == '')
            $userCurrentLanugage = $this->ObjSession->getSession($this->ObjView->_section . '_CurrentLanguageCode');
        if ($userCurrentLanugage == '')
            $userCurrentLanugage = $this->getSettingValue('site_settings', 'custom_language');

        $resLanguageDetails = $ObjLanguage->getLanguageByLCID($userCurrentLanugage);
        $currLanguageID = $resLanguageDetails['languageID'];

        if ($userInfo['email'] != "") {
            
            $userDetails = $ObjUser->getUserDetails(0, $userInfo['email'], "", "", "");
            if ($userDetails['userID'] < 1) {
                $cityID = $this->ObjSession->getSession('CITY_ID');
                $userInfo['selectedCity'] = $cityID;
                $userID = $ObjUser->savegPlusUserDetails($userInfo);
                if ($userID) {
                    $userName = $userInfo['name'];
                    /* FOR THANK YOU POPUP */
                    $this->ObjSession->setSession('REG_THANKYOU', 'Yes');
                    /* END FOR THANK YOU POPUP */
                }
            } else {
                $userStatus = $userDetails['userStatus'];
                if ($userStatus == "Locked" || $userStatus == "Inactive") {
                    $msgAccountIs = $this->getLanguageValue("msgAccountIs");
                    $msgContactAdmin = $this->getLanguageValue("msgContactAdmin");
                    $msgAccountIsStatusContactAdmin = $msgAccountIs . ' ' . $userStatus . $msgContactAdmin;
                    $this->setMessage($msgAccountIsStatusContactAdmin, "message_error", "Login", "common_fb_message");
                    $this->setRedirect('/index/');
                }
                $userID = $userDetails['userID'];
                if ($userDetails['userName'] == '') {
                    $ObjUser->updateFbUserID($userID, $userInfo['id']);
                }
                $userName = $userDetails['userFirstName'] . " " . $userDetails['userLastName'];
            }
            $resUserDetails = $ObjUser->getUserDetails(0, $userInfo['email'], "", "", "");
            $ObjSession->setSession("REGISTERED_USER_ID", $userID);
            $ObjSession->setSession("REGISTERED_USER_EMAIL", $resUserDetails['userEmail']);
            $ObjSession->setSession("TIMEOUT", time());
            $ObjSession->setSession("REGISTERED_USER_NAME", $userName);
            $ObjSession->setSession("REGISTERED_USER_IP", $userIPAddress);
            $ObjSession->setSession("REGISTERED_USER_ACCESS_DATE_TIME", $userAccessDateTime);
            $languageID = ($resUserDetails['userDefaultLanguage'] != '') ? $resUserDetails['userDefaultLanguage'] : 1;
            $resLanguageDetails = $ObjLanguage->getLanguageDetails($languageID);
            $languageLCIDstring = $resLanguageDetails['LanguageLCIDstring'];
            $this->ObjSession->setSession($this->ObjView->_section . '_CurrentLanguageID', $resLanguageDetails['languageID']);
            $this->ObjCookie->setCookie($this->ObjView->_section . '_CurrentLanguageCode', $languageLCIDstring);
            $this->ObjCookie->setCookie($this->ObjView->_section . '_CurrentLanguageID', $resLanguageDetails['languageID']);
            $this->ObjSession->setSession($this->ObjView->_section . '_CurrentLanguageCode', $languageLCIDstring);
           
           // $this->fbPageRedirect($_REQUEST);
            $reUrl = (isset($_GET['reurl'])) ? trim($_GET['reurl']) : '';        
            if ($reUrl != '') {
                if(substr($reUrl,0, 1)=='/') {
                    $reUrl  = substr($reUrl,1);
                    $reUrl  = rtrim($reUrl, '/');
                }
                $global_http_url = (rtrim($this->getSettingValue('site_settings', 'global_http_url'), '/')) . "/";						
                echo "<script>window.top.location.href = '" . $global_http_url . $reUrl . "/';</script>";
                exit;
            }
            if (isset($_REQUEST['parentUrl']) && !empty($_REQUEST['parentUrl'])) {
                echo "<script>window.top.location.href = '" . $_REQUEST['parentUrl'] . "';</script>";
                exit;
            } 
                       
            $historyURL = trim($this->getHistoryURL(), "/");
            if (trim($historyURL) == "cart/checkout") {
                $this->setRedirect("/cart/checkout/");
            } else {
                $this->setRedirect("/index/");
            } 
            
            if ((@substr_count($historyURL, "productreview/id/") > 0)) {
                $this->setRedirectNew("/" . trim($historyURL, "/") . "/");
            } else if (trim($historyURL) == "giftcoupon") {
                $this->setRedirectNew("/giftcoupon/");
            } else if (trim($historyURL) == "cart") {
                $this->setRedirectNew("/cart/");
            } else if (trim($historyURL) == "cart/checkout") {
                $this->setRedirectNew("/cart/checkout/");
            } else if (trim($historyURL) == "feed/preference") {
                $this->setRedirectNew("/feed/preference");
            } else if (trim($historyURL) == "user/referrals") {
                $this->setRedirectNew("/user/referrals/");
            } else if (trim($historyURL) == "user/wishlist") {
                $this->setRedirectNew("/user/wishlist/"); 
            } 
//            else if (trim($historyURL) == "store/profile") {
//               $this->setRedirect("/store/profile/");
//            }
            else if (trim($historyURL) == "store" || (@substr_count(trim($historyURL), 'store/') > 0)) {
                $reviewInfo = $this->ObjCookie->getCookie("REVIEW_INFO", "No");
                $reviewSplit = explode(':', $reviewInfo);
                if ($reviewSplit[0]) {
                    $this->setRedirect("/store/" . $reviewSplit[0] . "/");
                } else {
                    $this->setRedirect("/" . trim($historyURL) . "/");
                }
            }
            else if (trim($historyURL) == "feed") {
                $this->setRedirect("/feed/");
            } else {
                //$this->setRedirect("/user/account/");
                $this->setRedirectNew("/index/");
            }
        }
    }
	    public function signupProcessComplete($user,$isFacebook,$isSignup='') {
              
		  $ObjUser       = new UserModel();
		   $ObjCart                  = new CartModel();
		   $ObjEmailtemplate = new EmailtemplateModel();
		    $languageIDs   = $this->ObjView->languageIDs;
            if ($user) {
                //set cookie
                $resUserDetails = $ObjUser->getBasicUserDetails($user, array(
                    "userID",
                    "userGroupID",
                    "userFirstName",
                    "userLastName",
                    "userPhoneCountryID",
                    "userPhone",
                    "userEmail",
                    "userStatus",
                    "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']
                );
				$_POST['userPassword']=$userPassword=$this->ObjSession->getSession("TEMP_USER_PASSWORD");
                $this->setUserSessions($sessionParams);
				 $ObjUser->activateUserDetails( $userID);
                $resUserDetails = $ObjUser->getBasicUserDetails($user, array(
                    "userID",
                    "userGroupID",
                    "userFirstName",
                    "userLastName",
                    "userPhoneCountryID",
                    "userPhone",
                    "userEmail",
                    "userStatus",
                    "userDefaultLanguage"
                ));
                $ObjCart->linkOrderToUser($userID, $resUserDetails['userEmail']);
                $this->ObjSession->unsetSession("GUEST_ORDER_ID");
                $this->ObjSession->unsetSession("GUEST_EMAIL_ID");
				$this->ObjSession->unsetSession("TEMP_USER_ID");
				$this->ObjSession->unsetSession("TEMP_USER_PASSWORD");				
                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);
					$returnArray['redirectURL']        = 'user/account/';
                }
				if ($resUserDetails['userStatus']  =='Active' &&  $isSignup=='signup') {
			      	/* SMS Start */
						$ObjSmsTemplate            = new SmstemplateModel();
						$messageBody               = $ObjSmsTemplate->getSmsTempDetails("", $languageIDs,'sms_buyer_registration');
						
												
						//  sms body
							$bodytag                = str_replace('(1)', $resUserDetails['userFirstName'], $messageBody['smsTemplateContent']);

                        $user_id=$this->getSettingValue('sms_settings', 'sms_username');
                        $password=$this->getSettingValue('sms_settings', 'sms_password'); 
                        $userPhone     = $resUserDetails['userPhone'];
                        $userPhoneCountryID     = $resUserDetails['userPhoneCountryID'];
                       // $us  $userPhoneFul= str_replace("-","",$userPhoneFull);erPhoneFull= str_replace("-","",$resUserDetails['userPhone']);
                       $userPhoneFul= str_replace("91-","",$userPhone);
                       $userPhoneFull= '91'.$userPhoneFul;
                   
                   
                        if($userPhoneFull!=''){
                                $sms = new Sms($user_id, $password);
                                $result	=	$sms->setSms($bodytag,$userPhoneFull,'Normal',$msgKey);
                        }
                        /* SMS End */				
				
                $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                     = $resUserDetails['userFirstName'] . ' ' . $resUserDetails['userLastName'];
                //email body
                $bodytag                      = str_replace('{$userEmailID}', $resUserDetails['userEmail'], $emailbody['emailHtml']);
                $bodytag                      = str_replace('{$name}', $resUserDetails['userFirstName'] . " " . $resUserDetails['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}', $resUserDetails['userEmail'], $emailbody['emailHtml']);
                    $bodytag = str_replace('{$userPassword}', $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, $resUserDetails['userEmail'], $emailbody['emailSubject'], $body);
                if ($ObjMail->Send()) {
                    
                }
                if ($isAjax && !$isFacebook) {
                        echo "success";
                        exit;
                    } else {
                        return $returnArray;
                    }
            } else {
                if (!$isFacebook) {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errLoginExists");
                } else //Facebook
                    {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errorSignup");
                }
                $returnArray['error'] = 'Yes';
                return $returnArray;
            }
			}
       		
		}
        // NEW FUNCTION FOR CREATE RANDUM NUMBER
        private function randomString($count=4)
        {
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            $randstring = '';
            for ($i = 0; $i < $count; $i++) {
                $randstring.= $chars[rand(0, strlen($chars)-1)];
            }
            return $randstring;
        }
        //Ajax Action FOR MOBILE VERFY
        public function ajaxVerifyMobileAction()
	{
              
            $language_ids             = $this->ObjView->languageIDs;          
            $userID                   = $this->ObjSession->getSession("TEMP_USER_ID");
            $ObjUser                  = new UserModel();
            $returnArray['error']        = 'No';
            $returnArray['errorMessage'] = '';			
            $userPhone                = '';    
            $closePopup               = 'No';
            $redirect                 = $_GET['reurl']; 
			$page                 	  = (!empty($_GET['page'])) ? $_GET['page'] : '';  	
            $usrPhone                 = (!empty($_POST['userPhoneVerify'])) ? $_POST['userPhoneVerify'] : ''; 
            $usrPhone = ltrim($usrPhone, '0');
	    $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
		   
		   $resListCountryCode        = $ObjUser->loadAllCountryCode($language_ids);            
            if($userID > 0) {              
                $timeout  = $this->getSettingValue('sms_settings', 'otp_expire_time');
                $verifyDet            =       $ObjUser->getVarifyMobile($userID,$timeout);
				
				if(strpos($verifyDet['userPhone'],'-')=== false) {
                    $userPhone      	= $verifyDet['userPhone'];
                }else {
                    $phoneSplitted      = explode('-',$verifyDet['userPhone']);
                    $userPhone          = $phoneSplitted[1];
                    //$countryCode      = $phoneSplitted[0];
                }
                $countryCode    = $verifyDet['userPhoneCountryID'];
				
                if($verifyDet['code_send_date']==NULL OR $verifyDet['code_send_date']=='0000-00-00') {
                    $showTab='send';
                } else {
					if($page=='edit') {
						if(($userPhone==$usrPhone)) {
							$this->ObjView->assign('verify_codes', "");  
							$showTab='verify';
						}
						else
							$showTab='send';
					} else {
						$this->ObjView->assign('verify_codes', "");  
						$showTab='verify';
					}
                }

                if ($this->ObjForm->isValid('formVerifyCode', 'submitCode','', false))
                {
                 
                    $_POST['userID']        = $userID;       
					$hashedCode 			= $verifyDet['verify_code'];
                $code_exists     = $ObjUser->verify($this->escape($_POST['verify_codes']), $hashedCode);
                    if($code_exists) {
						 if($timeout>0 && $verifyDet['expireCode'] ==0){
							 $returnArray['error'] = 'Yes';
							 $returnArray['errorMessage'] = $this->getLanguageValue("errOTPMessage");
                                                          
							 echo json_encode($returnArray);
							 exit;				 
						 }					
                        $_POST['isverify']   = 'Y';
                        $retVerify           = $ObjUser->saveMobileVerify($_POST); 
                         $isSignup            = 'signup';
                        $closePopup          = 'Yes';
						$isFacebook = ($verifyDet['userLoginType']=='Facebook')?1:'';
						$this->signupProcessComplete($userID,$isFacebook,$isSignup);
                    }else {
					 $returnArray['error'] = 'Yes';
					  $returnArray['errorMessage'] = $this->getLanguageValue("errWrongVerifyCode");
                       
                    }
                }
                if ($this->ObjForm->isValid('formVerifyMobile', 'submitVerify','', false))
                {
                    $_POST['verify_code']   = $verify_code = $this->randomString(4);
                    $_POST['userID']        = $userID; 
                    $_POST['send_date']     = 'NOW';
                    $_POST['userCountrycode'] = $_POST['userCountrycode'];
                    $countryCode            = $_POST['userCountrycode'];  
                    $_POST['userPhone']     = $_POST['userPhoneVerify'];
                   // $userPhoneFull          = $userPhone;
                  //  $userPhoneFull= str_replace("-","",$userPhone);
//					if (strpos($userPhone, "05") === 0){
//					  $userPhoneFull          = '966'.ltrim($userPhone, '0');
//					}else{
//					  $userPhoneFull          = '91'.$userPhone;	
//					}					
                    $retVerify              = $ObjUser->saveMobileVerify($_POST);
                  //  $_POST['userPhone']     = $userPhone; 
                //    $userPhoneFull     = $_POST['userCountrycode'].$_POST['userPhone'];
                    
                    $userPhoneFul= str_replace("91-","",$_POST['userPhone']);
                    $userPhoneFull= '91'.$userPhoneFul;
                    //$userPhoneFull     ='91'.$_POST['userPhone'];
                    if($retVerify) {

                            $ObjSmsTemplate            = new SmstemplateModel();
			    $messageBody                    = $ObjSmsTemplate->getSmsTempDetails('', $language_ids,'sms_signup_otp');	
						//  sms body
			    $bodytag                = str_replace('(1)', $verify_code, $messageBody['smsTemplateContent']);
                            $msg = $smsTemplate['smsText'];
                            $msg = str_replace("#value",$verify_code,$msg);
                            $msg = str_replace("#exp",$timeout,$msg);
                            $msg=str_replace(" ","+",$msg);

                        $user_id=$this->getSettingValue('sms_settings', 'sms_username');
                        $password=$this->getSettingValue('sms_settings', 'sms_password');
                        $sms = new Sms($user_id, $password);
		        $result	=	$sms->setSms($bodytag,$userPhoneFull,'Normal');
                        $this->setMessage("language.lblCheckMobile", "message_success", '', 'common_message');
                        $this->ObjView->assign('verify_codes',""); 
                         $this->ObjView->assign('userPhone', $_POST['userPhoneVerify']);
                        //$this->ObjView->assign('verify_codes', $verify_code); 
                        $showTab='verify';
                    }                    
                } else if(isset($_POST['submitVerify'])){
				 $this->ObjCommon->setDynamicMenuPlugin($this->ObjView);
				$this->ObjView->display('account/AjaxLoginDetails.tpl');
                                exit;
}				
            }else {
                 $closePopup                 = 'Yes'; //24-02-15
            }
            $this->ObjView->assign('resListCountryCode', $resListCountryCode);
            $this->ObjView->assign('showTab', $showTab);
            $this->ObjView->assign('otpEnableRegistration', $otpEnableRegistration);
            $this->ObjView->assign('userPhone', $userPhone);
            $this->ObjView->assign('countryCode', $countryCode);
            $this->ObjView->assign('closePopup', $closePopup);
            $this->ObjView->assign('urlRedirect', $redirect);              
        echo json_encode($returnArray);
        exit;
        }
        public function verifyMobileAction()
		{
         
            $language_ids             = $this->ObjView->languageIDs;          
            $userID                   = $this->ObjSession->getSession("TEMP_USER_ID");
            $ObjUser                  = new UserModel();	          
            if($userID > 0) { 
               
                    $timeout  = $this->getSettingValue('sms_settings', 'otp_expire_time');
                    $_POST['verify_code']   = $verify_code = $this->randomString(4);
                    $_POST['userID']        = $userID; 
                    $_POST['send_date']     = 'NOW';
                  //  $_POST['userPhone'] = ltrim($_POST['userPhone'], '0');
                      $userPhoneVal             = $ObjUser->getUserPhone($userID);
                 
                       $userPhoneFul= str_replace("91-","",$userPhoneVal);
                       $userPhoneFull= '91'.$userPhoneFul;

//                    if($_POST['userCountrycode']){
//                    $userPhoneFull     = $_POST['userCountrycode'].$_POST['userPhone'];
//                    }else{
//                        $userPhoneFull     = '91'.$_POST['userPhone'];
//                    }
                    $retVerify              = $ObjUser->saveMobileVerify($_POST);
                    if($retVerify) {
		  
                        $user_id=$this->getSettingValue('sms_settings', 'sms_username');
                        $password=$this->getSettingValue('sms_settings', 'sms_password');
                        $ApiUrl=$this->getSettingValue('sms_settings','api_url');
                        $senderID=$this->getSettingValue('sms_settings','sms_sender_id');
                        $exp_minutes=$this->getSettingValue('sms_settings','otp_expire_time');
                      
                        if(trim($user_id) && trim($password))
                        {
                            $ObjSmsTemplate                = new SmstemplateModel();
			    $messageBody                    = $ObjSmsTemplate->getSmsTempDetails('', $language_ids,'sms_signup_otp');	
						//  sms body
		   	    $bodytag                = str_replace('(1)', $verify_code, $messageBody['smsTemplateContent']);
                            $msg = $smsTemplate['smsTemplateContent'];
                            $msg = str_replace("#value",$verify_code,$msg);
                            $msg = str_replace("#exp",$timeout,$msg);
                            $msg=str_replace(" ","+",$msg);   
                            $sms         =       new Sms($user_id, $password);
                           
		            $result	=	$sms->setSms($bodytag,$userPhoneFull,'Normal');
                           
                        }                        
                        $this->setMessage("language.lblCheckMobile", "message_success", '', 'common_message');
                        $this->ObjView->assign('verify_codes',""); 
                        $showTab='verify';
			$this->ObjView->assign('userID', $userID);   
                    }                    
                } 	
			}
    public function checkUserPhoneExist() {
         $userID                   = $this->ObjSession->getSession("TEMP_USER_ID");
        $ObjUser                  = new UserModel();
        if ($ObjUser->checkUserPhoneExist($_POST['userPhoneVerify'], $userID)) {
            return false;
        } else {
            return true;
        }
    }	
     //Checkout Login
    public function ajaxCheckoutLoginAction() {
       
        
        //redirect URL
        $reUrl          = (isset($_GET['reurl'])) ? trim($_GET['reurl']) : '';
        //Login Section
        $loginParams   = array(
            "ajaxRequest" => "0"
        );
        $validateLogin = $this->loginProcess($loginParams);
        if ($validateLogin['formSubmitted'] == "1") {
            $validateLogin['redirectUrl'] = $reUrl;
            echo json_encode($validateLogin);
            exit;
        }
         echo json_encode($validateLogin);
            exit;
        
    }
     //Signup Process
    public function signupProcessCheckout($params = array()) {
        $isAjax                       = true; //For Handling AJAX and Direct page Request
        $isFacebook                   = false;
        $isSignup                     = 'signup';
        $facebookUserData             = array();
        $returnArray['error']         = 'No';
        $returnArray['errorMessage']  = '';
        $returnArray['formSubmitted'] = 0;
        
        if (!empty($params)) {
            if (isset($params['ajaxRequest']) && $params['ajaxRequest'] == "0") {
                $isAjax = false;
            }
            //For Facebook Login
            if (isset($params['isFacebook']) && $params['isFacebook'] == "1") {
                $isFacebook = true;
            }
            //For Facebook
            if (!empty($params['facebookUserData'])) {
                $facebookUserData = $params['facebookUserData'];
            }
        }
        
        $ObjUser          = new UserModel();
        $ObjEmailtemplate = new EmailtemplateModel();
        $ObjCart          = new CartModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $siteName    = $this->getSettingValue('site_settings', 'site_name');
        $otpEnableRegistration      = $this->getSettingValue('sms_settings', 'enable_sms_otp');
	$otpEnableCheckout      = $this->getSettingValue('product_cart_settings', 'otp_enable_checkout');
	$this->ObjView->assign('otpEnableCheckout ', $otpEnableCheckout );
        $this->ObjView->assign('otpEnableRegistration ', $otpEnableRegistration );
        $this->ObjView->assign('isSignup ', $isSignup );
        if ($this->ObjForm->isValid('formLogin', 'submit', false) || $isFacebook) {
           
                $returnArray['userPhoneVerify'] = ltrim($_POST['userPhone'], '0');
                $returnArray['countryCodeVerify'] =$_POST['userCountrycode'];
                $_POST['userEmail'] = $_POST['userLoginEmail'];
                $_POST['userFirstName'] = $_POST['userName'];
                $_POST['userCountrycode'] = $_POST['userCountrycode'];
            if (isset($_POST['ajaxSubmit']) && $_POST['ajaxSubmit'] >0)
            {
                $isAjax = true;
            }
            //Form Submitted
            $returnArray['formSubmitted'] = 1;
            if (!$isFacebook) {
                $isValidEmail = $this->validateEmail($_POST['userEmail'], $isAjax);
                if ($isValidEmail['error'] == "Yes") {
                    $returnArray['error']        = 'Yes';
                    $returnArray['errorMessage'] = $isValidEmail['errorMessage'];
                    return $returnArray;
                }
                $_POST['userCurrentLanguage'] = $languageIDs['Current'];
                $_POST['userDefaultLanguage'] = $languageIDs['Current'];
                $_POST['userStatus'] = 'Inactive';//Inactive;//CHNAGE ON NXT COMMIT
                $_POST['userSourceOfReg']  =  $this->ObjCommon->_platform;
                $user                         = $ObjUser->saveUserDetails($_POST, '');
			 
				   if ($user) {
				  if($_POST['checkoutLogin']!='' && $otpEnableCheckout == 'Yes'){
                              
				    $this->ObjSession->setSession("TEMP_USER_ID", $user);
					 $this->ObjSession->setSession("TEMP_USER_PASSWORD", $_POST['userPassword']);
					 $this->verifyMobileAction();
                                         return $returnArray;
					}else{
					  $this->signupProcessComplete($user,'',$isSignup);			
					}
				   }
            } else //Facebook
                {
                    $user = $ObjUser->saveFbUserDetails($facebookUserData);
                    $resUserDetails = $ObjUser->getBasicUserDetails($user, array(
                        "userID",
                        "userGroupID",
                        "userFirstName",
                        "userLastName",
                        "userPhoneCountryID",
                        "userPhone",
                        "userEmail",
                        "userStatus",
                        "userDefaultLanguage"
                    ));

                    $this->ObjSession->setSession("TEMP_USER_ID", $user);
                    $returnArray['error']='Yes';
                    $returnArray['isverify']='No';
                    return $returnArray;
               //$this->signupProcessComplete($user);
            }
           if (!$user) {
                if (!$isFacebook) {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errLoginExists");
                } else //Facebook
                    {
                    $returnArray['errorMessage'] = $this->getLanguageValue("errorSignup");
                }
                $returnArray['error'] = 'Yes';
                return $returnArray;
            }
        }else{
              $validateResult =   $this->ObjForm->ObjValidate->ValidateResult;
              if(count($validateResult['formLogin'])>0){
                    $returnArray['error']='Yes';
                    $returnArray['errorMessage'] = $validateResult['formLogin']['userPassword']['error'];
                    $returnArray['passwordErrorMessage'] = $validateResult['formLogin']['userPassword']['error'];
              }
              

        }
        return $returnArray;
    } 
    public function ajaxCheckUserPhoneExistAction() {
        $ObjUser                  = new UserModel();
        $_POST['userPhone'] = ltrim($_POST['userPhone'], '0');
        echo $ObjUser->checkUserPhoneExist($_POST['userPhone']);
           exit;
    } 
     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;
  } 
 
}