Subversion Repositories SmartDukaan

Rev

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