Subversion Repositories SmartDukaan

Rev

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