Subversion Repositories SmartDukaan

Rev

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