Subversion Repositories SmartDukaan

Rev

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