Subversion Repositories SmartDukaan

Rev

Rev 19206 | Rev 19214 | 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');
19206 naman 20
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet','admin_push','socialauth','oneringcb','admin_usersanctions','admin_loanhistory','admin_credithistory','sendseen')); 
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;
18670 manas 298
		        		if($oldMobile['User']['activated']==0){
299
		        			$this->request->data['status'] = 1;
300
		        		}
14768 anikendra 301
					}
18670 manas 302
 
14300 anikendra 303
	        	}
18836 manish.sha 304
	        	if(!empty($this->request->data['referrer'])) {
14768 anikendra 305
	        		$referrer = $this->request->data['referrer'];
14787 anikendra 306
	        		$this->log(print_r($referrer,1),'activations');
14768 anikendra 307
	        		$this->loadModel('ActivationCode');
14785 anikendra 308
	        		$exists = $this->ActivationCode->findByCode(strtoupper($referrer));
14787 anikendra 309
	        		$this->log(print_r($exists,1),'activations');
14768 anikendra 310
	        		if(empty($exists)){
311
	        			$result = array('success'=>false,'message'=>'Invalid referral code');
15085 anikendra 312
	        			// unset($this->request->data['referrer']);
14770 anikendra 313
	        			$updateRequired = false;
15477 anikendra 314
	        		} else {
315
	        			$this->request->data['activated'] = 1;        		
316
	        		}		        		
14768 anikendra 317
	        	}	        		
14770 anikendra 318
	        	if($updateRequired){
319
		            if ($this->User->save($this->request->data)) {
15475 anikendra 320
		            	if($this->request->data['activated'] == 1) {
321
		            		//Call user activation api
322
		        			$this->markUserActivated($id);
323
		            	}			        		
14770 anikendra 324
		                $result = array('success'=>true,'message'=>'Your profile has been saved');
325
		            } else {
326
		                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
327
		            }
328
		        }
13736 anikendra 329
	        }  
330
	    }
331
        $this->set(array(
332
		    'result' => $result,
333
		    '_serialize' => array('result')
334
		)); 
335
		$this->render('/Elements/json');      
13532 anikendra 336
    }
337
 
338
/**
339
 * admin_index method
340
 *
341
 * @return void
342
 */
14408 anikendra 343
 
344
	public function admin_pushnotifications(){
345
		if ($this->request->is('post')) {
346
			$sql = $this->request->data['User']['sql'];
347
			if(!empty($sql)){
348
				$users = $this->User->query($sql);
349
				$this->set(compact('users'));
350
			}
351
		}
352
	}
353
 
14445 anikendra 354
	public function generateAffiliateUrl($url,$user_id,$store){
355
		//Get StoreProduct Info		
14428 anikendra 356
		$storeId = $store['Store']['id'];
357
		$prefix = "SHA".$storeId;
358
		$tag = $prefix.time();
359
		if($storeId == 2){				
360
			$url = str_replace('www','m',$url);
361
		} elseif($storeId == 3) {
362
			$url_parts = parse_url($url);
363
			$url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
364
			if(isset($url_parts['query'])) {
365
				$url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
366
			}else{
367
				$url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
368
			}
369
		} elseif($storeId == 4){
14445 anikendra 370
			$next = str_replace('www','m',$url);	
14428 anikendra 371
			$url = $this->getAutoLoginUrl($userId,$next);
372
			$url .= '?utm_source=profitmandi';
373
		}
374
		if( strpos($url, '?') === false ) {
375
			$firstChar = '?';
376
		} else {
377
			$firstChar = '&';
378
		}
379
		$url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
380
		if(!empty($store['Store']['sub_tag_param'])){
381
			$url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
382
		}
383
		$extras = array('store'=>$store['Store']['name'],'source'=>'notification');
384
		$data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
385
		$this->loadModel('Click');
386
		$this->Click->create();
387
		$this->Click->save($data);
388
		return $url;
389
	}
390
 
14408 anikendra 391
	public function admin_push(){
392
		if ($this->request->is('post')) {
393
			if(empty($this->request->data['userIds'])){
394
				$this->Session->setFlash(__('Please choose a few users'));
395
				$this->redirect(array('action' => 'admin_pushnotifications'));
396
			}else{
14824 anikendra 397
				$this->log(print_r($this->request->data,1),'pushnotifications');
14445 anikendra 398
				$message = $this->request->data['User'];
14776 anikendra 399
				$this->loadModel('NotificationCampaign');
400
				$this->NotificationCampaign->create();
17349 manish.sha 401
				$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 402
				if($this->NotificationCampaign->save($data)){
403
					$message['cid'] = $this->NotificationCampaign->getLastInsertId();
404
				} else{
405
					$message['cid'] = $message['name'];
406
				}
17232 anikendra 407
				/*				
14445 anikendra 408
				if($message['type'] == 'url' && !empty($message['url'])) {
409
					$url = $message['url'];
410
					$this->loadModel('Store');
411
					$store = $this->Store->getByUrl($url);					
17232 anikendra 412
					$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14445 anikendra 413
				}				
14408 anikendra 414
				$this->loadModel('GcmUser');
415
				foreach ($this->request->data['userIds'] as $key => $value) {					
14770 anikendra 416
					$options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
14408 anikendra 417
					$gcmUser = $this->GcmUser->find('first',$options);
418
					$regIds = array($gcmUser['GcmUser']['gcm_regid']);
14445 anikendra 419
					// $message = array('message'=>$this->request->data['User']['message']);					
420
					if($message['type'] == 'url' && !empty($message['url'])) {
421
						$message['url'] = $this->generateAffiliateUrl($url,$value,$store);
14428 anikendra 422
					}					
423
					$this->send_push_notification($regIds,$message,$value);
14408 anikendra 424
				}
17232 anikendra 425
				*/
426
				$sentUsers = array();
427
				$payload = array();
428
				foreach ($this->request->data['userIds'] as $key => $value) {	
429
					if(!in_array($value, $sentUsers)) {
430
						$sentUsers[] = $value;								
17349 manish.sha 431
						$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$value,'type'=>'pending','status'=>0);						
17232 anikendra 432
						$payload[] = $data;
433
					}
434
				}
435
				$url = Configure::read('nodeurl')."/addPushNotification";
436
				$this->make_request($url,json_encode($payload,JSON_NUMERIC_CHECK));
14408 anikendra 437
			}
438
		}
439
	}
17232 anikendra 440
 
15414 manas 441
	private function send_push_notification($registatoin_ids, $message, $user_id) {
442
                $msg = array(
443
                    'message'       => $message['message'],
444
                    'cid'               => $message['cid'],
445
                    'title'         => $message['title'],
446
                    'type'              => $message['type'],
447
                    'url'                   => $message['url'],
448
                    // 'expiresat'          => strtotime($message['expiresat']),
449
                    'vibrate'       => 1,
450
                    'sound'         => 1,
451
                    'largeIcon'     => 'large_icon',
452
                    'smallIcon'     => 'small_icon'
453
                );
454
                // Set POST variables
455
                $url = 'https://android.googleapis.com/gcm/send';
14408 anikendra 456
 
15414 manas 457
                $fields = array(
458
                    'registration_ids' => $registatoin_ids,
459
                    'data' => $msg,
460
                );
461
                $headers = array(
462
                    'Authorization: key=' . Configure::read('googleapikey'),
463
                    'Content-Type: application/json'
464
                );
465
                //print_r($headers);
466
                // Open connection
467
                $ch = curl_init();
468
 
469
                // Set the url, number of POST vars, POST data
470
                curl_setopt($ch, CURLOPT_URL, $url);
471
                curl_setopt($ch, CURLOPT_POST, true);
472
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
473
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
474
 
475
                // Disabling SSL Certificate support temporarly
476
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
477
 
478
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
479
 
480
                // Execute post
481
                $result = curl_exec($ch);
482
                if ($result === FALSE) {
483
                    die('Curl failed: ' . curl_error($ch));
484
                }
485
                $res = json_decode($result,1);
486
 
487
                $this->loadModel('Pushnotification');
488
                if($res['success']==1){
489
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>'success');
490
				}else if($res['success']==0){
491
					$error_message=$res['results'][0]['error'];
492
					$sqlQuery="update gcm_users set failurecount=failurecount+1 where gcm_regid='".$registatoin_ids[0]."'";
493
					$resultData=$this->GcmUser->query($sqlQuery);
494
					$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>$error_message);
495
				}
496
                #$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
497
                $this->Pushnotification->create();
498
                $this->Pushnotification->save($data);
499
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($data,1),'pushnotifications');
500
                // Close connection
501
                curl_close($ch);
502
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
503
        }
504
 
15761 manas 505
	public function admin_index() {
13532 anikendra 506
		$this->User->recursive = 0;
15767 anikendra 507
		$options = array('limit'=>20,'order'=>array('id'=>'desc'));
14395 anikendra 508
		$this->Paginator->settings = $options;
509
		$users = $this->Paginator->paginate();
15761 manas 510
 
13532 anikendra 511
		$groups = $this->User->Group->find('list');
15761 manas 512
 
513
		$postOfficeQuery="select pincode,state from postoffices group by pincode";
514
		$postOfficeResult=$this->User->query($postOfficeQuery);
515
		$postOffice=array();
516
		foreach($postOfficeResult as $value){
517
			$postOffice[$value['postoffices']['pincode']]=$value['postoffices']['state'];
518
		}
519
		foreach ($users as $key => $value) {
520
	$userId=$value['User']['id'];
15815 anikendra 521
	$masterQuery="select u.id,rl.retailer_id,r.state,r.city,r.pin,
15762 manas 522
					ra.state,ra.city,ra.pin,
523
					u.state,u.city,u.pincode,
524
					ua.state,ua.city,ua.pincode 
525
					from retailers r left  join retaileraddresses ra  on r.id=ra.retailer_id  
526
					join retailerlinks rl on r.id=rl.retailer_id 
527
					right join users u on rl.user_id=u.id 
16549 anikendra 528
					left join user_addresses ua on u.id=ua.user_id 
15762 manas 529
					where u.id=$userId";
530
	$retailerAddress=$this->User->query($masterQuery);
15815 anikendra 531
	$users[$key]['User']['retailer_id']=$retailerAddress[0]['rl']['retailer_id'];	
15762 manas 532
	if($retailerAddress[0]['ra']['city']==null && $retailerAddress[0]['ra']['state']==null && $retailerAddress[0]['ra']['pin']==null){
533
		if($retailerAddress[0]['r']['city']==null && $retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']==null){
534
			if($retailerAddress[0]['ua']['city']==null && $retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']==null){
535
				if($retailerAddress[0]['u']['city']==null && $retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']==null){
536
 
15761 manas 537
				}else{
15762 manas 538
					if($retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']!=null){
539
						$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['u']['pincode']];		
540
					}else{
541
						$users[$key]['User']['state']=$retailerAddress[0]['u']['state'];	
542
						$users[$key]['User']['city']=$retailerAddress[0]['u']['city'];	
15761 manas 543
				}	
15762 manas 544
 
545
				}
15761 manas 546
			}
547
			else{
15762 manas 548
				if($retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']!=null){
549
					$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pincode']];		
15761 manas 550
				}else{
15762 manas 551
					$users[$key]['User']['state']=$retailerAddress[0]['ua']['state'];	
552
					$users[$key]['User']['city']=$retailerAddress[0]['ua']['city'];	
553
				}	
15761 manas 554
			}
555
		}
556
		else{
15762 manas 557
			if($retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']!=null){
558
				$users[$key]['User']['city']=$retailerAddress[0]['r']['city'];	
559
				$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];		
15761 manas 560
			}else{
15762 manas 561
				$users[$key]['User']['state']=$retailerAddress[0]['r']['state'];	
562
				$users[$key]['User']['city']=$retailerAddress[0]['r']['city'];	
563
			}		
15761 manas 564
		}
565
	}else{
15762 manas 566
		if(($retailerAddress[0]['ra']['state']==null || empty($retailerAddress[0]['ra']['state'])) && $retailerAddress[0]['ra']['pin']!=null){
567
			$users[$key]['User']['city']=$retailerAddress[0]['ra']['city'];	
568
			$users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];		
15761 manas 569
		}else{
15762 manas 570
			$users[$key]['User']['state']=$retailerAddress[0]['ra']['state'];	
571
			$users[$key]['User']['city']=$retailerAddress[0]['ra']['city'];	
572
		}		
13532 anikendra 573
	}
15761 manas 574
}
15762 manas 575
 
15761 manas 576
	$this->set(compact('groups','users'));	
577
}
578
 
13532 anikendra 579
/**
580
 * admin_view method
581
 *
582
 * @throws NotFoundException
583
 * @param string $id
584
 * @return void
585
 */
586
	public function admin_view($id = null) {
587
		$this->User->id = $id;
588
		if (!$this->User->exists()) {
589
			throw new NotFoundException(__('Invalid user'));
590
		}
591
		$this->set('user', $this->User->read(null, $id));
592
	}
593
 
594
/**
595
 * admin_add method
596
 *
597
 * @return void
598
 */
599
	public function admin_add() {
600
		if ($this->request->is('post')) {
601
			$this->User->create();
602
			if ($this->User->save($this->request->data)) {
603
				$this->Session->setFlash(__('The user has been saved'));
604
				$this->redirect(array('action' => 'index'));
605
			} else {
606
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
607
			}
608
		}
609
		$groups = $this->User->Group->find('list');
610
		$this->set(compact('groups'));
611
	}
612
 
613
/**
614
 * admin_edit method
615
 *
616
 * @throws NotFoundException
617
 * @param string $id
618
 * @return void
619
 */
620
	public function admin_edit($id = null) {
621
		$this->User->id = $id;
622
		if (!$this->User->exists()) {
623
			throw new NotFoundException(__('Invalid user'));
624
		}
625
		if ($this->request->is('post') || $this->request->is('put')) {
626
			if ($this->User->save($this->request->data)) {
627
				$this->Session->setFlash(__('The user has been saved'));
628
				$this->redirect(array('action' => 'index'));
629
			} else {
630
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
631
			}
632
		} else {
633
			$this->request->data = $this->User->read(null, $id);
634
		}
635
		$groups = $this->User->Group->find('list');
636
		$this->set(compact('groups'));
637
	}
638
 
639
/**
640
 * admin_delete method
641
 *
642
 * @throws MethodNotAllowedException
643
 * @throws NotFoundException
644
 * @param string $id
645
 * @return void
646
 */
15217 anikendra 647
/*
13532 anikendra 648
	public function admin_delete($id = null) {
649
		if (!$this->request->is('post')) {
650
			throw new MethodNotAllowedException();
651
		}
652
		$this->User->id = $id;
653
		if (!$this->User->exists()) {
654
			throw new NotFoundException(__('Invalid user'));
655
		}
656
		if ($this->User->delete()) {
657
			$this->Session->setFlash(__('User deleted'));
658
			$this->redirect(array('action' => 'index'));
659
		}
660
		$this->Session->setFlash(__('User was not deleted'));
661
		$this->redirect(array('action' => 'index'));
662
	}
15217 anikendra 663
*/
13532 anikendra 664
 
15217 anikendra 665
	public function admin_search() {
666
		$type = $this->request->query('type');
667
		$search = $this->request->query('search');
668
		$this->User->recursive = -1;
669
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
15232 anikendra 670
		if($type == 'unactivated'){
671
			$options['conditions'] = array('activated' =>0);
672
		}
673
		else if(!empty($type) && !empty($search)){
16465 anikendra 674
			if($type=='id'){
675
				$options['conditions'] = array($type =>$search);			
676
			}else{
677
				$options['conditions'] = array($type.' LIKE '=>"%$search%");			
678
			}
15232 anikendra 679
		}else{
17210 anikendra 680
			$options['conditions'] = array('date(User.created)'=>date('Y-m-d',time()));			
16465 anikendra 681
		}	
17345 naman 682
		// $db = ConnectionManager::getDataSource("default"); // name of your database connection
683
		// $last_act = $db->fetchAll("SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ");
684
		$sql = "SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ";
685
		$last_act = $this->User->query($sql);
686
		// debug($last_act);
687
		$last_act_user_id = array();
688
		$last_activated = array();
689
		foreach ($last_act as $key => $row) {
690
			// echo $key;
691
			foreach ($row as $key => $value) {
692
				$last_activated['visited'] = $value['visited'];
693
				$last_act_user_id[$value['user_id']] = $last_activated['visited'];
694
			}
695
		}
696
		// debug($last_act_user_id);
697
		$this->set(compact('last_act_user_id'));
698
		$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 699
		$options['joins'] = array(
17345 naman 700
		    /*array('table' => 'useractive',
16465 anikendra 701
		        'alias' => 'Useractive',
702
		        'type' => 'LEFT',
703
		        'conditions' => array(
704
		            'Useractive.user_id = User.id',
705
		        )
17345 naman 706
		    ),*/
16925 anikendra 707
		    array('table' => 'appacls',
708
		        'alias' => 'Appacl',
709
		        'type' => 'LEFT',
710
		        'conditions' => array(
711
		            'Appacl.user_id = User.id',
712
		        )
16465 anikendra 713
		    )
714
	    );
15232 anikendra 715
		$this->Paginator->settings = $options;
716
		$users = $this->Paginator->paginate();		
16256 manas 717
		foreach ($users as $key => $value) {
718
			$userId = $value['User']['id'];
719
			$quer= "select r.retailer_id,a.name from retailerlinks r join agents a on r.agent_id=a.id where user_id=$userId";
720
			$res = $this->User->query($quer);
16449 manas 721
			/*$last_act= "select last_active from useractive where user_id=$userId";
722
			$res_last = $this->User->query($last_act);*/
16256 manas 723
			if(empty($res)){
724
				$users[$key]['User']['retailer_id']="";	
725
				$users[$key]['User']['agent_name']="";	
726
			}else{
727
				$users[$key]['User']['retailer_id']=$res[0]['r']['retailer_id'];	
728
				$users[$key]['User']['agent_name']=$res[0]['a']['name'];	
729
			}
16449 manas 730
			/*if(empty($res_last)){
16448 manas 731
				$users[$key]['User']['last_active']="";
732
			}else{
733
				$users[$key]['User']['last_active']=$res_last[0]['useractive']['last_active'];
16449 manas 734
			}*/
16256 manas 735
 
736
		}
737
 
15380 anikendra 738
		$this->set(compact('users'));	
15217 anikendra 739
	}
740
 
13532 anikendra 741
	public function dashboard() {
742
		App::uses('CakeTime', 'Utility');
743
		$user = $this->User->read(null,$this->Auth->user('id'));
744
		$this->set('user',$user);
745
		$this->set('title_for_layout', "Dashboard");
746
	}
747
 
748
/**
749
* user authentication funtions
750
*/
751
	public function register() {
752
		$referrer = $this->request->query('referrer');
753
		$this->log('referrer = '.$referrer);
754
		$this->Cookie->write('referrer',$referrer);
755
		$this->layout = 'auth';
756
		$this->set('title_for_layout','Register your free letushaggle.com account');
757
		$this->SignMeUp->register();
758
	}
759
 
760
	public function activate() {
13714 anikendra 761
		$this->layout = 'auth';
13532 anikendra 762
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 763
		$this->SignMeUp->activate();
13532 anikendra 764
	}
765
 
766
	public function forgotten_password() {
13714 anikendra 767
		$this->layout = 'auth';
13532 anikendra 768
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 769
		$this->SignMeUp->forgottenPassword();
13532 anikendra 770
	}	
771
 
772
	public function login() {
17345 naman 773
		// $db = ConnectionManager::getDataSource("default"); // name of your database connection
774
		// $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 ");
775
		// debug($rest);
776
 
13532 anikendra 777
		$this->layout = 'auth';
778
		if (!empty($this->data['User']['next'])) {
779
		    $next = $this->data['User']['next'];
780
		    $this->Session->write('next', $next);
781
		} elseif (!empty($this->params['url']['next'])) {
782
		    $next = $this->params['url']['next'];
783
		    $this->Session->write('next', $next);
784
		}
785
		if ($this->Auth->login()) {
17345 naman 786
 
13532 anikendra 787
		    $next = $this->Session->read('next');
788
		    if (!empty($next)) {
789
				header('location:' . $next);
790
				exit();
791
		    }
17345 naman 792
		    $user = $this->User->read(null, $this->Auth->User('id'));		
793
		    // debug($user['User']['group_id']);
794
		 //    session_start();
795
		 //    $_SESSION["group_id"] = $user['User']['group_id'];
796
 
797
		 //    $this->loadModel('Acl');
798
			// $resul = $this->Acl->find('all', array('conditions' => array('group_id' => $_SESSION["group_id"]),'fields'=>('action')));
799
			// $_SESSION["permitted_action"] = $resul;
800
 
801
			// debug($_SESSION["permitted_action"]);
802
		    // echo $_SESSION["group_id"];
13532 anikendra 803
			if ($user['User']['group_id'] == 1) {
13736 anikendra 804
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 805
				exit();
806
			}
15188 anikendra 807
			else if ($user['User']['group_id'] >= 2) {
808
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
809
				exit();
810
		    }
13532 anikendra 811
		} else {
812
		    if (!empty($this->data)) {                
13736 anikendra 813
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 814
		    }
815
		}
816
		$this->set('title_for_layout', "Login to letushaggle.com");
817
	}
818
 
819
	public function logout() {
17345 naman 820
		// session_unset("group_id"); 
821
		// session_unset("permitted_action");
822
		// session_destroy("");
823
		// echo "Group Id" , $_SESSION["group_id"];
13532 anikendra 824
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
825
		$this->redirect($this->Auth->logout());
826
	}
827
 
828
	public function updatetimezone() {
829
		$this->layout = 'ajax';		
830
		$timezone = $_GET['tz'];
831
		Configure::load('constant');
832
		$timeZones = Configure::read("timeZones");
833
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
834
		if($this->User->query($query)){
835
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
836
		}else{
837
			$result = array('success' => false);
838
		}
839
		$this->set('result',$result);
840
	}
841
 
13736 anikendra 842
	public function verifymobile() {
843
		$this->layout = 'innerpages';
844
	}
13532 anikendra 845
 
13736 anikendra 846
	public function getdial2verifynumber() {
847
		$TelNumber=substr($this->request->data("phone_number"),-10);
848
 
849
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
850
	    $API_KEY = Configure::read("dial2verifyapikey");
851
 
852
	  	//Get API Image Response
853
	    $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";
854
	    // $json=file_get_contents($APIUrl);
855
	    $json = json_encode($this->make_request($url,null));
856
	  	$this->response->type('json');
857
		$this->layout = 'ajax';
858
	    echo($json);die;
859
	}
860
 
861
	public function getdial2verifystatus() { 
862
 
863
		$SID=$_REQUEST["SID"];
864
 
865
	    $json = array();
866
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
867
 
868
	   // Make a call to Dial2Verify API & Parse The JSON Response
869
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
870
		$RequestPayload = $this->make_request($VerificationCall,null);
871
		// $RequestPayload = json_decode($response,true);
872
 
873
		$VerifStatus=$RequestPayload["VerificationStatus"];
874
 
875
		$json["VerificationStatus"]=$VerifStatus;
876
 
877
	   	$this->response->type('json');
878
		$this->layout = 'ajax';
879
	    echo(json_encode($json));die;
880
	}
881
 
882
	public function skipmobileverification() {
883
		$this->Session->write('skipmobileverification',1);
13739 anikendra 884
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 885
	}
886
 
887
	public function reauthenticate($userId) {
888
		$user = $this->User->read(null,$userId);
889
		$this->Auth->login($user['User']);
890
		$json = array('success'=>true);
891
		$this->response->type('json');
892
		$this->layout = 'ajax';
14150 anikendra 893
	    echo(json_encode($json));die;
13736 anikendra 894
	}
16013 anikendra 895
 
16982 naman 896
	public function getlinks($userId) {	
16082 anikendra 897
		$cachekey = 'userlinks-'.$userId;
898
		$links = Cache::read($cachekey,'day');
899
		if(empty($links)) {
900
			$links[3] = $this->getCatergoryLinks($userId,3);
901
			$links[5] = $this->getCatergoryLinks($userId,5);
902
			Cache::write($cachekey,$links,'day');
903
		}
16013 anikendra 904
	 	if ($this->request->is('requested')) {
905
            return $links;
906
        }
907
        $this->set('links', $links);
908
	}
909
 
910
	public function getCatergoryLinks($userId,$categoryId) {
911
		$temp = $links = $fixed = $random = array();		
912
		//populate fixed brands array
913
		if($categoryId == 3){
17172 anikendra 914
			$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 915
		} else {
17172 anikendra 916
			$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 917
		}
918
		$brandnames = $this->User->query($sql);
16982 naman 919
 
16013 anikendra 920
		if(!empty($brandnames)){
921
			foreach ($brandnames as $key => $value) {
922
				if($categoryId == 3){
923
					if($value['brands']['name'] == 'Samsung' || $value['brands']['name'] == 'Micromax'){
924
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
16982 naman 925
						// fixed for samsung and micromax
16013 anikendra 926
					} else {
16982 naman 927
						$temp[] = $value['brands']; //Any three brand except the above.
16013 anikendra 928
					}							
929
				}else{
930
					if($value['brands']['name'] == 'Dell' || $value['brands']['name'] == 'Lenovo'){
931
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
932
					} else {
933
						$temp[] = $value['brands'];
934
					}							
935
				}			
936
			}		
937
		}
16982 naman 938
 
16013 anikendra 939
		$rand_keys = array_rand(array_keys($temp), 3);
17978 amit.gupta 940
		$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 941
 
16013 anikendra 942
		$brands = $this->User->query($sql);
16982 naman 943
 
944
		$count = 0;
945
		$iterate= 0;
16013 anikendra 946
		if(!empty($brands)){
947
			foreach ($brands as $key => $brand) {
948
				if($key>2 && !empty($temp))continue;
16465 anikendra 949
				$links[$categoryId][$brand['u']['brand']] = "?filter=brand&brands=".$brand['b']['id'];
16982 naman 950
			}
951
 
16013 anikendra 952
			if(!empty($temp)){
16982 naman 953
				// for($i=0;$i<2;$i++) {//if brand in array and in while loop. first fix loop and then random.
954
				// 	$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];
955
				// 	echo "temp", $links[$categoryId][$temp[$rand_keys[$i]]['name']];
956
				while($count<2)
957
					{
958
						if(!array_key_exists($temp[$rand_keys[$iterate]]['name'], $links[$categoryId])) {							
959
							$links[$categoryId][$temp[$rand_keys[$iterate]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$iterate]]['id'];							
960
							$count++;
961
						}
962
						$iterate++;
963
					}
964
 
965
 
16013 anikendra 966
			}
967
		} else {
968
			if(!empty($fixed) && !empty($temp)){
969
				foreach ($fixed as $key => $value) {
970
					$links[$categoryId][$key] = $value;
971
				}			
972
				for($i=0;$i<3;$i++){
973
					$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];	
974
				}
16982 naman 975
 
16013 anikendra 976
			}
977
		}		
978
		return $links[$categoryId];		
979
	}
17766 manish.sha 980
 
981
	public function cartdetails(){
17947 manish.sha 982
		if ($this->request->is('post')) {
983
			$dataGiven = json_decode($this->request->data['cart_details']);
984
			$pincode = -1;
985
			$userId = $this->request->query('user_id');
986
 
987
			if(isset($this->request->data['pincode'])){
988
				$pincodeArgs = explode("_", $this->request->data['pincode']);
989
				$pincode = strval($pincodeArgs[1]);
990
			}
991
			if($pincode==-1 && isset($_COOKIE['s_pincode'])){
992
				$pincode = base64_decode($_COOKIE['s_pincode']);
993
			}
994
			$suserId = 0;
995
			$scartId = 0;
996
			$semailId = '';
997
 
998
			if(!(isset($_COOKIE['s_cart']))) {
999
				$this->loadModel('UserAccount');
1000
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
1001
				$cartId = $this->UserAccount->find('first',$options);
1002
				$scartId = $cartId['UserAccount']['account_key'];
1003
				setcookie('s_cart', base64_encode($scartId), -1, '/');
1004
			}else{
1005
				$scartId = base64_decode($_COOKIE['s_cart']);
1006
			}
1007
			if(!(isset($_COOKIE['s_id']))){
1008
				$this->loadModel('UserAccount');
1009
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1010
				$userAccount = $this->UserAccount->find('first',$options);
1011
				$suserId = $userAccount['UserAccount']['account_key'];
1012
				setcookie('s_id', base64_encode($suserId), -1, '/');
1013
			}else{
1014
				$suserId = base64_decode($_COOKIE['s_id']);
1015
			}
1016
			if(!(isset($_COOKIE['s_email']))){
1017
				$this->loadModel('User');
1018
				$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
1019
				$user = $this->User->find('first',$options);
1020
				$semailId = $user['User']['email'];
1021
				setcookie('s_email', base64_encode($user['User']['email']), -1, '/');
1022
			}else{
1023
				$semailId = base64_decode($_COOKIE['s_email']);
1024
			}
1025
 
1026
			$cartItems = array();
1027
 
1028
			foreach ($dataGiven->cartItems as $key=>$obj) {
1029
			    $itemobj = array(
1030
						'itemId'   => $key,
1031
			    		'quantity' => $obj->quantity);
1032
				array_push($cartItems, $itemobj);
1033
			}
1034
			$postData = array(
1035
						'cartItems'	=>	$cartItems
1036
						);
1037
 
1038
			$params = array(
1039
					'cartMap' => urlencode(json_encode($postData)));
1040
 
1041
			$this->layout = 'cartinnerpages';
1042
			$url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
1043
			if($pincode!='-1'){
1044
				$url = $url.'&pinCode='.$pincode;
1045
			}
1046
 
1047
			$cartskus = $this->post_cartinfo_request($url,$params);
1048
			if(isset($cartskus['response']) && $cartskus['response']=='error'){
18605 manish.sha 1049
				if(parse_url($this->referer(), PHP_URL_QUERY)){
1050
					if (strpos($this->referer(), 'error=1') !== false){
1051
						$this->redirect($this->referer());
1052
					}else{
1053
						$this->redirect($this->referer().'&error=1');
1054
					}
17947 manish.sha 1055
				}
18605 manish.sha 1056
				else{
1057
					$this->redirect($this->referer().'?error=1');
1058
				}
17947 manish.sha 1059
				#$this->redirect(array('controller' => 'deals', 'action' => '?user_id='.$userId.'&error=1'));
1060
			}else{
1061
				if(strpos($cartskus['estimateString'],"Can't ship here")===false){
1062
					setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
1063
				}
1064
				$this->set(compact('cartskus'));
1065
			}
17804 manish.sha 1066
		}else{
18246 manish.sha 1067
			$userId = $this->request->query('user_id');
18322 manish.sha 1068
			$disable = $this->request->query('disable');
1069
			$disablePage = false;
1070
			if(isset($disable)){
1071
				$disablePage = true;
1072
			}
18246 manish.sha 1073
			if(!(isset($_COOKIE['s_cart']))) {
1074
				$this->loadModel('UserAccount');
1075
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
1076
				$cartId = $this->UserAccount->find('first',$options);
1077
				$scartId = $cartId['UserAccount']['account_key'];
1078
			}else{
1079
				$scartId = base64_decode($_COOKIE['s_cart']);
1080
			}
1081
			if(!(isset($_COOKIE['s_id']))){
1082
				$this->loadModel('UserAccount');
1083
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1084
				$userAccount = $this->UserAccount->find('first',$options);
1085
				$suserId = $userAccount['UserAccount']['account_key'];
1086
			}else{
1087
				$suserId = base64_decode($_COOKIE['s_id']);
1088
			}
1089
			if(!(isset($_COOKIE['s_email']))){
1090
				$this->loadModel('User');
1091
				$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
1092
				$user = $this->User->find('first',$options);
1093
				$semailId = $user['User']['email'];
1094
			}else{
1095
				$semailId = base64_decode($_COOKIE['s_email']);
1096
			}
17947 manish.sha 1097
 
1098
			$pincode = -1;
1099
 
1100
			if($pincode==-1 && isset($_COOKIE['s_pincode'])){
1101
				$pincode = base64_decode($_COOKIE['s_pincode']);
1102
			}
1103
 
1104
			$cartItems = array();
1105
			$postData = array(
17804 manish.sha 1106
					'cartItems'	=>	$cartItems
1107
					);
1108
 
17947 manish.sha 1109
			$params = array(
1110
					'cartMap' => urlencode(json_encode($postData)));
1111
			$this->layout = 'cartinnerpages';
1112
			$url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
1113
			if($pincode!='-1'){
1114
				$url = $url.'&pinCode='.$pincode;
1115
			}
1116
			$cartskus = $this->post_cartinfo_request($url,$params);
1117
 
1118
			if(isset($cartskus['response']) && $cartskus['response']=='error'){
18605 manish.sha 1119
				if(parse_url($this->referer(), PHP_URL_QUERY)){
1120
					if (strpos($this->referer(), 'error=1') !== false){
1121
						$this->redirect($this->referer());
1122
					}else{
1123
						$this->redirect($this->referer().'&error=1');
1124
					}
17947 manish.sha 1125
				}
18605 manish.sha 1126
				else{
1127
					$this->redirect($this->referer().'?error=1');
1128
				}
17804 manish.sha 1129
			}else{
17947 manish.sha 1130
				if(strpos($cartskus['estimateString'],"Can't ship here")===false){
1131
					setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
1132
				}
1133
				$this->set(compact('cartskus'));
18322 manish.sha 1134
				if($disablePage){
1135
					$this->set('disablePage',$disablePage);
1136
					$this->render('/Users/cartdetails_disabled');
1137
				}
17804 manish.sha 1138
			}
1139
		}
1140
 
17766 manish.sha 1141
	}
18768 manish.sha 1142
 
1143
	public function admin_usersanctions(){
18809 manish.sha 1144
		$url = Configure::read('saholicapihost').'counter!getUsersSanctionDetails?limit=0&offset=0';
18768 manish.sha 1145
		$response = $this->make_request ( $url, null );
18806 manish.sha 1146
		$userSanctions = $response['response']['userSanctions']['userSanctions'];
18809 manish.sha 1147
		$hasMore = $response['response']['userSanctions']['hasMore'];
1148
		$totalCount = $response['response']['userSanctions']['totalCount'];
18784 manish.sha 1149
		$this->loadModel('UserAccount');
1150
		$usersMap = array();
1151
		foreach($userSanctions AS $userSanction){
18809 manish.sha 1152
			if (!array_key_exists($userSanction['user_id'], $usersMap)) {
1153
				$options = array('conditions'=>array('account_key'=>$userSanction['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
1154
				$userId = $this->UserAccount->find('first',$options);
1155
				$userId = $userId['UserAccount']['user_id'];
1156
				$usersMap[$userSanction['user_id']]=$userId;
1157
			}
18784 manish.sha 1158
		}
1159
 
18809 manish.sha 1160
		$this->set(compact('userSanctions','usersMap','hasMore','totalCount'));
18768 manish.sha 1161
	}
18809 manish.sha 1162
 
18848 naman 1163
	public function admin_credithistory($cuid = 0){
1164
		$page = $this->request->query('page');
1165
		if(!isset($page)){
1166
			$page = 1;
1167
		}
1168
		$limit = 20;
1169
		$offset = ($page - 1)*$limit;
18856 naman 1170
		$this->loadModel('UserAccount');
1171
 
1172
		if($cuid!= 0){
1173
			$opt = array('conditions'=>array('user_id'=>$cuid,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1174
			$usId = $this->UserAccount->find('first',$opt);
1175
			$cuid = $usId['UserAccount']['account_key'];			
1176
		}
1177
 
18848 naman 1178
		$url = Configure::read('saholicapihost').'counter!getCreditHistory?userId='.$cuid.'&limit='.$limit.'&offset='.$offset;
18809 manish.sha 1179
		$response = $this->make_request ( $url, null );
1180
		$creditHistory = $response['response']['creditHistory'];
1181
		$hasMore = $response['response']['hasMore'];
1182
		$totalCount = $response['response']['totalCount'];
18856 naman 1183
 
18809 manish.sha 1184
		$usersMap = array();
1185
		foreach($creditHistory AS $creditH){
1186
			if (!array_key_exists($creditH['user_id'], $usersMap)) {
1187
				$options = array('conditions'=>array('account_key'=>$creditH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
1188
				$userId = $this->UserAccount->find('first',$options);
1189
				$userId = $userId['UserAccount']['user_id'];
1190
				$usersMap[$creditH['user_id']]=$userId;
1191
			}
18856 naman 1192
		}
18848 naman 1193
		$this->set(compact('creditHistory','usersMap','hasMore','totalCount','page'));
18809 manish.sha 1194
	}
1195
 
18856 naman 1196
	public function admin_loanhistory($cuid = 0){
1197
		$page = $this->request->query('page');
1198
		if(!isset($page)){
1199
			$page = 1;
1200
		}
1201
		$limit = 20;
1202
		$offset = ($page - 1)*$limit;
1203
		$this->loadModel('UserAccount');
1204
		if($cuid!= 0){
1205
			$opt = array('conditions'=>array('user_id'=>$cuid,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1206
			$usId = $this->UserAccount->find('first',$opt);
1207
			$cuid = $usId['UserAccount']['account_key'];
1208
		}
1209
 
1210
		$url = Configure::read('saholicapihost').'counter!getLoanHistory?userId='.$cuid.'&limit='.$limit.'&offset='.$offset;
1211
 
18809 manish.sha 1212
		$response = $this->make_request ( $url, null );
1213
		$loanHistory = $response['response']['loanHistory'];
1214
		$hasMore = $response['response']['hasMore'];
1215
		$totalCount = $response['response']['totalCount'];
18856 naman 1216
 
18809 manish.sha 1217
		$usersMap = array();
1218
		foreach($loanHistory AS $loanH){
1219
			if (!array_key_exists($loanH['user_id'], $usersMap)) {
1220
				$options = array('conditions'=>array('account_key'=>$loanH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
1221
				$userId = $this->UserAccount->find('first',$options);
1222
				$userId = $userId['UserAccount']['user_id'];
1223
				$usersMap[$loanH['user_id']]=$userId;
1224
			}
1225
		}
1226
 
18856 naman 1227
		$this->set(compact('loanHistory','usersMap','hasMore','totalCount','page'));
18809 manish.sha 1228
	}
19046 naman 1229
 
1230
	public function usernotification($user = null){
19206 naman 1231
		$android_id = $this->request->query('android_id');
1232
		$user_id = $this->request->query('user_id');
19098 naman 1233
		$page = $this->request->query('page');
1234
		if(!isset($page)){
1235
			$page = 1;
1236
		}
1237
		$limit = 20;
1238
		$offset = ($page - 1)*$limit;
19046 naman 1239
		$this->layout = 'innerpages';
19206 naman 1240
		$url = Configure::read('nodeurl')."/getAllNotifications?user_id=".$user_id."&android_id=".$android_id."&offset=".$offset."&limit=".$limit;
1241
		$noti= $this->make_request($url,null);
1242
		if(isset($noti) && !empty($noti))
1243
		{
1244
			foreach ($noti as $nkey => $nval){
1245
				if($nval["status"] == "sent" || $nval["status"] == "recieved" || $nval["status"] == "failed"){
1246
					$noti[$nkey]['seen'] = false;
1247
				}
1248
				if($nval["status"] == "opened" || $nval["status"] == "referrer" || $nval["status"] == "login"){
1249
					$noti[$nkey]['seen'] = true;
1250
				}
1251
			}
19213 manas 1252
		}		
19098 naman 1253
		$nexturl = "/users/getmorenotification?page=".($page+1);
1254
		$this->set(compact('noti','nexturl'));
19046 naman 1255
	}
19098 naman 1256
 
1257
	public function getmorenotification(){
1258
		$this->layout = 'ajax';
1259
		$page = $this->request->query('page');
1260
		if(!isset($page)){
1261
			$page = 1;
1262
		}
1263
		$limit = 20;
1264
		$offset = ($page - 1)*$limit;
19206 naman 1265
		$url = Configure::read('nodeurl')."/getAllNotifications?user_id=".$user_id."&android_id=".$android_id."&offset=".$offset."&limit=".$limit;
1266
		$noti= $this->make_request($url,null);
19213 manas 1267
		debug($noti);
19206 naman 1268
		if(isset($noti) && !empty($noti))
1269
		{
1270
			foreach ($noti as $nkey => $nval){
1271
				if($nval["status"] == "sent" || $nval["status"] == "recieved" || $nval["status"] == "failed"){
1272
					$noti[$nkey]['seen'] = false;
1273
				}
1274
				if($nval["status"] == "opened" || $nval["status"] == "referrer" || $nval["status"] == "login"){
1275
					$noti[$nkey]['seen'] = true;
1276
				}
1277
			}
1278
		}
19098 naman 1279
		$nexturl = "/users/getmorenotification?page=".($page+1);
1280
		$this->set(compact('noti','nexturl'));
1281
		$this->render('/Elements/getnotification');
1282
	}
19206 naman 1283
 
1284
	public function sendseen($cid = null){
19213 manas 1285
 
1286
		$data = array();
1287
		$data['cid']=$cid;
1288
		$data['result']='opened';
1289
		$data['user_id']=$this->Auth->user('id');
1290
		$url = Configure::read('nodeurl')."/addPushNotificationByApk";//remove hardcoded value
1291
		$response = $this->post_request($url,$data);
1292
		if(!empty($response)){
1293
			$result = array('success' => true,'message'=>'The pushnotification has been saved.');
1294
		} else {
1295
			$result = array('success' => false,'message'=>'The pushnotification could not be saved. Please, try again.');
1296
		}		
1297
		$this->set(array(
1298
		    'result' => $result,
1299
		    '_serialize' => array('result')
1300
		));
1301
		$this->render('/Elements/json');	
19206 naman 1302
	}
17766 manish.sha 1303
}