Subversion Repositories SmartDukaan

Rev

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