Subversion Repositories SmartDukaan

Rev

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