Subversion Repositories SmartDukaan

Rev

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