Subversion Repositories SmartDukaan

Rev

Rev 20132 | Rev 20165 | 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{
17210 anikendra 700
			$options['conditions'] = array('date(User.created)'=>date('Y-m-d',time()));			
16465 anikendra 701
		}	
17345 naman 702
		// $db = ConnectionManager::getDataSource("default"); // name of your database connection
703
		// $last_act = $db->fetchAll("SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ");
704
		$sql = "SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ";
705
		$last_act = $this->User->query($sql);
706
		// debug($last_act);
707
		$last_act_user_id = array();
708
		$last_activated = array();
709
		foreach ($last_act as $key => $row) {
710
			// echo $key;
711
			foreach ($row as $key => $value) {
712
				$last_activated['visited'] = $value['visited'];
713
				$last_act_user_id[$value['user_id']] = $last_activated['visited'];
714
			}
715
		}
716
		// debug($last_act_user_id);
717
		$this->set(compact('last_act_user_id'));
718
		$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 719
		$options['joins'] = array(
17345 naman 720
		    /*array('table' => 'useractive',
16465 anikendra 721
		        'alias' => 'Useractive',
722
		        'type' => 'LEFT',
723
		        'conditions' => array(
724
		            'Useractive.user_id = User.id',
725
		        )
17345 naman 726
		    ),*/
16925 anikendra 727
		    array('table' => 'appacls',
728
		        'alias' => 'Appacl',
729
		        'type' => 'LEFT',
730
		        'conditions' => array(
731
		            'Appacl.user_id = User.id',
732
		        )
16465 anikendra 733
		    )
734
	    );
15232 anikendra 735
		$this->Paginator->settings = $options;
736
		$users = $this->Paginator->paginate();		
16256 manas 737
		foreach ($users as $key => $value) {
738
			$userId = $value['User']['id'];
739
			$quer= "select r.retailer_id,a.name from retailerlinks r join agents a on r.agent_id=a.id where user_id=$userId";
740
			$res = $this->User->query($quer);
16449 manas 741
			/*$last_act= "select last_active from useractive where user_id=$userId";
742
			$res_last = $this->User->query($last_act);*/
16256 manas 743
			if(empty($res)){
744
				$users[$key]['User']['retailer_id']="";	
745
				$users[$key]['User']['agent_name']="";	
746
			}else{
747
				$users[$key]['User']['retailer_id']=$res[0]['r']['retailer_id'];	
748
				$users[$key]['User']['agent_name']=$res[0]['a']['name'];	
749
			}
16449 manas 750
			/*if(empty($res_last)){
16448 manas 751
				$users[$key]['User']['last_active']="";
752
			}else{
753
				$users[$key]['User']['last_active']=$res_last[0]['useractive']['last_active'];
16449 manas 754
			}*/
16256 manas 755
 
756
		}
757
 
15380 anikendra 758
		$this->set(compact('users'));	
15217 anikendra 759
	}
760
 
13532 anikendra 761
	public function dashboard() {
762
		App::uses('CakeTime', 'Utility');
763
		$user = $this->User->read(null,$this->Auth->user('id'));
764
		$this->set('user',$user);
765
		$this->set('title_for_layout', "Dashboard");
766
	}
767
 
768
/**
769
* user authentication funtions
770
*/
771
	public function register() {
772
		$referrer = $this->request->query('referrer');
773
		$this->log('referrer = '.$referrer);
774
		$this->Cookie->write('referrer',$referrer);
775
		$this->layout = 'auth';
776
		$this->set('title_for_layout','Register your free letushaggle.com account');
777
		$this->SignMeUp->register();
778
	}
779
 
780
	public function activate() {
13714 anikendra 781
		$this->layout = 'auth';
13532 anikendra 782
		$this->set('title_for_layout','Activate your copublish.in account');
13714 anikendra 783
		$this->SignMeUp->activate();
13532 anikendra 784
	}
785
 
786
	public function forgotten_password() {
13714 anikendra 787
		$this->layout = 'auth';
13532 anikendra 788
		$this->set('title_for_layout','Reset your copublish.in password');
13714 anikendra 789
		$this->SignMeUp->forgottenPassword();
13532 anikendra 790
	}	
791
 
792
	public function login() {
17345 naman 793
		// $db = ConnectionManager::getDataSource("default"); // name of your database connection
794
		// $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 ");
795
		// debug($rest);
796
 
13532 anikendra 797
		$this->layout = 'auth';
798
		if (!empty($this->data['User']['next'])) {
799
		    $next = $this->data['User']['next'];
800
		    $this->Session->write('next', $next);
801
		} elseif (!empty($this->params['url']['next'])) {
802
		    $next = $this->params['url']['next'];
803
		    $this->Session->write('next', $next);
804
		}
805
		if ($this->Auth->login()) {
17345 naman 806
 
13532 anikendra 807
		    $next = $this->Session->read('next');
808
		    if (!empty($next)) {
809
				header('location:' . $next);
810
				exit();
811
		    }
17345 naman 812
		    $user = $this->User->read(null, $this->Auth->User('id'));		
813
		    // debug($user['User']['group_id']);
814
		 //    session_start();
815
		 //    $_SESSION["group_id"] = $user['User']['group_id'];
816
 
817
		 //    $this->loadModel('Acl');
818
			// $resul = $this->Acl->find('all', array('conditions' => array('group_id' => $_SESSION["group_id"]),'fields'=>('action')));
819
			// $_SESSION["permitted_action"] = $resul;
820
 
821
			// debug($_SESSION["permitted_action"]);
822
		    // echo $_SESSION["group_id"];
13532 anikendra 823
			if ($user['User']['group_id'] == 1) {
13736 anikendra 824
				$this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
13532 anikendra 825
				exit();
826
			}
19731 naman 827
			else if ($user['User']['group_id'] >= 2 && $user['User']['group_id']<99) {
15188 anikendra 828
				$this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
829
				exit();
830
		    }
13532 anikendra 831
		} else {
832
		    if (!empty($this->data)) {                
13736 anikendra 833
				$this->Session->setFlash(__('Invalid username or password'),'error_message');
13532 anikendra 834
		    }
835
		}
836
		$this->set('title_for_layout', "Login to letushaggle.com");
837
	}
838
 
839
	public function logout() {
17345 naman 840
		// session_unset("group_id"); 
841
		// session_unset("permitted_action");
842
		// session_destroy("");
843
		// echo "Group Id" , $_SESSION["group_id"];
13532 anikendra 844
		$this->Session->setFlash(__('You have been logged out now'),'success_message');
845
		$this->redirect($this->Auth->logout());
846
	}
847
 
848
	public function updatetimezone() {
849
		$this->layout = 'ajax';		
850
		$timezone = $_GET['tz'];
851
		Configure::load('constant');
852
		$timeZones = Configure::read("timeZones");
853
		$query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
854
		if($this->User->query($query)){
855
			$result = array('success' => true,'tz' => $timeZones[$timezone]);
856
		}else{
857
			$result = array('success' => false);
858
		}
859
		$this->set('result',$result);
860
	}
861
 
13736 anikendra 862
	public function verifymobile() {
863
		$this->layout = 'innerpages';
864
	}
13532 anikendra 865
 
13736 anikendra 866
	public function getdial2verifynumber() {
867
		$TelNumber=substr($this->request->data("phone_number"),-10);
868
 
869
	  // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
870
	    $API_KEY = Configure::read("dial2verifyapikey");
871
 
872
	  	//Get API Image Response
873
	    $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";
874
	    // $json=file_get_contents($APIUrl);
875
	    $json = json_encode($this->make_request($url,null));
876
	  	$this->response->type('json');
877
		$this->layout = 'ajax';
878
	    echo($json);die;
879
	}
880
 
881
	public function getdial2verifystatus() { 
882
 
883
		$SID=$_REQUEST["SID"];
884
 
885
	    $json = array();
886
		$VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";
887
 
888
	   // Make a call to Dial2Verify API & Parse The JSON Response
889
		// $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
890
		$RequestPayload = $this->make_request($VerificationCall,null);
891
		// $RequestPayload = json_decode($response,true);
892
 
893
		$VerifStatus=$RequestPayload["VerificationStatus"];
894
 
895
		$json["VerificationStatus"]=$VerifStatus;
896
 
897
	   	$this->response->type('json');
898
		$this->layout = 'ajax';
899
	    echo(json_encode($json));die;
900
	}
901
 
902
	public function skipmobileverification() {
903
		$this->Session->write('skipmobileverification',1);
13739 anikendra 904
		$this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
13736 anikendra 905
	}
906
 
907
	public function reauthenticate($userId) {
908
		$user = $this->User->read(null,$userId);
909
		$this->Auth->login($user['User']);
910
		$json = array('success'=>true);
911
		$this->response->type('json');
912
		$this->layout = 'ajax';
14150 anikendra 913
	    echo(json_encode($json));die;
13736 anikendra 914
	}
16013 anikendra 915
 
16982 naman 916
	public function getlinks($userId) {	
16082 anikendra 917
		$cachekey = 'userlinks-'.$userId;
918
		$links = Cache::read($cachekey,'day');
919
		if(empty($links)) {
920
			$links[3] = $this->getCatergoryLinks($userId,3);
921
			$links[5] = $this->getCatergoryLinks($userId,5);
922
			Cache::write($cachekey,$links,'day');
923
		}
16013 anikendra 924
	 	if ($this->request->is('requested')) {
925
            return $links;
926
        }
927
        $this->set('links', $links);
928
	}
929
 
930
	public function getCatergoryLinks($userId,$categoryId) {
931
		$temp = $links = $fixed = $random = array();		
932
		//populate fixed brands array
933
		if($categoryId == 3){
17172 anikendra 934
			$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 935
		} else {
17172 anikendra 936
			$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 937
		}
938
		$brandnames = $this->User->query($sql);
16982 naman 939
 
16013 anikendra 940
		if(!empty($brandnames)){
941
			foreach ($brandnames as $key => $value) {
942
				if($categoryId == 3){
943
					if($value['brands']['name'] == 'Samsung' || $value['brands']['name'] == 'Micromax'){
944
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
16982 naman 945
						// fixed for samsung and micromax
16013 anikendra 946
					} else {
16982 naman 947
						$temp[] = $value['brands']; //Any three brand except the above.
16013 anikendra 948
					}							
949
				}else{
950
					if($value['brands']['name'] == 'Dell' || $value['brands']['name'] == 'Lenovo'){
951
						$fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
952
					} else {
953
						$temp[] = $value['brands'];
954
					}							
955
				}			
956
			}		
957
		}
16982 naman 958
 
16013 anikendra 959
		$rand_keys = array_rand(array_keys($temp), 3);
17978 amit.gupta 960
		$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 961
 
16013 anikendra 962
		$brands = $this->User->query($sql);
16982 naman 963
 
964
		$count = 0;
965
		$iterate= 0;
16013 anikendra 966
		if(!empty($brands)){
967
			foreach ($brands as $key => $brand) {
968
				if($key>2 && !empty($temp))continue;
16465 anikendra 969
				$links[$categoryId][$brand['u']['brand']] = "?filter=brand&brands=".$brand['b']['id'];
16982 naman 970
			}
971
 
16013 anikendra 972
			if(!empty($temp)){
16982 naman 973
				// for($i=0;$i<2;$i++) {//if brand in array and in while loop. first fix loop and then random.
974
				// 	$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];
975
				// 	echo "temp", $links[$categoryId][$temp[$rand_keys[$i]]['name']];
976
				while($count<2)
977
					{
978
						if(!array_key_exists($temp[$rand_keys[$iterate]]['name'], $links[$categoryId])) {							
979
							$links[$categoryId][$temp[$rand_keys[$iterate]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$iterate]]['id'];							
980
							$count++;
981
						}
982
						$iterate++;
983
					}
984
 
985
 
16013 anikendra 986
			}
987
		} else {
988
			if(!empty($fixed) && !empty($temp)){
989
				foreach ($fixed as $key => $value) {
990
					$links[$categoryId][$key] = $value;
991
				}			
992
				for($i=0;$i<3;$i++){
993
					$links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];	
994
				}
16982 naman 995
 
16013 anikendra 996
			}
997
		}		
998
		return $links[$categoryId];		
999
	}
17766 manish.sha 1000
 
1001
	public function cartdetails(){
17947 manish.sha 1002
		if ($this->request->is('post')) {
1003
			$dataGiven = json_decode($this->request->data['cart_details']);
1004
			$pincode = -1;
1005
			$userId = $this->request->query('user_id');
1006
 
1007
			if(isset($this->request->data['pincode'])){
1008
				$pincodeArgs = explode("_", $this->request->data['pincode']);
1009
				$pincode = strval($pincodeArgs[1]);
1010
			}
1011
			if($pincode==-1 && isset($_COOKIE['s_pincode'])){
1012
				$pincode = base64_decode($_COOKIE['s_pincode']);
1013
			}
1014
			$suserId = 0;
1015
			$scartId = 0;
1016
			$semailId = '';
1017
 
1018
			if(!(isset($_COOKIE['s_cart']))) {
1019
				$this->loadModel('UserAccount');
1020
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
1021
				$cartId = $this->UserAccount->find('first',$options);
1022
				$scartId = $cartId['UserAccount']['account_key'];
1023
				setcookie('s_cart', base64_encode($scartId), -1, '/');
1024
			}else{
1025
				$scartId = base64_decode($_COOKIE['s_cart']);
1026
			}
1027
			if(!(isset($_COOKIE['s_id']))){
1028
				$this->loadModel('UserAccount');
1029
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1030
				$userAccount = $this->UserAccount->find('first',$options);
1031
				$suserId = $userAccount['UserAccount']['account_key'];
1032
				setcookie('s_id', base64_encode($suserId), -1, '/');
1033
			}else{
1034
				$suserId = base64_decode($_COOKIE['s_id']);
1035
			}
1036
			if(!(isset($_COOKIE['s_email']))){
1037
				$this->loadModel('User');
1038
				$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
1039
				$user = $this->User->find('first',$options);
1040
				$semailId = $user['User']['email'];
1041
				setcookie('s_email', base64_encode($user['User']['email']), -1, '/');
1042
			}else{
1043
				$semailId = base64_decode($_COOKIE['s_email']);
1044
			}
1045
 
1046
			$cartItems = array();
1047
 
1048
			foreach ($dataGiven->cartItems as $key=>$obj) {
1049
			    $itemobj = array(
1050
						'itemId'   => $key,
1051
			    		'quantity' => $obj->quantity);
1052
				array_push($cartItems, $itemobj);
1053
			}
1054
			$postData = array(
1055
						'cartItems'	=>	$cartItems
1056
						);
1057
 
1058
			$params = array(
1059
					'cartMap' => urlencode(json_encode($postData)));
1060
 
1061
			$this->layout = 'cartinnerpages';
1062
			$url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
1063
			if($pincode!='-1'){
1064
				$url = $url.'&pinCode='.$pincode;
1065
			}
1066
 
1067
			$cartskus = $this->post_cartinfo_request($url,$params);
1068
			if(isset($cartskus['response']) && $cartskus['response']=='error'){
18605 manish.sha 1069
				if(parse_url($this->referer(), PHP_URL_QUERY)){
1070
					if (strpos($this->referer(), 'error=1') !== false){
1071
						$this->redirect($this->referer());
1072
					}else{
1073
						$this->redirect($this->referer().'&error=1');
1074
					}
17947 manish.sha 1075
				}
18605 manish.sha 1076
				else{
1077
					$this->redirect($this->referer().'?error=1');
1078
				}
17947 manish.sha 1079
				#$this->redirect(array('controller' => 'deals', 'action' => '?user_id='.$userId.'&error=1'));
1080
			}else{
1081
				if(strpos($cartskus['estimateString'],"Can't ship here")===false){
1082
					setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
1083
				}
1084
				$this->set(compact('cartskus'));
1085
			}
17804 manish.sha 1086
		}else{
18246 manish.sha 1087
			$userId = $this->request->query('user_id');
18322 manish.sha 1088
			$disable = $this->request->query('disable');
1089
			$disablePage = false;
1090
			if(isset($disable)){
1091
				$disablePage = true;
1092
			}
18246 manish.sha 1093
			if(!(isset($_COOKIE['s_cart']))) {
1094
				$this->loadModel('UserAccount');
1095
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
1096
				$cartId = $this->UserAccount->find('first',$options);
1097
				$scartId = $cartId['UserAccount']['account_key'];
1098
			}else{
1099
				$scartId = base64_decode($_COOKIE['s_cart']);
1100
			}
1101
			if(!(isset($_COOKIE['s_id']))){
1102
				$this->loadModel('UserAccount');
1103
				$options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1104
				$userAccount = $this->UserAccount->find('first',$options);
1105
				$suserId = $userAccount['UserAccount']['account_key'];
1106
			}else{
1107
				$suserId = base64_decode($_COOKIE['s_id']);
1108
			}
1109
			if(!(isset($_COOKIE['s_email']))){
1110
				$this->loadModel('User');
1111
				$options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
1112
				$user = $this->User->find('first',$options);
1113
				$semailId = $user['User']['email'];
1114
			}else{
1115
				$semailId = base64_decode($_COOKIE['s_email']);
1116
			}
17947 manish.sha 1117
 
1118
			$pincode = -1;
1119
 
1120
			if($pincode==-1 && isset($_COOKIE['s_pincode'])){
1121
				$pincode = base64_decode($_COOKIE['s_pincode']);
1122
			}
1123
 
1124
			$cartItems = array();
1125
			$postData = array(
17804 manish.sha 1126
					'cartItems'	=>	$cartItems
1127
					);
1128
 
17947 manish.sha 1129
			$params = array(
1130
					'cartMap' => urlencode(json_encode($postData)));
1131
			$this->layout = 'cartinnerpages';
1132
			$url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
1133
			if($pincode!='-1'){
1134
				$url = $url.'&pinCode='.$pincode;
1135
			}
1136
			$cartskus = $this->post_cartinfo_request($url,$params);
1137
 
1138
			if(isset($cartskus['response']) && $cartskus['response']=='error'){
18605 manish.sha 1139
				if(parse_url($this->referer(), PHP_URL_QUERY)){
1140
					if (strpos($this->referer(), 'error=1') !== false){
1141
						$this->redirect($this->referer());
1142
					}else{
1143
						$this->redirect($this->referer().'&error=1');
1144
					}
17947 manish.sha 1145
				}
18605 manish.sha 1146
				else{
1147
					$this->redirect($this->referer().'?error=1');
1148
				}
17804 manish.sha 1149
			}else{
17947 manish.sha 1150
				if(strpos($cartskus['estimateString'],"Can't ship here")===false){
1151
					setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
1152
				}
1153
				$this->set(compact('cartskus'));
18322 manish.sha 1154
				if($disablePage){
1155
					$this->set('disablePage',$disablePage);
1156
					$this->render('/Users/cartdetails_disabled');
1157
				}
17804 manish.sha 1158
			}
1159
		}
1160
 
17766 manish.sha 1161
	}
18768 manish.sha 1162
 
1163
	public function admin_usersanctions(){
18809 manish.sha 1164
		$url = Configure::read('saholicapihost').'counter!getUsersSanctionDetails?limit=0&offset=0';
19892 manas 1165
		if($this->request->is('post')){
1166
			$filter = $this->request->data['UserSanctions']['searchUserBy'];
1167
			if ($filter==1){
1168
				$url = $url.'&sort=loan';	
1169
			}
1170
		}
18768 manish.sha 1171
		$response = $this->make_request ( $url, null );
18806 manish.sha 1172
		$userSanctions = $response['response']['userSanctions']['userSanctions'];
18809 manish.sha 1173
		$hasMore = $response['response']['userSanctions']['hasMore'];
1174
		$totalCount = $response['response']['userSanctions']['totalCount'];
18784 manish.sha 1175
		$this->loadModel('UserAccount');
1176
		$usersMap = array();
19731 naman 1177
		$usersName = array();
18784 manish.sha 1178
		foreach($userSanctions AS $userSanction){
18809 manish.sha 1179
			if (!array_key_exists($userSanction['user_id'], $usersMap)) {
1180
				$options = array('conditions'=>array('account_key'=>$userSanction['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
1181
				$userId = $this->UserAccount->find('first',$options);
1182
				$userId = $userId['UserAccount']['user_id'];
19731 naman 1183
				$opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>'first_name');
1184
				$userName = $this->User->find('first',$opts);
1185
				$usersName[$userSanction['user_id']] = $userName['User']['first_name'];
18809 manish.sha 1186
				$usersMap[$userSanction['user_id']]=$userId;
1187
			}
18784 manish.sha 1188
		}
19731 naman 1189
		$this->set(compact('usersName','userSanctions','usersMap','hasMore','totalCount'));
18768 manish.sha 1190
	}
18809 manish.sha 1191
 
18848 naman 1192
	public function admin_credithistory($cuid = 0){
1193
		$page = $this->request->query('page');
1194
		if(!isset($page)){
1195
			$page = 1;
1196
		}
1197
		$limit = 20;
1198
		$offset = ($page - 1)*$limit;
18856 naman 1199
		$this->loadModel('UserAccount');
1200
 
1201
		if($cuid!= 0){
1202
			$opt = array('conditions'=>array('user_id'=>$cuid,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1203
			$usId = $this->UserAccount->find('first',$opt);
1204
			$cuid = $usId['UserAccount']['account_key'];			
1205
		}
1206
 
18848 naman 1207
		$url = Configure::read('saholicapihost').'counter!getCreditHistory?userId='.$cuid.'&limit='.$limit.'&offset='.$offset;
18809 manish.sha 1208
		$response = $this->make_request ( $url, null );
1209
		$creditHistory = $response['response']['creditHistory'];
1210
		$hasMore = $response['response']['hasMore'];
1211
		$totalCount = $response['response']['totalCount'];
19731 naman 1212
		$usersName = array();
18809 manish.sha 1213
		$usersMap = array();
1214
		foreach($creditHistory AS $creditH){
1215
			if (!array_key_exists($creditH['user_id'], $usersMap)) {
1216
				$options = array('conditions'=>array('account_key'=>$creditH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
1217
				$userId = $this->UserAccount->find('first',$options);
1218
				$userId = $userId['UserAccount']['user_id'];
19731 naman 1219
				$opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>'first_name');
1220
				$userName = $this->User->find('first',$opts);
1221
				$usersName[$creditH['user_id']] = $userName['User']['first_name'];
18809 manish.sha 1222
				$usersMap[$creditH['user_id']]=$userId;
1223
			}
18856 naman 1224
		}
19731 naman 1225
		$this->set(compact('creditHistory','usersName','usersMap','hasMore','totalCount','page'));
18809 manish.sha 1226
	}
1227
 
18856 naman 1228
	public function admin_loanhistory($cuid = 0){
1229
		$page = $this->request->query('page');
1230
		if(!isset($page)){
1231
			$page = 1;
1232
		}
1233
		$limit = 20;
1234
		$offset = ($page - 1)*$limit;
1235
		$this->loadModel('UserAccount');
1236
		if($cuid!= 0){
1237
			$opt = array('conditions'=>array('user_id'=>$cuid,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
1238
			$usId = $this->UserAccount->find('first',$opt);
1239
			$cuid = $usId['UserAccount']['account_key'];
1240
		}
1241
 
1242
		$url = Configure::read('saholicapihost').'counter!getLoanHistory?userId='.$cuid.'&limit='.$limit.'&offset='.$offset;
1243
 
18809 manish.sha 1244
		$response = $this->make_request ( $url, null );
1245
		$loanHistory = $response['response']['loanHistory'];
1246
		$hasMore = $response['response']['hasMore'];
1247
		$totalCount = $response['response']['totalCount'];
19731 naman 1248
		$usersName = array();
18809 manish.sha 1249
		$usersMap = array();
1250
		foreach($loanHistory AS $loanH){
1251
			if (!array_key_exists($loanH['user_id'], $usersMap)) {
1252
				$options = array('conditions'=>array('account_key'=>$loanH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
1253
				$userId = $this->UserAccount->find('first',$options);
1254
				$userId = $userId['UserAccount']['user_id'];
19731 naman 1255
				$opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>'first_name');
1256
				$userName = $this->User->find('first',$opts);
1257
				$usersName[$loanH['user_id']] = $userName['User']['first_name'];
18809 manish.sha 1258
				$usersMap[$loanH['user_id']]=$userId;
1259
			}
1260
		}
1261
 
19731 naman 1262
		$this->set(compact('usersName','loanHistory','usersMap','hasMore','totalCount','page'));
18809 manish.sha 1263
	}
19046 naman 1264
 
1265
	public function usernotification($user = null){
19206 naman 1266
		$android_id = $this->request->query('android_id');
1267
		$user_id = $this->request->query('user_id');
19098 naman 1268
		$page = $this->request->query('page');
1269
		if(!isset($page)){
1270
			$page = 1;
1271
		}
1272
		$limit = 20;
1273
		$offset = ($page - 1)*$limit;
19046 naman 1274
		$this->layout = 'innerpages';
19206 naman 1275
		$url = Configure::read('nodeurl')."/getAllNotifications?user_id=".$user_id."&android_id=".$android_id."&offset=".$offset."&limit=".$limit;
1276
		$noti= $this->make_request($url,null);
19238 manas 1277
		if(isset($noti) && !empty($noti)){
19206 naman 1278
			foreach ($noti as $nkey => $nval){
1279
				if($nval["status"] == "sent" || $nval["status"] == "recieved" || $nval["status"] == "failed"){
1280
					$noti[$nkey]['seen'] = false;
1281
				}
1282
				if($nval["status"] == "opened" || $nval["status"] == "referrer" || $nval["status"] == "login"){
1283
					$noti[$nkey]['seen'] = true;
1284
				}
1285
			}
19238 manas 1286
			$updateCountUrl = Configure::read('nodeurl')."/updateNotificationCount?user_id=".$user_id."&android_id=".$android_id;
1287
			$this->post_request($updateCountUrl,null);				
1288
		}
19318 naman 1289
		else{
1290
			$this->render('/Elements/nonotification');
1291
		}
19883 naman 1292
		$nexturl = "/users/getmorenotification?page=".($page+1)."&user_id=".$user_id."&android_id=".$android_id;
19098 naman 1293
		$this->set(compact('noti','nexturl'));
19046 naman 1294
	}
19098 naman 1295
 
1296
	public function getmorenotification(){
1297
		$this->layout = 'ajax';
1298
		$page = $this->request->query('page');
19883 naman 1299
		$android_id = $this->request->query('android_id');
1300
		$user_id = $this->request->query('user_id');
19098 naman 1301
		if(!isset($page)){
1302
			$page = 1;
1303
		}
1304
		$limit = 20;
1305
		$offset = ($page - 1)*$limit;
19206 naman 1306
		$url = Configure::read('nodeurl')."/getAllNotifications?user_id=".$user_id."&android_id=".$android_id."&offset=".$offset."&limit=".$limit;
1307
		$noti= $this->make_request($url,null);
1308
		if(isset($noti) && !empty($noti))
1309
		{
1310
			foreach ($noti as $nkey => $nval){
1311
				if($nval["status"] == "sent" || $nval["status"] == "recieved" || $nval["status"] == "failed"){
1312
					$noti[$nkey]['seen'] = false;
1313
				}
1314
				if($nval["status"] == "opened" || $nval["status"] == "referrer" || $nval["status"] == "login"){
1315
					$noti[$nkey]['seen'] = true;
1316
				}
1317
			}
1318
		}
19883 naman 1319
		$nexturl = "/users/getmorenotification?page=".($page+1)."&user_id=".$user_id."&android_id=".$android_id;
19098 naman 1320
		$this->set(compact('noti','nexturl'));
1321
		$this->render('/Elements/getnotification');
1322
	}
19206 naman 1323
 
1324
	public function sendseen($cid = null){
19213 manas 1325
 
1326
		$data = array();
1327
		$data['cid']=$cid;
1328
		$data['result']='opened';
1329
		$data['user_id']=$this->Auth->user('id');
1330
		$url = Configure::read('nodeurl')."/addPushNotificationByApk";//remove hardcoded value
1331
		$response = $this->post_request($url,$data);
1332
		if(!empty($response)){
1333
			$result = array('success' => true,'message'=>'The pushnotification has been saved.');
1334
		} else {
1335
			$result = array('success' => false,'message'=>'The pushnotification could not be saved. Please, try again.');
1336
		}		
1337
		$this->set(array(
1338
		    'result' => $result,
1339
		    '_serialize' => array('result')
1340
		));
1341
		$this->render('/Elements/json');	
19206 naman 1342
	}
19359 manas 1343
 
1344
	public function admin_target($userId=null){
1345
		$this->layout = "innerpages";
1346
		$user_id = $userId;
1347
		$cachekey = 'target-'.$user_id;
1348
		$getoffer = Cache::read($cachekey,'target');
1349
		$current_time = time();
1350
		$response = "";
1351
		if($getoffer === false){
1352
			$offerurl = $this->apihost."getOfferForUser/?user_id=".$user_id;
1353
			$response = $this->make_request($offerurl,null);
1354
			Cache::write($cachekey , $response ,'target');
19700 naman 1355
			if(empty($response)){
19359 manas 1356
					$response = "";
1357
				}
19700 naman 1358
 
19359 manas 1359
		}else{
1360
			if(!empty($getoffer)){
1361
					$response = $getoffer;
1362
				}
1363
		}
1364
 
1365
		$maxpercentage = 0;
1366
 
1367
		if(isset($response['target2_cash_back_percetage']) && !empty($response['target2_cash_back_percetage'])){
1368
			$maxpercentage = $response['target2_cash_back_percetage'];
1369
		}
1370
		else{
1371
			if(isset($response['target1_cash_back_percetage']) && !empty($response['target1_cash_back_percetage'])){
1372
				$maxpercentage = $response['target1_cash_back_percetage'];
1373
			}
1374
		}
1375
 
1376
 
1377
		$this->loadModel('User');
1378
		$user_email = "";
1379
		if($user_id != null || $user_id != ''){
1380
			$opt = array('conditions'=>array('id'=>$user_id),'recursive'=>-1,'fields'=>'email');
1381
			$usId = $this->User->find('first',$opt);
1382
			$user_email = $usId['User']['email'];
1383
		}
1384
		$this->set(compact('response','maxpercentage','user_email'));
1385
	}
19461 naman 1386
 
1387
	public function admin_userrefund(){
1388
		$id = $this->request->query('id');
1389
		$email = $this->request->query('email');
1390
		$phone = $this->request->query('mob'); 
1391
		$data = $this->request->data['UserRefund'];
1392
		if($this->request->is('post')){
1393
			$jsonVar = json_encode($data, JSON_NUMERIC_CHECK );
19477 naman 1394
			$url = $this->apihost."refundToWallet";
19461 naman 1395
			$response = $this->make_request($url, $jsonVar);
1396
			if ($response['result'] == 'success') {
1397
				$this->Session->setFlash("Query submitted. Pending for Approval.");
1398
				return $this->redirect(array('action' => 'admin_search'));
1399
			} else {
1400
				$this->Session->setFlash("Query not submitted");
1401
			}
1402
		}
1403
 
1404
		$this->set(compact('id','phone','email'));
1405
	}
19726 naman 1406
 
1407
	public function admin_userretailer()
1408
	{}
1409
 
1410
	public function admin_searchuserretailer()
1411
	{
1412
		$this->autoRender = false;
1413
		$this->request->onlyAllow ( 'ajax' );
1414
		$type = $this->request->query('type');
1415
		$search = $this->request->query('search');
1416
		$searchfor = $this->request->query('searchfor');
1417
		$this->User->recursive = -1;
1418
		$options = array('limit'=>100,'order'=>array('id'=>'desc'));
1419
 
1420
		$response = "";
1421
		if(!empty($type) && !empty($search)){			
1422
			if($searchfor == "usertype"){
1423
				$options['conditions'] = array($type.' LIKE '=>"%$search%");
1424
				$users = $this->User->find('all',$options);
1425
				$response = $users;
1426
			}elseif($searchfor == "retailertype"){
1427
				$this->loadModel('Retailer');
1428
				if($type=='contact'){
1429
					$options['conditions'] =array('OR'=>array('contact1 LIKE '=>"%$search%",'contact2 LIKE '=>"%$search%"));
1430
				}else{
1431
					$options['conditions'] = array($type.' LIKE '=>"%$search%");
1432
				}
1433
 
1434
				$users = $this->Retailer->find('all',$options);
1435
 
1436
				$response = $users;
1437
 
1438
			}
1439
 
1440
		}
1441
		return json_encode($response);
1442
	}
19738 naman 1443
 
1444
	public function admin_addretailer(){
1445
 
1446
 
1447
		if ($this->request->is('post')) {
19794 naman 1448
			$agentid = Configure::read('agentid');
19788 naman 1449
			$cur_date = date('Y-m-d H:i:s', time());
19738 naman 1450
			$data = $this->request->data['Retailer'];
19742 naman 1451
			$retailer['Retailer']['identifier'] = NULL;
19738 naman 1452
			$retailer['Retailer']['title'] = $data['storeName'];
1453
			$retailer['Retailer']['address'] = $data['completeAddress'];
1454
			$retailer['Retailer']['contact1'] = $data['mobileNumber'];
19742 naman 1455
			$retailer['Retailer']['status'] = "pending_verification";
19738 naman 1456
			$retailer['Retailer']['is_elavated'] = 1;
1457
			$retailer['Retailer']['pin'] = $data['pin'];
1458
			$retailer['Retailer']['city'] = $data['city'];
1459
			$retailer['Retailer']['state'] = $data['state'];
1460
			$retailer['Retailer']['retry_count'] = 0;
1461
			$retailer['Retailer']['invalid_retry_count'] = 0;
19742 naman 1462
			$retailer['Retailer']['call_priority'] = NULL;
19738 naman 1463
			$retailer['Retailer']['next_call_time'] = 0;
1464
			$retailer['Retailer']['is_std'] = 0;
1465
			$retailer['Retailer']['is_or'] = 0;
19772 naman 1466
			$retailer['Retailer']['disposition'] = "inbound_call";
1467
			$retailer['Retailer']['source'] = "inbound";
19742 naman 1468
			$retailer['Retailer']['created'] = $cur_date;
1469
			$retailer['Retailer']['modified'] = $cur_date;
1470
			$retailer['Retailer']['tinnumber'] = $data['tinNumber'];
1471
			$retailer['Retailer']['next_call_time'] = NULL;
19738 naman 1472
			$retailer['Retailer']['isvalidated'] = 0;
1473
 
19742 naman 1474
 
19738 naman 1475
			$this->loadModel('Retailer');
1476
			$this->Retailer->create();
19742 naman 1477
			if ($retdata = $this->Retailer->save($retailer)) {
19738 naman 1478
				$this->Session->setFlash(__('The user has been saved'));
19794 naman 1479
				$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 1480
				$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 1481
				$this->User->query($contactquery);
1482
				$this->User->query($callhistoryquery);
19749 naman 1483
				$this->redirect('userretailer');
19738 naman 1484
			} else {
1485
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
1486
			}
1487
		}
1488
	}
1489
 
1490
	public function getcode($id){
1491
		$this->autoRender = false;
1492
		$this->request->onlyAllow('ajax');
19807 naman 1493
		$agentid = Configure::read('agentid');
19794 naman 1494
		$url = $this->apihost."getDtrLink/".$agentid."/fresh/".$id;
19738 naman 1495
		$response = $this->make_request($url,null); 
1496
 
1497
		return json_encode($response['result']);
1498
 
1499
	}
19892 manas 1500
 
1501
	public function admin_outstanding($type,$userId=null) {
1502
		$url = Configure::read('saholicapihost').'counter!getOutstandingLoans?fetchType='.$type;
1503
		if(isset($userId)){
1504
			$url = $url.'&userId='.$userId;
1505
		}
1506
		$response = $this->make_request ( $url, null );
1507
		$outstandingPayments = $response['response'];
1508
		$usersName = array();
1509
		$usersMap = array();
1510
		$this->loadModel('UserAccount');
1511
		foreach($outstandingPayments AS $loanH){
1512
			if (!array_key_exists($loanH['user_id'], $usersMap)) {
1513
				$options = array('conditions'=>array('account_key'=>$loanH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
1514
				$userId = $this->UserAccount->find('first',$options);
1515
				$userId = $userId['UserAccount']['user_id'];
1516
				$opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>array('first_name','email'));
1517
				$userName = $this->User->find('first',$opts);
1518
				$usersName[$loanH['user_id']] = $userName['User']['first_name'];
1519
				$usersMap[$loanH['user_id']]=$userName['User']['email'];
1520
			}
1521
		}
1522
		$this->set(compact('usersName','outstandingPayments','usersMap'));
1523
		if($type=='credit'){
1524
			$this->render('admin_outstandingcredits');
1525
		}
1526
	}
19929 manas 1527
 
1528
	public function admin_marksettlement(){
1529
		if(empty($this->request->data['repayment_date']) || empty($this->request->data['amount'])){
1530
			$message = "Please fill a valid date or amount for the settlement";
1531
		}
1532
		elseif ($this->request->data['amount']<=0){
1533
			$message = "Please check the amount that you filled earlier";
1534
		}else{
1535
			$payload = $this->request->data;
1536
			$url = Configure::read('saholicapihost').'counter!markOutstandingPaymentsAsSettled?settlement='.json_encode($payload,JSON_NUMERIC_CHECK);
1537
			$response = $this->make_request($url,json_encode($payload,JSON_NUMERIC_CHECK));
1538
			$message = $response['response'][key($response['response'])];
1539
		}
1540
		$this->set(compact('message'));
1541
	}
19892 manas 1542
}