Subversion Repositories SmartDukaan

Rev

Rev 20132 | Rev 20316 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
App::uses('AppController', 'Controller');
App::uses('ConnectionManager', 'Model');
/**
 * Users Controller
 *
 * @property User $User
 */

set_time_limit(0);

class UsersController extends AppController {

        public $components = array('SignMeUp.SignMeUp','RequestHandler','Cookie','Paginator');

    public function beforeFilter() {
        parent::beforeFilter();
        // $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
        $this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'display','home');
        $this->Auth->allow(array('mine','login', 'forgotten_password', 'register', 'activate', 'checkemail','checkfbuser','registertwitteruser','skipmobileverification','reauthenticate','edit','mywallet','admin_push','socialauth','oneringcb','sendseen','cartdetails')); 
                $this->Cookie->name = 'profittill';
                $this->Cookie->time = 86400*30; 
                $this->Cookie->path = '/';
                $this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#H23s~#^';
                $this->Cookie->httpOnly = true;
    }
    
        public function oneringcb() {
                $this->log(print_r($_REQUEST,1),'onering');
                $this->layout = "ajax";
                $this->response->type('json');
                $this->set(array(
                    'result' => $result,
                    '_serialize' => array('result')
                )); 
                $this->render('/Elements/json');
        }

        public function mywallet() {
                $userId = $this->request->query('user_id');
                $tokenValidated = $this->checkToken($userId);
                if(isset($userId) && !empty($userId) && $tokenValidated==1){    
                        $next = "/my-wallet";                                   
                        $redirectUrl = $this->getAutoLoginUrl($userId,$next);
                        $this->log($redirectUrl,'headers');
                        $this->layout = 'innerpages';
                        $this->set(compact('redirectUrl'));
                }else{
                        if($tokenValidated == 0){
                                $this->redirect(array('controller'=>'special','action'=>'native','login'));
                        }elseif($tokenValidated == -1){
                                $this->redirect(array('controller'=>'abouts','action'=>'askforupdate'));
                        }
                }
        }

        public function socialauth() {
                $this->layout = "ajax";
                $this->log(print_r($this->request->data,1),'socialauth');
        }

        public function mine() {
                $this->response->type('json');
                $this->layout = 'ajax';
                $userId = $this->request->query('user_id');
                if(isset($userId) && !empty($userId)){
                        $this->loadModel('User');
                        $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',
                                'city','state','pincode','referrer'),'recursive'=>-1);
                        $user = $this->User->find('first',$options);
                        $result = $user['User'];
                }
                $this->set(array(
                    'result' => $result,
                    '_serialize' => array('result')
                )); 
                $this->render('/Elements/json'); 
        }

        function registertwitteruser(){
                $this->twitterObj->setToken($_GET['oauth_token']);
                $token = $this->twitterObj->getAccessToken();
                $this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
                $twitterInfo= $this->twitterObj->get_accountVerify_credentials();
                $data = array();
                $data['twitter_id'] = $twitterInfo->id;         
                $this->Session->write('twtusername',$twitterInfo->screen_name);
                $data['twitter_token'] = $token->oauth_token;
                $data['twitter_secret'] = $token->oauth_token_secret;
                $data['twitter_screen_name'] = $twitterInfo->screen_name;                                       
                $data['active'] = 1;

                $id = $this->Auth->user('id');
                if(!isset($id) || $id == ''){
                //      $count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
                        $user = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
                        //if($count<1){
                        if(empty($user)){
                                $this->User->create();
                                $this->User->save($data);
//                              $dbuser = $this->User->read(null,$this->User->id);
                                $this->Auth->login($this->User->data);
                        }else{
                //              $data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
                                $this->Auth->login($user['User']);
                        }
                }else{
                        //$data['id'] = $this->Auth->user('id');
                        $user = $this->Auth->user;
//                      $this->User->save($data);
//                      $this->Auth->login($data);
                }                
                $user = $this->User->read(null, $this->Auth->User('id'));
                if ($user['User']['group_id'] == 1) {
                        //$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
                        header('location:users/dashboard?userid='.$this->Auth->user('id'));
                        exit();
                }
                elseif ($user['User']['group_id'] == 2) {
                        $this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
                        exit();
                }
        }

    public function checkfbuser($accessToken=null){
                $sessionState = $this->Session->read('state');
                if($sessionState != $_GET['state']) {
                        $this->redirect(array('controller'=>'users','action'=>'login'));
                }
                else {
                        if(isset($_GET['code'])){
                                $code = $_GET['code'];
                                $facebookConfig = Configure::read("Facebook");          
                                $token_url = "https://graph.facebook.com/oauth/access_token?"
                               . "client_id=" . $facebookConfig['fbappid'] . "&redirect_uri=" . urlencode($facebookConfig['base_url'].'/users/checkfbuser/')
                               . "&client_secret=" . $facebookConfig['secret'] . "&code=" . $code;

                            $response = file_get_contents($token_url);
                            $params = null;
                            parse_str($response, $params);
                            $accessToken = $params['access_token'];
                        }else{
                                $this->redirect(array('controller'=>'users','action'=>'login'));
                        }
                }
                $this->User->recursive = -1;
                if (!$accessToken) {
                    $this->redirect(array('controller'=>'users','action'=>'login'));
                    //$this->redirect(array('controller'=>'pages','action'=>'display','home'));
                }        
                if (isset($accessToken) && $accessToken != 'undefined') {                       

                    $graph_url = "https://graph.facebook.com/me?access_token=" . $accessToken;

                    $user = json_decode(file_get_contents($graph_url));
                        $this->log("FB user = ".print_r($user,1),'fb');
                    if (!empty($user)) {
                        if (!$this->isAuthorized()) {
                            $id = $this->User->checkFbUser($user,$accessToken);
                                $dbuser = $this->User->findById($id);
                            $this->Session->write('facebook_id',$user->id);
                                $this->Auth->login($dbuser['User']);
                                if($this->Auth->login()){
                                        $this->log("logged = ".print_r($this->Auth->user('id'),1)."\n",'fb');
                                }
                            $next = $this->Session->read('next');
                                $this->log("next= ".$next."\n",'fb');
                        
                            if (!empty($next)) {
                                        header('Location:' . $next);
                                        exit();
                            }else {
                                        //$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
                                        header('location:users/dashboard?userid='.$this->Auth->user('id'));
                                        exit();
                                    }
                                        //$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
                                        header('location:users/dashboard?userid='.$this->Auth->user('id'));
                                        exit();
                                } else {                        
                                        //$this->redirect(array('controller'=>'users','action'=>'dashboard','?userid='.$this->Auth->user('id')));
                                        header('location:users/dashboard?userid='.$this->Auth->user('id'));
                                        exit();
                                }
                    }
                }
    }

        public function uploadavatar(){
                $this->log(print_r($_FILES,1),'debug');
                $path = "img/avatars/";
                $valid_formats = array("jpg", "png", "gif", "bmp");
                if ($this->request->is('post')) {
                        $name = $_FILES['photoimg']['name'];
                        $size = $_FILES['photoimg']['size'];
                        
                        if(strlen($name))
                                {
                                        list($txt, $ext) = explode(".", $name);
                                        if(in_array($ext,$valid_formats))
                                        {
                                        if($size<(1024*1024))
                                                {
                                                        $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                                                        $tmp = $_FILES['photoimg']['tmp_name'];
                                                        if(move_uploaded_file($tmp, $path.$actual_image_name))
                                                                {
                                                                        echo "<img width='250' src='../".$path.$actual_image_name."'  class='preview'>";
                                                                        echo "<input type='hidden' id='imageUrl' name='photo_url' value='".'http://' . $_SERVER['SERVER_NAME'] . Router::url('/').$path.$actual_image_name."'></input>";
                                                                }
                                                        else
                                                                echo __('Upload Failed');
                                                }
                                                else
                                                echo __("Maximum allowed image file size is 1 MB");                                     
                                                }
                                                else
                                                echo __("Invalid file format"); 
                                }
                        else
                                echo __("Please select image");
                        exit;
                }
        }

    function checkemail() {
        $this->User->recursive = -1;
        $this->layout = 'ajax';
        if (!empty($this->params['url']['data']['User']['email'])) {
            $username = $this->params['url']['data']['User']['email'];
        } elseif (!empty($this->params['url']['data']['Doctor']['email'])) {
            $username = $this->params['url']['data']['Doctor']['email'];
        } else {
            $result = false;
            $this->set('result', $result);
        }
        if ($this->Auth->user('id') != null) {
            $conditions = array('User.email' => $username, 'User.id !=' => $this->Auth->user('id'));
        } else {
            $conditions = array('User.email' => $username);
        }
        $count = $this->User->find('count', array('conditions' => $conditions));
        if ($count > 0) {
            $result = false;
        } else {
            $result = true;
        }
        $this->set('result', $result);
    }

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function view($id = null) {
                $this->response->type('json');
                $this->layout = 'ajax';
                $callback = $this->request->query('callback');
                $this->User->id = $id;
                if (!$this->User->exists()) {
                        throw new NotFoundException(__('Invalid user'));
                }
                $user = $this->User->find('first', array('conditions' =>array('id' => $id),'recursive'=>-1));
                $result = array('user'=>$user);
                $this->set(array(
                    'result' => $result,
                    'callback' => $callback,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }
/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */

    public function edit($id = null) {
                $this->log(print_r($this->request->data,1),'mydetails');
                $this->response->type('json');
                $this->layout = 'ajax';
                $this->User->recursive = -1;
                $updateRequired = true;
        if (!$this->User->exists($id)) {
                        $result = array('success'=>false,'message'=>'Invalid user');
                } else {
                if ($this->request->is('post') || $this->request->is('put')) {
                        if(!empty($this->request->data['mobile_number']) && empty($this->request->data['mobile_verified'])) {
                                        $options = array('conditions'=>array('User.id'=>$id),'fields'=>array('mobile_number'),'recursive'=>-1);
                                        $oldMobile = $this->User->find('first',$options);
                                        if($this->request->data['mobile_number'] != $oldMobile['User']['mobile_number']) {
                                        $this->request->data['mobile_verified'] = 0;
                                        if($oldMobile['User']['activated']==0){
                                                $this->request->data['status'] = 1;
                                        }
                                        }

                        }
                        if(!empty($this->request->data['referrer'])) {
                                $referrer = $this->request->data['referrer'];
                                $this->log(print_r($referrer,1),'activations');
                                $this->loadModel('ActivationCode');
                                $opt['conditions'] = array('code' => strtoupper($referrer) , 'status'=> 0 );
                                $exists = $this->ActivationCode->find('first',$opt);
//                              $exists = $this->ActivationCode->findByCode(strtoupper($referrer));
                                $this->log(print_r($exists,1),'activations');
                                if(empty($exists)){
                                        $result = array('success'=>false,'message'=>'Invalid referral code');
                                        // unset($this->request->data['referrer']);
                                        $updateRequired = false;
                                } else {
                                        $this->request->data['activated'] = 1;                  
                                }                                       
                        }                               
                        /*if(!empty($this->request->data['address_line_1']) || !empty($this->request->data['address_line_2']) || !empty($this->request->data['pincode']) ){
                                $checkQuery = "select * from all_user_addresses where source='user_profile' and user_id=".$this->request->data['id'];
                                        $result  = $this->User->query($checkQuery);             
                                        if(empty($result)){
                                                $inserQuery = "insert into all_user_addresses (user_id,address,store_name,city,pincode,source,created) values ('".$this->request->data['id']."',CONCAT('".$this->request->data['address_line_1']."',' ','".$this->request->data['address_line_2']."'),'".$this->request->data['first_name']."','".$this->request->data['city']."','".$this->request->data['pincode']."','user_profile',now() )";
                                                $result  = $this->User->query($inserQuery);                     
                                        }else{
                                                $updateQuery = "update all_user_addresses set address=CONCAT('".$this->request->data['address_line_1']."',' ','".$this->request->data['address_line_2']."'), pincode='".$this->request->data['pincode']."', city='".$this->request->data['city']."',store_name='".$this->request->data['first_name']."' where source='user_profile' and user_id=".$this->request->data['id'];
                                                $result  = $this->User->query($updateQuery);                    
                                        }       
                        }*/

                        if($updateRequired){
                            if ($this->User->save($this->request->data)) {
                                if($this->request->data['activated'] == 1) {
                                        //Call user activation api
                                                $this->markUserActivated($id);
                                                $ignorereferrer = Configure::read('referrercode');
                                                if(in_array(strtoupper($referrer) , $ignorereferrer)){
                                                }else{
                                                        $upstatus = "update activation_codes set status = 1 where code = '".strtoupper($referrer)."'";
                                                        $this->User->query($upstatus);
                                                }
                                }                                               
                                $result = array('success'=>true,'message'=>'Your profile has been saved');
                            } else {
                                $result = array('success'=>false,'message'=> 'The user could not be saved. Please, try again.');
                            }
                        }
                }  
            }
        $this->set(array(
                    'result' => $result,
                    '_serialize' => array('result')
                )); 
                $this->render('/Elements/json');      
    }

/**
 * admin_index method
 *
 * @return void
 */

        public function admin_pushnotifications(){
                if ($this->request->is('post')) {
                        $sql = $this->request->data['User']['sql'];
                        if(!empty($sql)){
                                $users = $this->User->query($sql);
                                $this->set(compact('users'));
                        }
                }
        }

        public function generateAffiliateUrl($url,$user_id,$store){
                //Get StoreProduct Info         
                $storeId = $store['Store']['id'];
                $prefix = "SHA".$storeId;
                $tag = $prefix.time();
                if($storeId == 2){                              
                        $url = str_replace('www','m',$url);
                } elseif($storeId == 3) {
                        $url_parts = parse_url($url);
                        $url_parts['path'] = str_replace('viewAllSellers/','',$url_parts['path']);//quickfix for snapdeal
                        if(isset($url_parts['query'])) {
                                $url = "http://m.snapdeal.com".$url_parts['path'].'?'.$url_parts['query']."&utm_source=aff_prog&utm_campaign=afts&offer_id=17";
                        }else{
                                $url = "http://m.snapdeal.com".$url_parts['path'].'?utm_source=aff_prog&utm_campaign=afts&offer_id=17';
                        }
                } elseif($storeId == 4){
                        $next = str_replace('www','m',$url);    
                        $url = $this->getAutoLoginUrl($userId,$next);
                        $url .= '?utm_source=profitmandi';
                }
                if( strpos($url, '?') === false ) {
                        $firstChar = '?';
                } else {
                        $firstChar = '&';
                }
                $url .= $firstChar.$store['Store']['affid_param'].'='.$store['Store']['affiliate_id'];
                if(!empty($store['Store']['sub_tag_param'])){
                        $url .= '&'.$store['Store']['sub_tag_param'].'='.$tag;
                }
                $extras = array('store'=>$store['Store']['name'],'source'=>'notification');
                $data = array('user_id' => $user_id,'store_product_id'=>0,'tag'=>$tag,'url'=>$url,'price'=>0,'extras'=>json_encode($extras));
                $this->loadModel('Click');
                $this->Click->create();
                $this->Click->save($data);
                return $url;
        }

        public function admin_push(){
                if ($this->request->is('post')) {
                        if(empty($this->request->data['userIds'])){
                                $this->Session->setFlash(__('Please choose a few users'));
                                $this->redirect(array('action' => 'admin_pushnotifications'));
                        }else{
                                $this->log(print_r($this->request->data,1),'pushnotifications');
                                $message = $this->request->data['User'];
                                $this->loadModel('NotificationCampaign');
                                $this->NotificationCampaign->create();
                                $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']);
                                if($this->NotificationCampaign->save($data)){
                                        $message['cid'] = $this->NotificationCampaign->getLastInsertId();
                                } else{
                                        $message['cid'] = $message['name'];
                                }
                                /*                              
                                if($message['type'] == 'url' && !empty($message['url'])) {
                                        $url = $message['url'];
                                        $this->loadModel('Store');
                                        $store = $this->Store->getByUrl($url);                                  
                                        $message['url'] = $this->generateAffiliateUrl($url,$value,$store);
                                }                               
                                $this->loadModel('GcmUser');
                                foreach ($this->request->data['userIds'] as $key => $value) {                                   
                                        $options = array('conditions'=>array('user_id'=>$value),'fields'=>array('gcm_regid'),'order'=>array('id'=>'desc'));
                                        $gcmUser = $this->GcmUser->find('first',$options);
                                        $regIds = array($gcmUser['GcmUser']['gcm_regid']);
                                        // $message = array('message'=>$this->request->data['User']['message']);                                        
                                        if($message['type'] == 'url' && !empty($message['url'])) {
                                                $message['url'] = $this->generateAffiliateUrl($url,$value,$store);
                                        }                                       
                                        $this->send_push_notification($regIds,$message,$value);
                                }
                                */
                                $sentUsers = array();
                                $payload = array();
                                foreach ($this->request->data['userIds'] as $key => $value) {   
                                        if(!in_array($value, $sentUsers)) {
                                                $sentUsers[] = $value;                                                          
                                                $data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$value,'type'=>'pending','status'=>0);                                             
                                                $payload[] = $data;
                                        }
                                }
                                $url = Configure::read('nodeurl')."/addPushNotification";
                                $this->make_request($url,json_encode($payload,JSON_NUMERIC_CHECK));
                        }
                }
        }
        
        private function send_push_notification($registatoin_ids, $message, $user_id) {
                $msg = array(
                    'message'       => $message['message'],
                    'cid'               => $message['cid'],
                    'title'         => $message['title'],
                    'type'              => $message['type'],
                    'url'                   => $message['url'],
                    // 'expiresat'          => strtotime($message['expiresat']),
                    'vibrate'       => 1,
                    'sound'         => 1,
                    'largeIcon'     => 'large_icon',
                    'smallIcon'     => 'small_icon'
                );
                // Set POST variables
                $url = 'https://android.googleapis.com/gcm/send';

                $fields = array(
                    'registration_ids' => $registatoin_ids,
                    'data' => $msg,
                );
                $headers = array(
                    'Authorization: key=' . Configure::read('googleapikey'),
                    'Content-Type: application/json'
                );
                //print_r($headers);
                // Open connection
                $ch = curl_init();

                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                // Disabling SSL Certificate support temporarly
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

                // Execute post
                $result = curl_exec($ch);
                if ($result === FALSE) {
                    die('Curl failed: ' . curl_error($ch));
                }
                $res = json_decode($result,1);

                $this->loadModel('Pushnotification');
                if($res['success']==1){
                                        $data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>'success');
                                }else if($res['success']==0){
                                        $error_message=$res['results'][0]['error'];
                                        $sqlQuery="update gcm_users set failurecount=failurecount+1 where gcm_regid='".$registatoin_ids[0]."'";
                                        $resultData=$this->GcmUser->query($sqlQuery);
                                        $data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'type'=>'sent','status'=>$res['success'],'message'=>$error_message);
                                }
                #$data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
                $this->Pushnotification->create();
                $this->Pushnotification->save($data);
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($data,1),'pushnotifications');
                // Close connection
                curl_close($ch);
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
        }

        public function admin_index() {
                $this->User->recursive = 0;
                $options = array('limit'=>20,'order'=>array('id'=>'desc'));
                $this->Paginator->settings = $options;
                $users = $this->Paginator->paginate();

                $groups = $this->User->Group->find('list');
                
                $postOfficeQuery="select pincode,state from postoffices group by pincode";
                $postOfficeResult=$this->User->query($postOfficeQuery);
                $postOffice=array();
                foreach($postOfficeResult as $value){
                        $postOffice[$value['postoffices']['pincode']]=$value['postoffices']['state'];
                }
                foreach ($users as $key => $value) {
        $userId=$value['User']['id'];
        $masterQuery="select u.id,rl.retailer_id,r.state,r.city,r.pin,
                                        ra.state,ra.city,ra.pin,
                                        u.state,u.city,u.pincode,
                                        ua.state,ua.city,ua.pincode 
                                        from retailers r left  join retaileraddresses ra  on r.id=ra.retailer_id  
                                        join retailerlinks rl on r.id=rl.retailer_id 
                                        right join users u on rl.user_id=u.id 
                                        left join user_addresses ua on u.id=ua.user_id 
                                        where u.id=$userId";
        $retailerAddress=$this->User->query($masterQuery);
        $users[$key]['User']['retailer_id']=$retailerAddress[0]['rl']['retailer_id'];   
        if($retailerAddress[0]['ra']['city']==null && $retailerAddress[0]['ra']['state']==null && $retailerAddress[0]['ra']['pin']==null){
                if($retailerAddress[0]['r']['city']==null && $retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']==null){
                        if($retailerAddress[0]['ua']['city']==null && $retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']==null){
                                if($retailerAddress[0]['u']['city']==null && $retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']==null){

                                }else{
                                        if($retailerAddress[0]['u']['state']==null && $retailerAddress[0]['u']['pincode']!=null){
                                                $users[$key]['User']['state']=$postOffice[$retailerAddress[0]['u']['pincode']];         
                                        }else{
                                                $users[$key]['User']['state']=$retailerAddress[0]['u']['state'];        
                                                $users[$key]['User']['city']=$retailerAddress[0]['u']['city'];  
                                }       
        
                                }
                        }
                        else{
                                if($retailerAddress[0]['ua']['state']==null && $retailerAddress[0]['ua']['pincode']!=null){
                                        $users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pincode']];         
                                }else{
                                        $users[$key]['User']['state']=$retailerAddress[0]['ua']['state'];       
                                        $users[$key]['User']['city']=$retailerAddress[0]['ua']['city']; 
                                }       
                        }
                }
                else{
                        if($retailerAddress[0]['r']['state']==null && $retailerAddress[0]['r']['pin']!=null){
                                $users[$key]['User']['city']=$retailerAddress[0]['r']['city'];  
                                $users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];             
                        }else{
                                $users[$key]['User']['state']=$retailerAddress[0]['r']['state'];        
                                $users[$key]['User']['city']=$retailerAddress[0]['r']['city'];  
                        }               
                }
        }else{
                if(($retailerAddress[0]['ra']['state']==null || empty($retailerAddress[0]['ra']['state'])) && $retailerAddress[0]['ra']['pin']!=null){
                        $users[$key]['User']['city']=$retailerAddress[0]['ra']['city']; 
                        $users[$key]['User']['state']=$postOffice[$retailerAddress[0]['r']['pin']];             
                }else{
                        $users[$key]['User']['state']=$retailerAddress[0]['ra']['state'];       
                        $users[$key]['User']['city']=$retailerAddress[0]['ra']['city']; 
                }               
        }
}
        
        $this->set(compact('groups','users'));  
}

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_view($id = null) {
                $this->User->id = $id;
                if (!$this->User->exists()) {
                        throw new NotFoundException(__('Invalid user'));
                }
                $this->set('user', $this->User->read(null, $id));
        }

/**
 * admin_add method
 *
 * @return void
 */
        public function admin_add() {
                if ($this->request->is('post')) {
                        $this->User->create();
                        if ($this->User->save($this->request->data)) {
                                $this->Session->setFlash(__('The user has been saved'));
                                $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                        }
                }
                $groups = $this->User->Group->find('list');
                $this->set(compact('groups'));
        }

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_edit($id = null) {
                $this->User->id = $id;
                if (!$this->User->exists()) {
                        throw new NotFoundException(__('Invalid user'));
                }
                if ($this->request->is('post') || $this->request->is('put')) {
                        if ($this->User->save($this->request->data)) {
                                $this->Session->setFlash(__('The user has been saved'));
                                $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                        }
                } else {
                        $this->request->data = $this->User->read(null, $id);
                }
                $groups = $this->User->Group->find('list');
                $this->set(compact('groups'));
        }

/**
 * admin_delete method
 *
 * @throws MethodNotAllowedException
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
/*
        public function admin_delete($id = null) {
                if (!$this->request->is('post')) {
                        throw new MethodNotAllowedException();
                }
                $this->User->id = $id;
                if (!$this->User->exists()) {
                        throw new NotFoundException(__('Invalid user'));
                }
                if ($this->User->delete()) {
                        $this->Session->setFlash(__('User deleted'));
                        $this->redirect(array('action' => 'index'));
                }
                $this->Session->setFlash(__('User was not deleted'));
                $this->redirect(array('action' => 'index'));
        }
*/

        public function admin_search() {
                $type = $this->request->query('type');
                $search = $this->request->query('search');
                $this->User->recursive = -1;
                $options = array('limit'=>100,'order'=>array('id'=>'desc'));
                if($type == 'unactivated'){
                        $options['conditions'] = array('activated' =>0);
                }
                else if(!empty($type) && !empty($search)){
                        if($type=='id'){
                                $options['conditions'] = array($type =>$search);                        
                        }else{
                                $options['conditions'] = array($type.' LIKE '=>"%$search%");                    
                        }
                }else{
                        $options['conditions'] = array('date(User.created)'=>date('Y-m-d',time()));                     
                }       
                // $db = ConnectionManager::getDataSource("default"); // name of your database connection
                // $last_act = $db->fetchAll("SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ");
                $sql = "SELECT * from (SELECT * from daily_visitors order by visited desc) as x group by x.user_id ";
                $last_act = $this->User->query($sql);
                // debug($last_act);
                $last_act_user_id = array();
                $last_activated = array();
                foreach ($last_act as $key => $row) {
                        // echo $key;
                        foreach ($row as $key => $value) {
                                $last_activated['visited'] = $value['visited'];
                                $last_act_user_id[$value['user_id']] = $last_activated['visited'];
                        }
                }
                // debug($last_act_user_id);
                $this->set(compact('last_act_user_id'));
                $options['fields'] = array('id','email','first_name','referrer','utm_source','utm_medium','utm_term','utm_campaign','mobile_number','activated','User.created','Appacl.access');
                $options['joins'] = array(
                    /*array('table' => 'useractive',
                        'alias' => 'Useractive',
                        'type' => 'LEFT',
                        'conditions' => array(
                            'Useractive.user_id = User.id',
                        )
                    ),*/
                    array('table' => 'appacls',
                        'alias' => 'Appacl',
                        'type' => 'LEFT',
                        'conditions' => array(
                            'Appacl.user_id = User.id',
                        )
                    )
            );
                $this->Paginator->settings = $options;
                $users = $this->Paginator->paginate();          
                foreach ($users as $key => $value) {
                        $userId = $value['User']['id'];
                        $quer= "select r.retailer_id,a.name from retailerlinks r join agents a on r.agent_id=a.id where user_id=$userId";
                        $res = $this->User->query($quer);
                        /*$last_act= "select last_active from useractive where user_id=$userId";
                        $res_last = $this->User->query($last_act);*/
                        if(empty($res)){
                                $users[$key]['User']['retailer_id']=""; 
                                $users[$key]['User']['agent_name']="";  
                        }else{
                                $users[$key]['User']['retailer_id']=$res[0]['r']['retailer_id'];        
                                $users[$key]['User']['agent_name']=$res[0]['a']['name'];        
                        }
                        /*if(empty($res_last)){
                                $users[$key]['User']['last_active']="";
                        }else{
                                $users[$key]['User']['last_active']=$res_last[0]['useractive']['last_active'];
                        }*/
                        
                }

                $this->set(compact('users'));   
        }

        public function dashboard() {
                App::uses('CakeTime', 'Utility');
                $user = $this->User->read(null,$this->Auth->user('id'));
                $this->set('user',$user);
                $this->set('title_for_layout', "Dashboard");
        }

/**
* user authentication funtions
*/
        public function register() {
                $referrer = $this->request->query('referrer');
                $this->log('referrer = '.$referrer);
                $this->Cookie->write('referrer',$referrer);
                $this->layout = 'auth';
                $this->set('title_for_layout','Register your free letushaggle.com account');
                $this->SignMeUp->register();
        }

        public function activate() {
                $this->layout = 'auth';
                $this->set('title_for_layout','Activate your copublish.in account');
                $this->SignMeUp->activate();
        }

        public function forgotten_password() {
                $this->layout = 'auth';
                $this->set('title_for_layout','Reset your copublish.in password');
                $this->SignMeUp->forgottenPassword();
        }       

        public function login() {
                // $db = ConnectionManager::getDataSource("default"); // name of your database connection
                // $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 ");
                // debug($rest);

                $this->layout = 'auth';
                if (!empty($this->data['User']['next'])) {
                    $next = $this->data['User']['next'];
                    $this->Session->write('next', $next);
                } elseif (!empty($this->params['url']['next'])) {
                    $next = $this->params['url']['next'];
                    $this->Session->write('next', $next);
                }
                if ($this->Auth->login()) {
                        
                    $next = $this->Session->read('next');
                    if (!empty($next)) {
                                header('location:' . $next);
                                exit();
                    }
                    $user = $this->User->read(null, $this->Auth->User('id'));           
                    // debug($user['User']['group_id']);
                 //    session_start();
                 //    $_SESSION["group_id"] = $user['User']['group_id'];

                 //    $this->loadModel('Acl');
                        // $resul = $this->Acl->find('all', array('conditions' => array('group_id' => $_SESSION["group_id"]),'fields'=>('action')));
                        // $_SESSION["permitted_action"] = $resul;

                        // debug($_SESSION["permitted_action"]);
                    // echo $_SESSION["group_id"];
                        if ($user['User']['group_id'] == 1) {
                                $this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
                                exit();
                        }
                        else if ($user['User']['group_id'] >= 2 && $user['User']['group_id']<99) {
                                $this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
                                exit();
                    }
                } else {
                    if (!empty($this->data)) {                
                                $this->Session->setFlash(__('Invalid username or password'),'error_message');
                    }
                }
                $this->set('title_for_layout', "Login to letushaggle.com");
        }

        public function logout() {
                // session_unset("group_id"); 
                // session_unset("permitted_action");
                // session_destroy("");
                // echo "Group Id" , $_SESSION["group_id"];
                $this->Session->setFlash(__('You have been logged out now'),'success_message');
                $this->redirect($this->Auth->logout());
        }

        public function updatetimezone() {
                $this->layout = 'ajax';         
                $timezone = $_GET['tz'];
                Configure::load('constant');
                $timeZones = Configure::read("timeZones");
                $query = "UPDATE users SET user_timezone = $timezone WHERE id = ".$this->Auth->User('id');
                if($this->User->query($query)){
                        $result = array('success' => true,'tz' => $timeZones[$timezone]);
                }else{
                        $result = array('success' => false);
                }
                $this->set('result',$result);
        }

        public function verifymobile() {
                $this->layout = 'innerpages';
        }

        public function getdial2verifynumber() {
                $TelNumber=substr($this->request->data("phone_number"),-10);

          // Replace with your Dial2Verify API Passkey generated using ( http://kb.dial2verify.in/?q=5 )
            $API_KEY = Configure::read("dial2verifyapikey");
  
                //Get API Image Response
            $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";
            // $json=file_get_contents($APIUrl);
            $json = json_encode($this->make_request($url,null));
                $this->response->type('json');
                $this->layout = 'ajax';
            echo($json);die;
        }

        public function getdial2verifystatus() { 

                $SID=$_REQUEST["SID"];
    
            $json = array();
                $VerificationCall="http://engine.dial2verify.in/Integ/UserLayer/DataFeed_APIV2.dvf?SID=$SID";

           // Make a call to Dial2Verify API & Parse The JSON Response
                // $RequestPayload=json_decode(file_get_contents($VerificationCall),true);
                $RequestPayload = $this->make_request($VerificationCall,null);
                // $RequestPayload = json_decode($response,true);

                $VerifStatus=$RequestPayload["VerificationStatus"];
             
                $json["VerificationStatus"]=$VerifStatus;
                
                $this->response->type('json');
                $this->layout = 'ajax';
            echo(json_encode($json));die;
        }

        public function skipmobileverification() {
                $this->Session->write('skipmobileverification',1);
                $this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
        }

        public function reauthenticate($userId) {
                $user = $this->User->read(null,$userId);
                $this->Auth->login($user['User']);
                $json = array('success'=>true);
                $this->response->type('json');
                $this->layout = 'ajax';
            echo(json_encode($json));die;
        }

        public function getlinks($userId) {     
                $cachekey = 'userlinks-'.$userId;
                $links = Cache::read($cachekey,'day');
                if(empty($links)) {
                        $links[3] = $this->getCatergoryLinks($userId,3);
                        $links[5] = $this->getCatergoryLinks($userId,5);
                        Cache::write($cachekey,$links,'day');
                }
                if ($this->request->is('requested')) {
            return $links;
        }
        $this->set('links', $links);
        }

        public function getCatergoryLinks($userId,$categoryId) {
                $temp = $links = $fixed = $random = array();            
                //populate fixed brands array
                if($categoryId == 3){
                        $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";
                } else {
                        $sql = "SELECT id,name FROM brands WHERE lower(name) IN('lenovo','dell','hp','iball','digiflip','samsung','datawind','apple','micromax','asus') AND category_id = $categoryId";
                }
                $brandnames = $this->User->query($sql);
                
                if(!empty($brandnames)){
                        foreach ($brandnames as $key => $value) {
                                if($categoryId == 3){
                                        if($value['brands']['name'] == 'Samsung' || $value['brands']['name'] == 'Micromax'){
                                                $fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
                                                // fixed for samsung and micromax
                                        } else {
                                                $temp[] = $value['brands']; //Any three brand except the above.
                                        }                                                       
                                }else{
                                        if($value['brands']['name'] == 'Dell' || $value['brands']['name'] == 'Lenovo'){
                                                $fixed[$value['brands']['name']] = "?filter=brand&brands=".$value['brands']['id'];
                                        } else {
                                                $temp[] = $value['brands'];
                                        }                                                       
                                }                       
                        }               
                }

                $rand_keys = array_rand(array_keys($temp), 3);
                $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";
                
                $brands = $this->User->query($sql);
                
                $count = 0;
                $iterate= 0;
                if(!empty($brands)){
                        foreach ($brands as $key => $brand) {
                                if($key>2 && !empty($temp))continue;
                                $links[$categoryId][$brand['u']['brand']] = "?filter=brand&brands=".$brand['b']['id'];
                        }
                        
                        if(!empty($temp)){
                                // for($i=0;$i<2;$i++) {//if brand in array and in while loop. first fix loop and then random.
                                //      $links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];
                                //      echo "temp", $links[$categoryId][$temp[$rand_keys[$i]]['name']];
                                while($count<2)
                                        {
                                                if(!array_key_exists($temp[$rand_keys[$iterate]]['name'], $links[$categoryId])) {                                                       
                                                        $links[$categoryId][$temp[$rand_keys[$iterate]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$iterate]]['id'];                                                   
                                                        $count++;
                                                }
                                                $iterate++;
                                        }
                                
                                
                        }
                } else {
                        if(!empty($fixed) && !empty($temp)){
                                foreach ($fixed as $key => $value) {
                                        $links[$categoryId][$key] = $value;
                                }                       
                                for($i=0;$i<3;$i++){
                                        $links[$categoryId][$temp[$rand_keys[$i]]['name']] = "?filter=brand&brands=".$temp[$rand_keys[$i]]['id'];       
                                }
                                        
                        }
                }               
                return $links[$categoryId];             
        }
        
        public function cartdetails(){
                if ($this->request->is('post')) {
                        $dataGiven = json_decode($this->request->data['cart_details']);
                        $pincode = -1;
                        $userId = $this->request->query('user_id');
                        
                        if(isset($this->request->data['pincode'])){
                                $pincodeArgs = explode("_", $this->request->data['pincode']);
                                $pincode = strval($pincodeArgs[1]);
                        }
                        if($pincode==-1 && isset($_COOKIE['s_pincode'])){
                                $pincode = base64_decode($_COOKIE['s_pincode']);
                        }
                        $suserId = 0;
                        $scartId = 0;
                        $semailId = '';
                        
                        if(!(isset($_COOKIE['s_cart']))) {
                                $this->loadModel('UserAccount');
                                $options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
                                $cartId = $this->UserAccount->find('first',$options);
                                $scartId = $cartId['UserAccount']['account_key'];
                                setcookie('s_cart', base64_encode($scartId), -1, '/');
                        }else{
                                $scartId = base64_decode($_COOKIE['s_cart']);
                        }
                        if(!(isset($_COOKIE['s_id']))){
                                $this->loadModel('UserAccount');
                                $options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
                                $userAccount = $this->UserAccount->find('first',$options);
                                $suserId = $userAccount['UserAccount']['account_key'];
                                setcookie('s_id', base64_encode($suserId), -1, '/');
                        }else{
                                $suserId = base64_decode($_COOKIE['s_id']);
                        }
                        if(!(isset($_COOKIE['s_email']))){
                                $this->loadModel('User');
                                $options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
                                $user = $this->User->find('first',$options);
                                $semailId = $user['User']['email'];
                                setcookie('s_email', base64_encode($user['User']['email']), -1, '/');
                        }else{
                                $semailId = base64_decode($_COOKIE['s_email']);
                        }
                        
                        $cartItems = array();
                        
                        foreach ($dataGiven->cartItems as $key=>$obj) {
                            $itemobj = array(
                                                'itemId'   => $key,
                                        'quantity' => $obj->quantity);
                                array_push($cartItems, $itemobj);
                        }
                        $postData = array(
                                                'cartItems'     =>      $cartItems
                                                );
                                                
                        $params = array(
                                        'cartMap' => urlencode(json_encode($postData)));
                        
                        $this->layout = 'cartinnerpages';
                        $url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
                        if($pincode!='-1'){
                                $url = $url.'&pinCode='.$pincode;
                        }
                        
                        $cartskus = $this->post_cartinfo_request($url,$params);
                        if(isset($cartskus['response']) && $cartskus['response']=='error'){
                                if(parse_url($this->referer(), PHP_URL_QUERY)){
                                        if (strpos($this->referer(), 'error=1') !== false){
                                                $this->redirect($this->referer());
                                        }else{
                                                $this->redirect($this->referer().'&error=1');
                                        }
                                }
                                else{
                                        $this->redirect($this->referer().'?error=1');
                                }
                                #$this->redirect(array('controller' => 'deals', 'action' => '?user_id='.$userId.'&error=1'));
                        }else{
                                if(strpos($cartskus['estimateString'],"Can't ship here")===false){
                                        setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
                                }
                                $this->set(compact('cartskus'));
                        }
                }else{
                        $userId = $this->request->query('user_id');
                        $disable = $this->request->query('disable');
                        $disablePage = false;
                        if(isset($disable)){
                                $disablePage = true;
                        }
                        if(!(isset($_COOKIE['s_cart']))) {
                                $this->loadModel('UserAccount');
                                $options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'cartId'),'recursive'=>-1,'fields'=>'account_key');
                                $cartId = $this->UserAccount->find('first',$options);
                                $scartId = $cartId['UserAccount']['account_key'];
                        }else{
                                $scartId = base64_decode($_COOKIE['s_cart']);
                        }
                        if(!(isset($_COOKIE['s_id']))){
                                $this->loadModel('UserAccount');
                                $options = array('conditions'=>array('user_id'=>$userId,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
                                $userAccount = $this->UserAccount->find('first',$options);
                                $suserId = $userAccount['UserAccount']['account_key'];
                        }else{
                                $suserId = base64_decode($_COOKIE['s_id']);
                        }
                        if(!(isset($_COOKIE['s_email']))){
                                $this->loadModel('User');
                                $options = array('contain'=>array('UserAccount'), 'conditions'=>array('User.id'=>$userId),'fields'=>array('username','email'),'recursive'=>-1);
                                $user = $this->User->find('first',$options);
                                $semailId = $user['User']['email'];
                        }else{
                                $semailId = base64_decode($_COOKIE['s_email']);
                        }
                        
                        $pincode = -1;
                        
                        if($pincode==-1 && isset($_COOKIE['s_pincode'])){
                                $pincode = base64_decode($_COOKIE['s_pincode']);
                        }
                        
                        $cartItems = array();
                        $postData = array(
                                        'cartItems'     =>      $cartItems
                                        );
                                        
                        $params = array(
                                        'cartMap' => urlencode(json_encode($postData)));
                        $this->layout = 'cartinnerpages';
                        $url = Configure::read('saholicapihost').'cart!validateCart?isLoggedIn=true&privateDealUser=true&userId='.$suserId.'&id='.$scartId.'&email='.$semailId;
                        if($pincode!='-1'){
                                $url = $url.'&pinCode='.$pincode;
                        }
                        $cartskus = $this->post_cartinfo_request($url,$params);
                        
                        if(isset($cartskus['response']) && $cartskus['response']=='error'){
                                if(parse_url($this->referer(), PHP_URL_QUERY)){
                                        if (strpos($this->referer(), 'error=1') !== false){
                                                $this->redirect($this->referer());
                                        }else{
                                                $this->redirect($this->referer().'&error=1');
                                        }
                                }
                                else{
                                        $this->redirect($this->referer().'?error=1');
                                }
                        }else{
                                if(strpos($cartskus['estimateString'],"Can't ship here")===false){
                                        setcookie('s_pincode', base64_encode($cartskus['pincode']), -1, '/');
                                }
                                $this->set(compact('cartskus'));
                                if($disablePage){
                                        $this->set('disablePage',$disablePage);
                                        $this->render('/Users/cartdetails_disabled');
                                }
                        }
                }
                
        }
        
        public function admin_usersanctions(){
                $url = Configure::read('saholicapihost').'counter!getUsersSanctionDetails?limit=0&offset=0';
                if($this->request->is('post')){
                        $filter = $this->request->data['UserSanctions']['searchUserBy'];
                        if ($filter==1){
                                $url = $url.'&sort=loan';       
                        }
                }
                $response = $this->make_request ( $url, null );
                $userSanctions = $response['response']['userSanctions']['userSanctions'];
                $hasMore = $response['response']['userSanctions']['hasMore'];
                $totalCount = $response['response']['userSanctions']['totalCount'];
                $this->loadModel('UserAccount');
                $usersMap = array();
                $usersName = array();
                foreach($userSanctions AS $userSanction){
                        if (!array_key_exists($userSanction['user_id'], $usersMap)) {
                                $options = array('conditions'=>array('account_key'=>$userSanction['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
                                $userId = $this->UserAccount->find('first',$options);
                                $userId = $userId['UserAccount']['user_id'];
                                $opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>'first_name');
                                $userName = $this->User->find('first',$opts);
                                $usersName[$userSanction['user_id']] = $userName['User']['first_name'];
                                $usersMap[$userSanction['user_id']]=$userId;
                        }
                }
                $this->set(compact('usersName','userSanctions','usersMap','hasMore','totalCount'));
        }
        
        public function admin_credithistory($cuid = 0){
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $limit = 20;
                $offset = ($page - 1)*$limit;
                $this->loadModel('UserAccount');
                
                if($cuid!= 0){
                        $opt = array('conditions'=>array('user_id'=>$cuid,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
                        $usId = $this->UserAccount->find('first',$opt);
                        $cuid = $usId['UserAccount']['account_key'];                    
                }

                $url = Configure::read('saholicapihost').'counter!getCreditHistory?userId='.$cuid.'&limit='.$limit.'&offset='.$offset;
                $response = $this->make_request ( $url, null );
                $creditHistory = $response['response']['creditHistory'];
                $hasMore = $response['response']['hasMore'];
                $totalCount = $response['response']['totalCount'];
                $usersName = array();
                $usersMap = array();
                foreach($creditHistory AS $creditH){
                        if (!array_key_exists($creditH['user_id'], $usersMap)) {
                                $options = array('conditions'=>array('account_key'=>$creditH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
                                $userId = $this->UserAccount->find('first',$options);
                                $userId = $userId['UserAccount']['user_id'];
                                $opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>'first_name');
                                $userName = $this->User->find('first',$opts);
                                $usersName[$creditH['user_id']] = $userName['User']['first_name'];
                                $usersMap[$creditH['user_id']]=$userId;
                        }
                }
                $this->set(compact('creditHistory','usersName','usersMap','hasMore','totalCount','page'));
        }
        
        public function admin_loanhistory($cuid = 0){
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $limit = 20;
                $offset = ($page - 1)*$limit;
                $this->loadModel('UserAccount');
                if($cuid!= 0){
                        $opt = array('conditions'=>array('user_id'=>$cuid,'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'account_key');
                        $usId = $this->UserAccount->find('first',$opt);
                        $cuid = $usId['UserAccount']['account_key'];
                }
                
                $url = Configure::read('saholicapihost').'counter!getLoanHistory?userId='.$cuid.'&limit='.$limit.'&offset='.$offset;
                
                $response = $this->make_request ( $url, null );
                $loanHistory = $response['response']['loanHistory'];
                $hasMore = $response['response']['hasMore'];
                $totalCount = $response['response']['totalCount'];
                $usersName = array();
                $usersMap = array();
                foreach($loanHistory AS $loanH){
                        if (!array_key_exists($loanH['user_id'], $usersMap)) {
                                $options = array('conditions'=>array('account_key'=>$loanH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
                                $userId = $this->UserAccount->find('first',$options);
                                $userId = $userId['UserAccount']['user_id'];
                                $opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>'first_name');
                                $userName = $this->User->find('first',$opts);
                                $usersName[$loanH['user_id']] = $userName['User']['first_name'];
                                $usersMap[$loanH['user_id']]=$userId;
                        }
                }
                                        
                $this->set(compact('usersName','loanHistory','usersMap','hasMore','totalCount','page'));
        }
        
        public function usernotification($user = null){
                $android_id = $this->request->query('android_id');
                $user_id = $this->request->query('user_id');
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $limit = 20;
                $offset = ($page - 1)*$limit;
                $this->layout = 'innerpages';
                $url = Configure::read('nodeurl')."/getAllNotifications?user_id=".$user_id."&android_id=".$android_id."&offset=".$offset."&limit=".$limit;
                $noti= $this->make_request($url,null);
                if(isset($noti) && !empty($noti)){
                        foreach ($noti as $nkey => $nval){
                                if($nval["status"] == "sent" || $nval["status"] == "recieved" || $nval["status"] == "failed"){
                                        $noti[$nkey]['seen'] = false;
                                }
                                if($nval["status"] == "opened" || $nval["status"] == "referrer" || $nval["status"] == "login"){
                                        $noti[$nkey]['seen'] = true;
                                }
                        }
                        $updateCountUrl = Configure::read('nodeurl')."/updateNotificationCount?user_id=".$user_id."&android_id=".$android_id;
                        $this->post_request($updateCountUrl,null);                              
                }
                else{
                        $this->render('/Elements/nonotification');
                }
                $nexturl = "/users/getmorenotification?page=".($page+1)."&user_id=".$user_id."&android_id=".$android_id;
                $this->set(compact('noti','nexturl'));
        }
        
        public function getmorenotification(){
                $this->layout = 'ajax';
                $page = $this->request->query('page');
                $android_id = $this->request->query('android_id');
                $user_id = $this->request->query('user_id');
                if(!isset($page)){
                        $page = 1;
                }
                $limit = 20;
                $offset = ($page - 1)*$limit;
                $url = Configure::read('nodeurl')."/getAllNotifications?user_id=".$user_id."&android_id=".$android_id."&offset=".$offset."&limit=".$limit;
                $noti= $this->make_request($url,null);
                if(isset($noti) && !empty($noti))
                {
                        foreach ($noti as $nkey => $nval){
                                if($nval["status"] == "sent" || $nval["status"] == "recieved" || $nval["status"] == "failed"){
                                        $noti[$nkey]['seen'] = false;
                                }
                                if($nval["status"] == "opened" || $nval["status"] == "referrer" || $nval["status"] == "login"){
                                        $noti[$nkey]['seen'] = true;
                                }
                        }
                }
                $nexturl = "/users/getmorenotification?page=".($page+1)."&user_id=".$user_id."&android_id=".$android_id;
                $this->set(compact('noti','nexturl'));
                $this->render('/Elements/getnotification');
        }
        
        public function sendseen($cid = null){
                
                $data = array();
                $data['cid']=$cid;
                $data['result']='opened';
                $data['user_id']=$this->Auth->user('id');
                $url = Configure::read('nodeurl')."/addPushNotificationByApk";//remove hardcoded value
                $response = $this->post_request($url,$data);
                if(!empty($response)){
                        $result = array('success' => true,'message'=>'The pushnotification has been saved.');
                } else {
                        $result = array('success' => false,'message'=>'The pushnotification could not be saved. Please, try again.');
                }               
                $this->set(array(
                    'result' => $result,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');        
        }

        public function admin_target($userId=null){
                $this->layout = "innerpages";
                $user_id = $userId;
                $cachekey = 'target-'.$user_id;
                $getoffer = Cache::read($cachekey,'target');
                $current_time = time();
                $response = "";
                if($getoffer === false){
                        $offerurl = $this->apihost."getOfferForUser/?user_id=".$user_id;
                        $response = $this->make_request($offerurl,null);
                        Cache::write($cachekey , $response ,'target');
                        if(empty($response)){
                                        $response = "";
                                }
                                
                }else{
                        if(!empty($getoffer)){
                                        $response = $getoffer;
                                }
                }
                
                $maxpercentage = 0;

                if(isset($response['target2_cash_back_percetage']) && !empty($response['target2_cash_back_percetage'])){
                        $maxpercentage = $response['target2_cash_back_percetage'];
                }
                else{
                        if(isset($response['target1_cash_back_percetage']) && !empty($response['target1_cash_back_percetage'])){
                                $maxpercentage = $response['target1_cash_back_percetage'];
                        }
                }
                
                
                $this->loadModel('User');
                $user_email = "";
                if($user_id != null || $user_id != ''){
                        $opt = array('conditions'=>array('id'=>$user_id),'recursive'=>-1,'fields'=>'email');
                        $usId = $this->User->find('first',$opt);
                        $user_email = $usId['User']['email'];
                }
                $this->set(compact('response','maxpercentage','user_email'));
        }
        
        public function admin_userrefund(){
                $id = $this->request->query('id');
                $email = $this->request->query('email');
                $phone = $this->request->query('mob'); 
                $data = $this->request->data['UserRefund'];
                if($this->request->is('post')){
                        $jsonVar = json_encode($data, JSON_NUMERIC_CHECK );
                        $url = $this->apihost."refundToWallet";
                        $response = $this->make_request($url, $jsonVar);
                        if ($response['result'] == 'success') {
                                $this->Session->setFlash("Query submitted. Pending for Approval.");
                                return $this->redirect(array('action' => 'admin_search'));
                        } else {
                                $this->Session->setFlash("Query not submitted");
                        }
                }
                                
                $this->set(compact('id','phone','email'));
        }
        
        public function admin_userretailer()
        {}
        
        public function admin_searchuserretailer()
        {
                $this->autoRender = false;
                $this->request->onlyAllow ( 'ajax' );
                $type = $this->request->query('type');
                $search = $this->request->query('search');
                $searchfor = $this->request->query('searchfor');
                $this->User->recursive = -1;
                $options = array('limit'=>100,'order'=>array('id'=>'desc'));
                
                $response = "";
                if(!empty($type) && !empty($search)){                   
                        if($searchfor == "usertype"){
                                $options['conditions'] = array($type.' LIKE '=>"%$search%");
                                $users = $this->User->find('all',$options);
                                $response = $users;
                        }elseif($searchfor == "retailertype"){
                                $this->loadModel('Retailer');
                                if($type=='contact'){
                                        $options['conditions'] =array('OR'=>array('contact1 LIKE '=>"%$search%",'contact2 LIKE '=>"%$search%"));
                                }else{
                                        $options['conditions'] = array($type.' LIKE '=>"%$search%");
                                }
                                
                                $users = $this->Retailer->find('all',$options);

                                $response = $users;

                        }

                }
                return json_encode($response);
        }
        
        public function admin_addretailer(){
                

                if ($this->request->is('post')) {
                        $agentid = Configure::read('agentid');
                        $cur_date = date('Y-m-d H:i:s', time());
                        $data = $this->request->data['Retailer'];
                        $retailer['Retailer']['identifier'] = NULL;
                        $retailer['Retailer']['title'] = $data['storeName'];
                        $retailer['Retailer']['address'] = $data['completeAddress'];
                        $retailer['Retailer']['contact1'] = $data['mobileNumber'];
                        $retailer['Retailer']['status'] = "pending_verification";
                        $retailer['Retailer']['is_elavated'] = 1;
                        $retailer['Retailer']['pin'] = $data['pin'];
                        $retailer['Retailer']['city'] = $data['city'];
                        $retailer['Retailer']['state'] = $data['state'];
                        $retailer['Retailer']['retry_count'] = 0;
                        $retailer['Retailer']['invalid_retry_count'] = 0;
                        $retailer['Retailer']['call_priority'] = NULL;
                        $retailer['Retailer']['next_call_time'] = 0;
                        $retailer['Retailer']['is_std'] = 0;
                        $retailer['Retailer']['is_or'] = 0;
                        $retailer['Retailer']['disposition'] = "inbound_call";
                        $retailer['Retailer']['source'] = "inbound";
                        $retailer['Retailer']['created'] = $cur_date;
                        $retailer['Retailer']['modified'] = $cur_date;
                        $retailer['Retailer']['tinnumber'] = $data['tinNumber'];
                        $retailer['Retailer']['next_call_time'] = NULL;
                        $retailer['Retailer']['isvalidated'] = 0;
                        
                        
                        $this->loadModel('Retailer');
                        $this->Retailer->create();
                        if ($retdata = $this->Retailer->save($retailer)) {
                                $this->Session->setFlash(__('The user has been saved'));
                                $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."')";
                                $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."')";
                                $this->User->query($contactquery);
                                $this->User->query($callhistoryquery);
                                $this->redirect('userretailer');
                        } else {
                                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                        }
                }
        }
        
        public function getcode($id){
                $this->autoRender = false;
                $this->request->onlyAllow('ajax');
                $agentid = Configure::read('agentid');
                $url = $this->apihost."getDtrLink/".$agentid."/fresh/".$id;
                $response = $this->make_request($url,null); 
                
                return json_encode($response['result']);
                
        }
        
        public function admin_outstanding($type,$userId=null) {
                $url = Configure::read('saholicapihost').'counter!getOutstandingLoans?fetchType='.$type;
                if(isset($userId)){
                        $url = $url.'&userId='.$userId;
                }
                $response = $this->make_request ( $url, null );
                $outstandingPayments = $response['response'];
                $usersName = array();
                $usersMap = array();
                $this->loadModel('UserAccount');
                foreach($outstandingPayments AS $loanH){
                        if (!array_key_exists($loanH['user_id'], $usersMap)) {
                                $options = array('conditions'=>array('account_key'=>$loanH['user_id'],'account_type'=>'saholic'),'recursive'=>-1,'fields'=>'user_id');
                                $userId = $this->UserAccount->find('first',$options);
                                $userId = $userId['UserAccount']['user_id'];
                                $opts = array('conditions'=>array('id'=>$userId),'recursive'=>-1,'fields'=>array('first_name','email'));
                                $userName = $this->User->find('first',$opts);
                                $usersName[$loanH['user_id']] = $userName['User']['first_name'];
                                $usersMap[$loanH['user_id']]=$userName['User']['email'];
                        }
                }
                $this->set(compact('usersName','outstandingPayments','usersMap'));
                if($type=='credit'){
                        $this->render('admin_outstandingcredits');
                }
        }
        
        public function admin_marksettlement(){
                if(empty($this->request->data['repayment_date']) || empty($this->request->data['amount'])){
                        $message = "Please fill a valid date or amount for the settlement";
                }
                elseif ($this->request->data['amount']<=0){
                        $message = "Please check the amount that you filled earlier";
                }else{
                        $payload = $this->request->data;
                        $url = Configure::read('saholicapihost').'counter!markOutstandingPaymentsAsSettled?settlement='.json_encode($payload,JSON_NUMERIC_CHECK);
                        $response = $this->make_request($url,json_encode($payload,JSON_NUMERIC_CHECK));
                        $message = $response['response'][key($response['response'])];
                }
                $this->set(compact('message'));
        }
}