Subversion Repositories SmartDukaan

Rev

Rev 17978 | Rev 18322 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 1
<?php
2
App::uses('AppController', 'Controller');
17345 naman 3
App::uses('ConnectionManager', 'Model');
13532 anikendra 4
/**
5
 * Users Controller
6
 *
7
 * @property User $User
8
 */
14408 anikendra 9
 
10
set_time_limit(0);
11
 
13532 anikendra 12
class UsersController extends AppController {
13
 
14395 anikendra 14
	public $components = array('SignMeUp.SignMeUp','RequestHandler','Cookie','Paginator');
13532 anikendra 15
 
16
    public function beforeFilter() {
17
    	parent::beforeFilter();
18
    	// $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
19
    	$this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'display','home');
15511 anikendra 20
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet','admin_push','socialauth','oneringcb')); 
13736 anikendra 21
		$this->Cookie->name = 'profittill';
22
		$this->Cookie->time = 86400*30; 
23
		$this->Cookie->path = '/';
24
		$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#H23s~#^';
25
		$this->Cookie->httpOnly = true;
13532 anikendra 26
    }
27
 
15511 anikendra 28
	public function oneringcb() {
29
		$this->log(print_r($_REQUEST,1),'onering');
15523 anikendra 30
		$this->layout = "ajax";
15767 anikendra 31
		$this->response->type('json');
32
		$this->set(array(
33
		    'result' => $result,
34
		    '_serialize' => array('result')
35
		)); 
36
		$this->render('/Elements/json');
13532 anikendra 37
	}
38
 
14019 anikendra 39
	public function mywallet() {
40
		$userId = $this->request->query('user_id');
15380 anikendra 41
		$tokenValidated = $this->checkToken($userId);
15651 anikendra 42
		if(isset($userId) && !empty($userId) && $tokenValidated==1){	
14441 anikendra 43
			$next = "/my-wallet";					
14150 anikendra 44
			$redirectUrl = $this->getAutoLoginUrl($userId,$next);
15380 anikendra 45
			$this->log($redirectUrl,'headers');
15247 anikendra 46
			$this->layout = 'innerpages';
47
			$this->set(compact('redirectUrl'));
14891 anikendra 48
		}else{
16308 anikendra 49
			if($tokenValidated == 0){
15651 anikendra 50
				$this->redirect(array('controller'=>'special','action'=>'native','login'));
51
			}elseif($tokenValidated == -1){
52
				$this->redirect(array('controller'=>'abouts','action'=>'askforupdate'));
16308 anikendra 53
			}
14019 anikendra 54
		}
55
	}
56
 
14825 anikendra 57
	public function socialauth() {
58
		$this->layout = "ajax";
59
		$this->log(print_r($this->request->data,1),'socialauth');
60
	}
61
 
13740 anikendra 62
	public function mine() {
13758 anikendra 63
		$this->response->type('json');
64
		$this->layout = 'ajax';
13740 anikendra 65
		$userId = $this->request->query('user_id');
66
		if(isset($userId) && !empty($userId)){
67
			$this->loadModel('User');
13758 anikendra 68
			$options = array('conditions'=>array('User.id'=>$userId),'fields'=>array('username','email','first_name','profile_pic','mobile_number','mobile_verified','address_line_1','address_line_2',
69
				'city','state','pincode','referrer'),'recursive'=>-1);
13763 anikendra 70
			$user = $this->User->find('first',$options);
71
			$result = $user['User'];
13740 anikendra 72
		}
13758 anikendra 73
		$this->set(array(
74
		    'result' => $result,
75
		    '_serialize' => array('result')
76
		)); 
77
		$this->render('/Elements/json'); 
13740 anikendra 78
	}
79
 
13532 anikendra 80
	function registertwitteruser(){
81
		$this->twitterObj->setToken($_GET['oauth_token']);
82
		$token = $this->twitterObj->getAccessToken();
83
		$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
84
		$twitterInfo= $this->twitterObj->get_accountVerify_credentials();
85
		$data = array();
86
		$data['twitter_id'] = $twitterInfo->id;		
87
		$this->Session->write('twtusername',$twitterInfo->screen_name);
88
		$data['twitter_token'] = $token->oauth_token;
89
		$data['twitter_secret'] = $token->oauth_token_secret;
90
		$data['twitter_screen_name'] = $twitterInfo->screen_name;					
91
		$data['active'] = 1;
92
 
93
		$id = $this->Auth->user('id');
94
		if(!isset($id) || $id == ''){
95
		//	$count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
96
			$user = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
97
			//if($count<1){
98
			if(empty($user)){
99
				$this->User->create();
100
				$this->User->save($data);
101
//				$dbuser = $this->User->read(null,$this->User->id);
102
				$this->Auth->login($this->User->data);
103
			}else{
104
		//		$data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
105
				$this->Auth->login($user['User']);
106
			}
107
		}else{
108
			//$data['id'] = $this->Auth->user('id');
109
			$user = $this->Auth->user;
110
//			$this->User->save($data);
111
//			$this->Auth->login($data);
112
		}                
113
		$user = $this->User->read(null, $this->Auth->User('id'));
114
		if ($user['User']['group_id'] == 1) {
115
			//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
116
			header('location:users/dashboard?userid='.$this->Auth->user('id'));
117
			exit();
118
		}
119
		elseif ($user['User']['group_id'] == 2) {
120
			$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
121
			exit();
122
		}
123
	}
124
 
125
    public function checkfbuser($accessToken=null){
126
		$sessionState = $this->Session->read('state');
127
		if($sessionState != $_GET['state']) {
128
			$this->redirect(array('controller'=>'users','action'=>'login'));
129
		}
130
		else {
131
			if(isset($_GET['code'])){
132
				$code = $_GET['code'];
133
				$facebookConfig = Configure::read("Facebook");		
134
				$token_url = "https://graph.facebook.com/oauth/access_token?"
135
			       . "client_id=" . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/')
136
			       . "&client_secret=" . $facebookConfig['secret'] . "&code=" . $code;
137
 
138
			    $response = file_get_contents($token_url);
139
			    $params = null;
140
			    parse_str($response, $params);
141
			    $accessToken = $params['access_token'];
142
			}else{
143
				$this->redirect(array('controller'=>'users','action'=>'login'));
144
			}
145
		}
146
		$this->User->recursive = -1;
147
		if (!$accessToken) {
148
		    $this->redirect(array('controller'=>'users','action'=>'login'));
149
		    //$this->redirect(array('controller'=>'pages','action'=>'display','home'));
150
		}        
151
		if (isset($accessToken) && $accessToken != 'undefined') {			
152
 
153
		    $graph_url = "https://graph.facebook.com/me?access_token=" . $accessToken;
154
 
155
		    $user = json_decode(file_get_contents($graph_url));
156
			$this->log("FB user = ".print_r($user,1),'fb');
157
		    if (!empty($user)) {
158
			if (!$this->isAuthorized()) {
159
			    $id = $this->User->checkFbUser($user,$accessToken);
160
				$dbuser = $this->User->findById($id);
161
			    $this->Session->write('facebook_id',$user->id);
162
				$this->Auth->login($dbuser['User']);
163
				if($this->Auth->login()){
164
					$this->log("logged = ".print_r($this->Auth->user('id'),1)."\n",'fb');
165
				}
166
			    $next = $this->Session->read('next');
167
				$this->log("next= ".$next."\n",'fb');
168
 
169
			    if (!empty($next)) {
170
					header('Location:' . $next);
171
					exit();
172
			    }else {
173
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
174
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
175
					exit();
176
			            }
177
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
178
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
179
					exit();
180
				} else {                	
181
					//$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
182
					header('location:users/dashboard?userid='.$this->Auth->user('id'));
183
					exit();
184
				}
185
		    }
186
		}
187
    }
188
 
189
	public function uploadavatar(){
190
		$this->log(print_r($_FILES,1),'debug');
191
		$path = "img/avatars/";
192
		$valid_formats = array("jpg", "png", "gif", "bmp");
193
		if ($this->request->is('post')) {
194
			$name = $_FILES['photoimg']['name'];
195
			$size = $_FILES['photoimg']['size'];
196
 
197
			if(strlen($name))
198
				{
199
					list($txt, $ext) = explode(".", $name);
200
					if(in_array($ext,$valid_formats))
201
					{
202
					if($size<(1024*1024))
203
						{
204
							$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
205
							$tmp = $_FILES['photoimg']['tmp_name'];
206
							if(move_uploaded_file($tmp, $path.$actual_image_name))
207
								{
208
									echo "<img width='250' src='../".$path.$actual_image_name."'  class='preview'>";
209
									echo "<input type='hidden' id='imageUrl' name='photo_url' value='".'http://' . $_SERVER['SERVER_NAME'] . Router::url('/').$path.$actual_image_name."'></input>";
210
								}
211
							else
212
								echo __('Upload Failed');
213
						}
214
						else
215
						echo __("Maximum allowed image file size is 1 MB");					
216
						}
217
						else
218
						echo __("Invalid file format");	
219
				}
220
			else
221
				echo __("Please select image");
222
			exit;
223
		}
224
	}
225
 
226
    function checkemail() {
227
        $this->User->recursive = -1;
228
        $this->layout = 'ajax';
229
        if (!empty($this->params['url']['data']['User']['email'])) {
230
            $username = $this->params['url']['data']['User']['email'];
231
        } elseif (!empty($this->params['url']['data']['Doctor']['email'])) {
232
            $username = $this->params['url']['data']['Doctor']['email'];
233
        } else {
234
            $result = false;
235
            $this->set('result', $result);
236
        }
237
        if ($this->Auth->user('id') != null) {
238
            $conditions = array('User.email' => $username, 'User.id !=' => $this->Auth->user('id'));
239
        } else {
240
            $conditions = array('User.email' => $username);
241
        }
242
        $count = $this->User->find('count', array('conditions' => $conditions));
243
        if ($count > 0) {
244
            $result = false;
245
        } else {
246
            $result = true;
247
        }
248
        $this->set('result', $result);
249
    }
250
 
251
/**
252
 * view method
253
 *
254
 * @throws NotFoundException
255
 * @param string $id
256
 * @return void
257
 */
258
	public function view($id = null) {
259
		$this->response->type('json');
260
		$this->layout = 'ajax';
261
		$callback = $this->request->query('callback');
262
		$this->User->id = $id;
263
		if (!$this->User->exists()) {
264
			throw new NotFoundException(__('Invalid user'));
265
		}
266
		$user = $this->User->find('first', array('conditions' =>array('id' => $id),'recursive'=>-1));
267
		$result = array('user'=>$user);
268
		$this->set(array(
269
		    'result' => $result,
270
		    'callback' => $callback,
271
		    '_serialize' => array('result')
272
		));
13736 anikendra 273
		$this->render('/Elements/json');
13532 anikendra 274
	}
275
/**
276
 * edit method
277
 *
278
 * @throws NotFoundException
279
 * @param string $id
280
 * @return void
281
 */
282
 
13736 anikendra 283
    public function edit($id = null) {
14770 anikendra 284
		$this->log(print_r($this->request->data,1),'mydetails');
285
		$this->response->type('json');
286
		$this->layout = 'ajax';
287
		$this->User->recursive = -1;
288
		$updateRequired = true;
13736 anikendra 289
        if (!$this->User->exists($id)) {
14300 anikendra 290
			$result = array('success'=>false,'message'=>'Invalid user');
13736 anikendra 291
		} else {
292
	        if ($this->request->is('post') || $this->request->is('put')) {
14768 anikendra 293
           		if(!empty($this->request->data['mobile_number']) && empty($this->request->data['mobile_verified'])) {
294
					$options = array('conditions'=>array('User.id'=>$id),'fields'=>array('mobile_number'),'recursive'=>-1);
295
					$oldMobile = $this->User->find('first',$options);
296
					if($this->request->data['mobile_number'] != $oldMobile['User']['mobile_number']) {
14316 anikendra 297
		        		$this->request->data['mobile_verified'] = 0;
14768 anikendra 298
					}
14300 anikendra 299
	        	}
14770 anikendra 300
	        	if(!empty($this->request->data['referrer'])) {
14768 anikendra 301
	        		$referrer = $this->request->data['referrer'];
14787 anikendra 302
	        		$this->log(print_r($referrer,1),'activations');
14768 anikendra 303
	        		$this->loadModel('ActivationCode');
14785 anikendra 304
	        		$exists = $this->ActivationCode->findByCode(strtoupper($referrer));
14787 anikendra 305
	        		$this->log(print_r($exists,1),'activations');
14768 anikendra 306
	        		if(empty($exists)){
307
	        			$result = array('success'=>false,'message'=>'Invalid referral code');
15085 anikendra 308
	        			// unset($this->request->data['referrer']);
14770 anikendra 309
	        			$updateRequired = false;
15477 anikendra 310
	        		} else {
311
	        			$this->request->data['activated'] = 1;        		
312
	        		}		        		
14768 anikendra 313
	        	}	        		
14770 anikendra 314
	        	if($updateRequired){
315
		            if ($this->User->save($this->request->data)) {
15475 anikendra 316
		            	if($this->request->data['activated'] == 1) {
317
		            		//Call user activation api
318
		        			$this->markUserActivated($id);
319
		            	}			        		
14770 anikendra 320
		                $result = array('success'=>true,'message'=>'Your profile has been saved');
321
		            } else {
322
		                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
323
		            }
324
		        }
13736 anikendra 325
	        }  
326
	    }
327
        $this->set(array(
328
		    'result' => $result,
329
		    '_serialize' => array('result')
330
		)); 
331
		$this->render('/Elements/json');      
13532 anikendra 332
    }
333
 
334
/**
335
 * admin_index method
336
 *
337
 * @return void
338
 */
14408 anikendra 339
 
340
	public function admin_pushnotifications(){
341
		if ($this->request->is('post')) {
342
			$sql = $this->request->data['User']['sql'];
343
			if(!empty($sql)){
344
				$users = $this->User->query($sql);
345
				$this->set(compact('users'));
346
			}
347
		}
348
	}
349
 
14445 anikendra 350
	public function generateAffiliateUrl($url,$user_id,$store){
351
		//Get StoreProduct Info		
14428 anikendra 352
		$storeId = $store['Store']['id'];
353
		$prefix = "SHA".$storeId;
354
		$tag = $prefix.time();
355
		if($storeId == 2){				
356
			$url = str_replace('www','m',$url);
357
		} elseif($storeId == 3) {
358
			$url_parts = parse_url($url);
359
			$url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
360
			if(isset($url_parts['query'])) {
361
				$url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
362
			}else{
363
				$url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
364
			}
365
		} elseif($storeId == 4){
14445 anikendra 366
			$next = str_replace('www','m',$url);	
14428 anikendra 367
			$url = $this->getAutoLoginUrl($userId,$next);
368
			$url .= '?utm_source=profitmandi';
369
		}
370
		if( strpos($url, '?') === false ) {
371
			$firstChar = '?';
372
		} else {
373
			$firstChar = '&';
374
		}
375
		$url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
376
		if(!empty($store['Store']['sub_tag_param'])){
377
			$url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
378
		}
379
		$extras = array('store'=>$store['Store']['name'],'source'=>'notification');
380
		$data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
381
		$this->loadModel('Click');
382
		$this->Click->create();
383
		$this->Click->save($data);
384
		return $url;
385
	}
386
 
14408 anikendra 387
	public function admin_push(){
388
		if ($this->request->is('post')) {
389
			if(empty($this->request->data['userIds'])){
390
				$this->Session->setFlash(__('Please choose a few users'));
391
				$this->redirect(array('action' => 'admin_pushnotifications'));
392
			}else{
14824 anikendra 393
				$this->log(print_r($this->request->data,1),'pushnotifications');
14445 anikendra 394
				$message = $this->request->data['User'];
14776 anikendra 395
				$this->loadModel('NotificationCampaign');
396
				$this->NotificationCampaign->create();
17349 manish.sha 397
				$data = array('name'=>$message['name'],'title'=>$message['title'],'type'=>$message['type'],'message'=>$message['message'],'url'=>$message['url'],'expiresat'=>$message['expiresat'], 'sendsms'=>$message['sendsms'], 'messagetext'=>$message['messagetext']);
14776 anikendra 398
				if($this->NotificationCampaign->save($data)){
399
					$message['cid'] = $this->NotificationCampaign->getLastInsertId();
400
				} else{
401
					$message['cid'] = $message['name'];
402
				}
17232 anikendra 403
				/*				
14445 anikendra 404
				if($message['type'] == 'url' && !empty($message['url'])) {
405
					$url = $message['url'];
406
					$this->loadModel('Store');
407
					$store = $this->Store->getByUrl($url);					
17232 anikendra 408
					$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14445 anikendra 409
				}				
14408 anikendra 410
				$this->loadModel('GcmUser');
411
				foreach ($this->request->data['userIds'] as $key => $value) {					
14770 anikendra 412
					$options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
14408 anikendra 413
					$gcmUser = $this->GcmUser->find('first',$options);
414
					$regIds = array($gcmUser['GcmUser']['gcm_regid']);
14445 anikendra 415
					// $message = array('message'=>$this->request->data['User']['message']);					
416
					if($message['type'] == 'url' && !empty($message['url'])) {
417
						$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14428 anikendra 418
					}					
419
					$this->send_push_notification($regIds,$message,$value);
14408 anikendra 420
				}
17232 anikendra 421
				*/
422
				$sentUsers = array();
423
				$payload = array();
424
				foreach ($this->request->data['userIds'] as $key => $value) {	
425
					if(!in_array($value, $sentUsers)) {
426
						$sentUsers[] = $value;								
17349 manish.sha 427
						$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$value,'type'=>'pending','status'=>0);						
17232 anikendra 428
						$payload[] = $data;
429
					}
430
				}
431
				$url = Configure::read('nodeurl')."/addPushNotification";
432
				$this->make_request($url,json_encode($payload,JSON_NUMERIC_CHECK));
14408 anikendra 433
			}
434
		}
435
	}
17232 anikendra 436
 
15414 manas 437
	private function send_push_notification($registatoin_ids, $message, $user_id) {
438
                $msg = array(
439
                    'message'       => $message['message'],
440
                    'cid'               => $message['cid'],
441
                    'title'         => $message['title'],
442
                    'type'              => $message['type'],
443
                    'url'                   => $message['url'],
444
                    // 'expiresat'          => strtotime($message['expiresat']),
445
                    'vibrate'       => 1,
446
                    'sound'         => 1,
447
                    'largeIcon'     => 'large_icon',
448
                    'smallIcon'     => 'small_icon'
449
                );
450
                // Set POST variables
451
                $url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 452
 
15414 manas 453
                $fields = array(
454
                    'registration_ids' => $registatoin_ids,
455
                    'data' => $msg,
456
                );
457
                $headers = array(
458
                    'Authorization: key=' . Configure::read('googleapikey'),
459
                    'Content-Type: application/json'
460
                );
461
                //print_r($headers);
462
                // Open connection
463
                $ch = curl_init();
464
 
465
                // Set the url, number of POST vars, POST data
466
                curl_setopt($ch, CURLOPT_URL, $url);
467
                curl_setopt($ch, CURLOPT_POST, true);
468
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
469
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
470
 
471
                // Disabling SSL Certificate support temporarly
472
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
473
 
474
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
475
 
476
                // Execute post
477
                $result = curl_exec($ch);
478
                if ($result === FALSE) {
479
                    die('Curl failed: ' . curl_error($ch));
480
                }
481
                $res = json_decode($result,1);
482
 
483
                $this->loadModel('Pushnotification');
484
                if($res['success']==1){
485
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>'success');
486
				}else if($res['success']==0){
487
					$error_message=$res['results'][0]['error'];
488
					$sqlQuery="update gcm_users set failurecount=failurecount+1 where gcm_regid='".$registatoin_ids[0]."'";
489
					$resultData=$this->GcmUser->query($sqlQuery);
490
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>$error_message);
491
				}
492
                #$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
493
                $this->Pushnotification->create();
494
                $this->Pushnotification->save($data);
495
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($data,1),'pushnotifications');
496
                // Close connection
497
                curl_close($ch);
498
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
499
        }
500
 
15761 manas 501
	public function admin_index() {
13532 anikendra 502
		$this->User->recursive = 0;
15767 anikendra 503
		$options = array('limit'=>20,'order'=>array('id'=>'desc'));
14395 anikendra 504
		$this->Paginator->settings = $options;
505
		$users = $this->Paginator->paginate();
15761 manas 506
 
13532 anikendra 507
		$groups = $this->User->Group->find('list');
15761 manas 508
 
509
		$postOfficeQuery="select pincode,state from postoffices group by pincode";
510
		$postOfficeResult=$this->User->query($postOfficeQuery);
511
		$postOffice=array();
512
		foreach($postOfficeResult as $value){
513
			$postOffice[$value['postoffices']['pincode']]=$value['postoffices']['state'];
514
		}
515
		foreach ($users as $key => $value) {
516
	$userId=$value['User']['id'];
15815 anikendra 517
	$masterQuery="select u.id,rl.retailer_id,r.state,r.city,r.pin,
15762 manas 518
					ra.state,ra.city,ra.pin,
519
					u.state,u.city,u.pincode,
520
					ua.state,ua.city,ua.pincode 
521
					from retailers r left  join retaileraddresses ra  on r.id=ra.retailer_id  
522
					join retailerlinks rl on r.id=rl.retailer_id 
523
					right join users u on rl.user_id=u.id 
16549 anikendra 524
					left join user_addresses ua on u.id=ua.user_id 
15762 manas 525
					where u.id=$userId";
526
	$retailerAddress=$this->User->query($masterQuery);
15815 anikendra 527
	$users[$key]['User']['retailer_id']=$retailerAddress[0]['rl']['retailer_id'];	
15762 manas 528
	if($retailerAddress[0]['ra']['city']==null && $retailerAddress[0]['ra']['state']==null && $retailerAddress[0]['ra']['pin']==null){
529
		if($retailerAddress[0]['r']['city']==null && $retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']==null){
530
			if($retailerAddress[0]['ua']['city']==null && $retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']==null){
531
				if($retailerAddress[0]['u']['city']==null && $retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']==null){
532
 
15761 manas 533
				}else{
15762 manas 534
					if($retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']!=null){
535
						$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['u']['pincode']];		
536
					}else{
537
						$users[$key]['User']['state']=$retailerAddress[0]['u']['state'];	
538
						$users[$key]['User']['city']=$retailerAddress[0]['u']['city'];	
15761 manas 539
				}	
15762 manas 540
 
541
				}
15761 manas 542
			}
543
			else{
15762 manas 544
				if($retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']!=null){
545
					$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pincode']];		
15761 manas 546
				}else{
15762 manas 547
					$users[$key]['User']['state']=$retailerAddress[0]['ua']['state'];	
548
					$users[$key]['User']['city']=$retailerAddress[0]['ua']['city'];	
549
				}	
15761 manas 550
			}
551
		}
552
		else{
15762 manas 553
			if($retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']!=null){
554
				$users[$key]['User']['city']=$retailerAddress[0]['r']['city'];	
555
				$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];		
15761 manas 556
			}else{
15762 manas 557
				$users[$key]['User']['state']=$retailerAddress[0]['r']['state'];	
558
				$users[$key]['User']['city']=$retailerAddress[0]['r']['city'];	
559
			}		
15761 manas 560
		}
561
	}else{
15762 manas 562
		if(($retailerAddress[0]['ra']['state']==null || empty($retailerAddress[0]['ra']['state'])) && $retailerAddress[0]['ra']['pin']!=null){
563
			$users[$key]['User']['city']=$retailerAddress[0]['ra']['city'];	
564
			$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];		
15761 manas 565
		}else{
15762 manas 566
			$users[$key]['User']['state']=$retailerAddress[0]['ra']['state'];	
567
			$users[$key]['User']['city']=$retailerAddress[0]['ra']['city'];	
568
		}		
13532 anikendra 569
	}
15761 manas 570
}
15762 manas 571
 
15761 manas 572
	$this->set(compact('groups','users'));	
573
}
574
 
13532 anikendra 575
/**
576
 * admin_view method
577
 *
578
 * @throws NotFoundException
579
 * @param string $id
580
 * @return void
581
 */
582
	public function admin_view($id = null) {
583
		$this->User->id = $id;
584
		if (!$this->User->exists()) {
585
			throw new NotFoundException(__('Invalid user'));
586
		}
587
		$this->set('user', $this->User->read(null, $id));
588
	}
589
 
590
/**
591
 * admin_add method
592
 *
593
 * @return void
594
 */
595
	public function admin_add() {
596
		if ($this->request->is('post')) {
597
			$this->User->create();
598
			if ($this->User->save($this->request->data)) {
599
				$this->Session->setFlash(__('The user has been saved'));
600
				$this->redirect(array('action' => 'index'));
601
			} else {
602
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
603
			}
604
		}
605
		$groups = $this->User->Group->find('list');
606
		$this->set(compact('groups'));
607
	}
608
 
609
/**
610
 * admin_edit method
611
 *
612
 * @throws NotFoundException
613
 * @param string $id
614
 * @return void
615
 */
616
	public function admin_edit($id = null) {
617
		$this->User->id = $id;
618
		if (!$this->User->exists()) {
619
			throw new NotFoundException(__('Invalid user'));
620
		}
621
		if ($this->request->is('post') || $this->request->is('put')) {
622
			if ($this->User->save($this->request->data)) {
623
				$this->Session->setFlash(__('The user has been saved'));
624
				$this->redirect(array('action' => 'index'));
625
			} else {
626
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
627
			}
628
		} else {
629
			$this->request->data = $this->User->read(null, $id);
630
		}
631
		$groups = $this->User->Group->find('list');
632
		$this->set(compact('groups'));
633
	}
634
 
635
/**
636
 * admin_delete method
637
 *
638
 * @throws MethodNotAllowedException
639
 * @throws NotFoundException
640
 * @param string $id
641
 * @return void
642
 */
15217 anikendra 643
/*
13532 anikendra 644
	public function admin_delete($id = null) {
645
		if (!$this->request->is('post')) {
646
			throw new MethodNotAllowedException();
647
		}
648
		$this->User->id = $id;
649
		if (!$this->User->exists()) {
650
			throw new NotFoundException(__('Invalid user'));
651
		}
652
		if ($this->User->delete()) {
653
			$this->Session->setFlash(__('User deleted'));
654
			$this->redirect(array('action' => 'index'));
655
		}
656
		$this->Session->setFlash(__('User was not deleted'));
657
		$this->redirect(array('action' => 'index'));
658
	}
15217 anikendra 659
*/
13532 anikendra 660
 
15217 anikendra 661
	public function admin_search() {
662
		$type = $this->request->query('type');
663
		$search = $this->request->query('search');
664
		$this->User->recursive = -1;
665
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
15232 anikendra 666
		if($type == 'unactivated'){
667
			$options['conditions'] = array('activated' =>0);
668
		}
669
		else if(!empty($type) && !empty($search)){
16465 anikendra 670
			if($type=='id'){
671
				$options['conditions'] = array($type =>$search);			
672
			}else{
673
				$options['conditions'] = array($type.' LIKE '=>"%$search%");			
674
			}
15232 anikendra 675
		}else{
17210 anikendra 676
			$options['conditions'] = array('date(User.created)'=>date('Y-m-d',time()));			
16465 anikendra 677
		}	
17345 naman 678
		// $db = ConnectionManager::getDataSource("default"); // name of your database connection
679
		// $last_act = $db->fetchAll("SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ");
680
		$sql = "SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ";
681
		$last_act = $this->User->query($sql);
682
		// debug($last_act);
683
		$last_act_user_id = array();
684
		$last_activated = array();
685
		foreach ($last_act as $key => $row) {
686
			// echo $key;
687
			foreach ($row as $key => $value) {
688
				$last_activated['visited'] = $value['visited'];
689
				$last_act_user_id[$value['user_id']] = $last_activated['visited'];
690
			}
691
		}
692
		// debug($last_act_user_id);
693
		$this->set(compact('last_act_user_id'));
694
		$options['fields'] = array('id','email','first_name','referrer','utm_source','utm_medium','utm_term','utm_campaign','mobile_number','activated','User.created','Appacl.access');
16465 anikendra 695
		$options['joins'] = array(
17345 naman 696
		    /*array('table' => 'useractive',
16465 anikendra 697
		        'alias' => 'Useractive',
698
		        'type' => 'LEFT',
699
		        'conditions' => array(
700
		            'Useractive.user_id = User.id',
701
		        )
17345 naman 702
		    ),*/
16925 anikendra 703
		    array('table' => 'appacls',
704
		        'alias' => 'Appacl',
705
		        'type' => 'LEFT',
706
		        'conditions' => array(
707
		            'Appacl.user_id = User.id',
708
		        )
16465 anikendra 709
		    )
710
	    );
15232 anikendra 711
		$this->Paginator->settings = $options;
712
		$users = $this->Paginator->paginate();		
16256 manas 713
		foreach ($users as $key => $value) {
714
			$userId = $value['User']['id'];
715
			$quer= "select r.retailer_id,a.name from retailerlinks r join agents a on r.agent_id=a.id where user_id=$userId";
716
			$res = $this->User->query($quer);
16449 manas 717
			/*$last_act= "select last_active from useractive where user_id=$userId";
718
			$res_last = $this->User->query($last_act);*/
16256 manas 719
			if(empty($res)){
720
				$users[$key]['User']['retailer_id']="";	
721
				$users[$key]['User']['agent_name']="";	
722
			}else{
723
				$users[$key]['User']['retailer_id']=$res[0]['r']['retailer_id'];	
724
				$users[$key]['User']['agent_name']=$res[0]['a']['name'];	
725
			}
16449 manas 726
			/*if(empty($res_last)){
16448 manas 727
				$users[$key]['User']['last_active']="";
728
			}else{
729
				$users[$key]['User']['last_active']=$res_last[0]['useractive']['last_active'];
16449 manas 730
			}*/
16256 manas 731
 
732
		}
733
 
15380 anikendra 734
		$this->set(compact('users'));	
15217 anikendra 735
	}
736
 
13532 anikendra 737
	public function dashboard() {
738
		App::uses('CakeTime', 'Utility');
739
		$user = $this->User->read(null,$this->Auth->user('id'));
740
		$this->set('user',$user);
741
		$this->set('title_for_layout', "Dashboard");
742
	}
743
 
744
/**
745
* user authentication funtions
746
*/
747
	public function register() {
748
		$referrer = $this->request->query('referrer');
749
		$this->log('referrer = '.$referrer);
750
		$this->Cookie->write('referrer',$referrer);
751
		$this->layout = 'auth';
752
		$this->set('title_for_layout','Register your free letushaggle.com account');
753
		$this->SignMeUp->register();
754
	}
755
 
756
	public function activate() {
13714 anikendra 757
		$this->layout = 'auth';
13532 anikendra 758
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 759
		$this->SignMeUp->activate();
13532 anikendra 760
	}
761
 
762
	public function forgotten_password() {
13714 anikendra 763
		$this->layout = 'auth';
13532 anikendra 764
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 765
		$this->SignMeUp->forgottenPassword();
13532 anikendra 766
	}	
767
 
768
	public function login() {
17345 naman 769
		// $db = ConnectionManager::getDataSource("default"); // name of your database connection
770
		// $rest = $db->fetchAll("SELECT * from (SELECT * from daily_visitors order by visited desc) as x where x.user_id in (33, 47,2) group by x.user_id ");
771
		// debug($rest);
772
 
13532 anikendra 773
		$this->layout = 'auth';
774
		if (!empty($this->data['User']['next'])) {
775
		    $next = $this->data['User']['next'];
776
		    $this->Session->write('next', $next);
777
		} elseif (!empty($this->params['url']['next'])) {
778
		    $next = $this->params['url']['next'];
779
		    $this->Session->write('next', $next);
780
		}
781
		if ($this->Auth->login()) {
17345 naman 782
 
13532 anikendra 783
		    $next = $this->Session->read('next');
784
		    if (!empty($next)) {
785
				header('location:' . $next);
786
				exit();
787
		    }
17345 naman 788
		    $user = $this->User->read(null, $this->Auth->User('id'));		
789
		    // debug($user['User']['group_id']);
790
		 //    session_start();
791
		 //    $_SESSION["group_id"] = $user['User']['group_id'];
792
 
793
		 //    $this->loadModel('Acl');
794
			// $resul = $this->Acl->find('all', array('conditions' => array('group_id' => $_SESSION["group_id"]),'fields'=>('action')));
795
			// $_SESSION["permitted_action"] = $resul;
796
 
797
			// debug($_SESSION["permitted_action"]);
798
		    // echo $_SESSION["group_id"];
13532 anikendra 799
			if ($user['User']['group_id'] == 1) {
13736 anikendra 800
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 801
				exit();
802
			}
15188 anikendra 803
			else if ($user['User']['group_id'] >= 2) {
804
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
805
				exit();
806
		    }
13532 anikendra 807
		} else {
808
		    if (!empty($this->data)) {                
13736 anikendra 809
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 810
		    }
811
		}
812
		$this->set('title_for_layout', "Login to letushaggle.com");
813
	}
814
 
815
	public function logout() {
17345 naman 816
		// session_unset("group_id"); 
817
		// session_unset("permitted_action");
818
		// session_destroy("");
819
		// echo "Group Id" , $_SESSION["group_id"];
13532 anikendra 820
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
821
		$this->redirect($this->Auth->logout());
822
	}
823
 
824
	public function updatetimezone() {
825
		$this->layout = 'ajax';		
826
		$timezone = $_GET['tz'];
827
		Configure::load('constant');
828
		$timeZones = Configure::read("timeZones");
829
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
830
		if($this->User->query($query)){
831
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
832
		}else{
833
			$result = array('success' => false);
834
		}
835
		$this->set('result',$result);
836
	}
837
 
13736 anikendra 838
	public function verifymobile() {
839
		$this->layout = 'innerpages';
840
	}
13532 anikendra 841
 
13736 anikendra 842
	public function getdial2verifynumber() {
843
		$TelNumber=substr($this->request->data("phone_number"),-10);
844
 
845
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
846
	    $API_KEY = Configure::read("dial2verifyapikey");
847
 
848
	  	//Get API Image Response
849
	    $url ="http://engine.dial2verify.in/Integ/API.dvf?mobile=$TelNumber&passkey=$API_KEY&notify=http://engine.dial2verify.in/Integ/CatchAll.dvf&e-notify=support@dial2verify.in&out=JSON&cn=IN";
850
	    // $json=file_get_contents($APIUrl);
851
	    $json = json_encode($this->make_request($url,null));
852
	  	$this->response->type('json');
853
		$this->layout = 'ajax';
854
	    echo($json);die;
855
	}
856
 
857
	public function getdial2verifystatus() { 
858
 
859
		$SID=$_REQUEST["SID"];
860
 
861
	    $json = array();
862
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
863
 
864
	   // Make a call to Dial2Verify API & Parse The JSON Response
865
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
866
		$RequestPayload = $this->make_request($VerificationCall,null);
867
		// $RequestPayload = json_decode($response,true);
868
 
869
		$VerifStatus=$RequestPayload["VerificationStatus"];
870
 
871
		$json["VerificationStatus"]=$VerifStatus;
872
 
873
	   	$this->response->type('json');
874
		$this->layout = 'ajax';
875
	    echo(json_encode($json));die;
876
	}
877
 
878
	public function skipmobileverification() {
879
		$this->Session->write('skipmobileverification',1);
13739 anikendra 880
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 881
	}
882
 
883
	public function reauthenticate($userId) {
884
		$user = $this->User->read(null,$userId);
885
		$this->Auth->login($user['User']);
886
		$json = array('success'=>true);
887
		$this->response->type('json');
888
		$this->layout = 'ajax';
14150 anikendra 889
	    echo(json_encode($json));die;
13736 anikendra 890
	}
16013 anikendra 891
 
16982 naman 892
	public function getlinks($userId) {	
16082 anikendra 893
		$cachekey = 'userlinks-'.$userId;
894
		$links = Cache::read($cachekey,'day');
895
		if(empty($links)) {
896
			$links[3] = $this->getCatergoryLinks($userId,3);
897
			$links[5] = $this->getCatergoryLinks($userId,5);
898
			Cache::write($cachekey,$links,'day');
899
		}
16013 anikendra 900
	 	if ($this->request->is('requested')) {
901
            return $links;
902
        }
903
        $this->set('links', $links);
904
	}
905
 
906
	public function getCatergoryLinks($userId,$categoryId) {
907
		$temp = $links = $fixed = $random = array();		
908
		//populate fixed brands array
909
		if($categoryId == 3){
17172 anikendra 910
			$sql = "SELECT id,name FROM brands WHERE lower(name) IN('samsung','micromax','apple','intex','lava','spice','htc','lenovo','nokia','microsoft','xiaomi','sony') AND category_id = $categoryId";
16013 anikendra 911
		} else {
17172 anikendra 912
			$sql = "SELECT id,name FROM brands WHERE lower(name) IN('lenovo','dell','hp','iball','digiflip','samsung','datawind','apple','micromax','asus') AND category_id = $categoryId";
16013 anikendra 913
		}
914
		$brandnames = $this->User->query($sql);
16982 naman 915
 
16013 anikendra 916
		if(!empty($brandnames)){
917
			foreach ($brandnames as $key => $value) {
918
				if($categoryId == 3){
919
					if($value['brands']['name'] == 'Samsung' || $value['brands']['name'] == 'Micromax'){
920
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
16982 naman 921
						// fixed for samsung and micromax
16013 anikendra 922
					} else {
16982 naman 923
						$temp[] = $value['brands']; //Any three brand except the above.
16013 anikendra 924
					}							
925
				}else{
926
					if($value['brands']['name'] == 'Dell' || $value['brands']['name'] == 'Lenovo'){
927
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
928
					} else {
929
						$temp[] = $value['brands'];
930
					}							
931
				}			
932
			}		
933
		}
16982 naman 934
 
16013 anikendra 935
		$rand_keys = array_rand(array_keys($temp), 3);
17978 amit.gupta 936
		$sql = "select b.id,u.user_id,u.brand,sum(u.weight) w from newuserlinkssegmentation u left join brands b on lower(u.brand) = lower(b.name) where u.user_id = $userId and u.category_id = $categoryId and b.category_id=$categoryId group by u.brand order by w desc limit 5";
16982 naman 937
 
16013 anikendra 938
		$brands = $this->User->query($sql);
16982 naman 939
 
940
		$count = 0;
941
		$iterate= 0;
16013 anikendra 942
		if(!empty($brands)){
943
			foreach ($brands as $key => $brand) {
944
				if($key>2 && !empty($temp))continue;
16465 anikendra 945
				$links[$categoryId][$brand['u']['brand']] = "?filter=brand&brands=".$brand['b']['id'];
16982 naman 946
			}
947
 
16013 anikendra 948
			if(!empty($temp)){
16982 naman 949
				// for($i=0;$i<2;$i++) {//if brand in array and in while loop. first fix loop and then random.
950
				// 	$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];
951
				// 	echo "temp", $links[$categoryId][$temp[$rand_keys[$i]]['name']];
952
				while($count<2)
953
					{
954
						if(!array_key_exists($temp[$rand_keys[$iterate]]['name'], $links[$categoryId])) {							
955
							$links[$categoryId][$temp[$rand_keys[$iterate]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$iterate]]['id'];							
956
							$count++;
957
						}
958
						$iterate++;
959
					}
960
 
961
 
16013 anikendra 962
			}
963
		} else {
964
			if(!empty($fixed) && !empty($temp)){
965
				foreach ($fixed as $key => $value) {
966
					$links[$categoryId][$key] = $value;
967
				}			
968
				for($i=0;$i<3;$i++){
969
					$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];	
970
				}
16982 naman 971
 
16013 anikendra 972
			}
973
		}		
974
		return $links[$categoryId];		
975
	}
17766 manish.sha 976
 
977
	public function cartdetails(){
17947 manish.sha 978
		if ($this->request->is('post')) {
979
			$dataGiven = json_decode($this->request->data['cart_details']);
980
			$pincode = -1;
981
			$userId = $this->request->query('user_id');
982
 
983
			if(isset($this->request->data['pincode'])){
984
				$pincodeArgs = explode("_", $this->request->data['pincode']);
985
				$pincode = strval($pincodeArgs[1]);
986
			}
987
			if($pincode==-1 && isset($_COOKIE['s_pincode'])){
988
				$pincode = base64_decode($_COOKIE['s_pincode']);
989
			}
990
			$suserId = 0;
991
			$scartId = 0;
992
			$semailId = '';
993
 
994
			if(!(isset($_COOKIE['s_cart']))) {
995
				$this->loadModel('UserAccount');
996
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
997
				$cartId = $this->UserAccount->find('first',$options);
998
				$scartId = $cartId['UserAccount']['account_key'];
999
				setcookie('s_cart', base64_encode($scartId), -1, '/');
1000
			}else{
1001
				$scartId = base64_decode($_COOKIE['s_cart']);
1002
			}
1003
			if(!(isset($_COOKIE['s_id']))){
1004
				$this->loadModel('UserAccount');
1005
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1006
				$userAccount = $this->UserAccount->find('first',$options);
1007
				$suserId = $userAccount['UserAccount']['account_key'];
1008
				setcookie('s_id', base64_encode($suserId), -1, '/');
1009
			}else{
1010
				$suserId = base64_decode($_COOKIE['s_id']);
1011
			}
1012
			if(!(isset($_COOKIE['s_email']))){
1013
				$this->loadModel('User');
1014
				$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
1015
				$user = $this->User->find('first',$options);
1016
				$semailId = $user['User']['email'];
1017
				setcookie('s_email', base64_encode($user['User']['email']), -1, '/');
1018
			}else{
1019
				$semailId = base64_decode($_COOKIE['s_email']);
1020
			}
1021
 
1022
			$cartItems = array();
1023
 
1024
			foreach ($dataGiven->cartItems as $key=>$obj) {
1025
			    $itemobj = array(
1026
						'itemId'   => $key,
1027
			    		'quantity' => $obj->quantity);
1028
				array_push($cartItems, $itemobj);
1029
			}
1030
			$postData = array(
1031
						'cartItems'	=>	$cartItems
1032
						);
1033
 
1034
			$params = array(
1035
					'cartMap' => urlencode(json_encode($postData)));
1036
 
1037
			$this->layout = 'cartinnerpages';
1038
			$url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
1039
			if($pincode!='-1'){
1040
				$url = $url.'&pinCode='.$pincode;
1041
			}
1042
 
1043
			$cartskus = $this->post_cartinfo_request($url,$params);
1044
			if(isset($cartskus['response']) && $cartskus['response']=='error'){
1045
				if (strpos($this->referer(), '&error=1') !== false){
1046
					$this->redirect($this->referer());
1047
				}else{
1048
					$this->redirect($this->referer().'&error=1');
1049
				}
1050
				#$this->redirect(array('controller' => 'deals', 'action' => '?user_id='.$userId.'&error=1'));
1051
			}else{
1052
				if(strpos($cartskus['estimateString'],"Can't ship here")===false){
1053
					setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
1054
				}
1055
				$this->set(compact('cartskus'));
1056
			}
17804 manish.sha 1057
		}else{
18246 manish.sha 1058
			$userId = $this->request->query('user_id');
1059
			if(!(isset($_COOKIE['s_cart']))) {
1060
				$this->loadModel('UserAccount');
1061
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
1062
				$cartId = $this->UserAccount->find('first',$options);
1063
				$scartId = $cartId['UserAccount']['account_key'];
1064
			}else{
1065
				$scartId = base64_decode($_COOKIE['s_cart']);
1066
			}
1067
			if(!(isset($_COOKIE['s_id']))){
1068
				$this->loadModel('UserAccount');
1069
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1070
				$userAccount = $this->UserAccount->find('first',$options);
1071
				$suserId = $userAccount['UserAccount']['account_key'];
1072
			}else{
1073
				$suserId = base64_decode($_COOKIE['s_id']);
1074
			}
1075
			if(!(isset($_COOKIE['s_email']))){
1076
				$this->loadModel('User');
1077
				$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
1078
				$user = $this->User->find('first',$options);
1079
				$semailId = $user['User']['email'];
1080
			}else{
1081
				$semailId = base64_decode($_COOKIE['s_email']);
1082
			}
17947 manish.sha 1083
 
1084
			$pincode = -1;
1085
 
1086
			if($pincode==-1 && isset($_COOKIE['s_pincode'])){
1087
				$pincode = base64_decode($_COOKIE['s_pincode']);
1088
			}
1089
 
1090
			$cartItems = array();
1091
			$postData = array(
17804 manish.sha 1092
					'cartItems'	=>	$cartItems
1093
					);
1094
 
17947 manish.sha 1095
			$params = array(
1096
					'cartMap' => urlencode(json_encode($postData)));
1097
			$this->layout = 'cartinnerpages';
1098
			$url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
1099
			if($pincode!='-1'){
1100
				$url = $url.'&pinCode='.$pincode;
1101
			}
1102
			$cartskus = $this->post_cartinfo_request($url,$params);
1103
 
1104
			if(isset($cartskus['response']) && $cartskus['response']=='error'){
1105
				if (strpos($this->referer(), '&error=1') !== false){
1106
					$this->redirect($this->referer());
1107
				}else{
1108
					$this->redirect($this->referer().'&error=1');
1109
				}
17804 manish.sha 1110
			}else{
17947 manish.sha 1111
				if(strpos($cartskus['estimateString'],"Can't ship here")===false){
1112
					setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
1113
				}
1114
				$this->set(compact('cartskus'));
17804 manish.sha 1115
			}
1116
		}
1117
 
17766 manish.sha 1118
	}
1119
}