Subversion Repositories SmartDukaan

Rev

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