Subversion Repositories SmartDukaan

Rev

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