Subversion Repositories SmartDukaan

Rev

Rev 19812 | Blame | Compare with Previous | Last modification | View Log | RSS feed

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

set_time_limit(0);

class UsersController extends AppController {

        //public $components = array('SignMeUp.SignMeUp','RequestHandler','Cookie','Paginator');
        public $components = array('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')); 
                $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() {
                throw new NotFoundException(__('Unauthorized access'));
                $this->log(print_r($_REQUEST,1),'onering');
                error_log(print_r($_REQUEST,1),3,TMP.'logs/onering.log');
                $this->layout = "ajax";
                $this->response->type('json');
                $this->set(array(
                    'result' => $_REQUEST,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }

        public function mywallet() {
                throw new NotFoundException(__('Unauthorized access'));
                $userId = $this->request->query('user_id');
                $tokenValidated = $this->checkToken();
                if(isset($userId) && !empty($userId) && $tokenValidated){       
                        $next = "/my-wallet";                                   
                        $redirectUrl = $this->getAutoLoginUrl($userId,$next);
                        header('location:'.$redirectUrl);
                        exit();
                }else{
                        $this->redirect(array('controller'=>'special','action'=>'native','login'));
                }
        }

        public function socialauth() {
                throw new NotFoundException(__('Unauthorized access'));
                $this->layout = "ajax";
                $this->log(print_r($this->request->data,1),'socialauth');
        }

        public function mine() {
                throw new NotFoundException(__('Unauthorized access'));
                $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(){
                throw new NotFoundException(__('Unauthorized access'));
                $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){
                throw new NotFoundException(__('Unauthorized access'));
                $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(){
                throw new NotFoundException(__('Unauthorized access'));
                $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() {
                throw new NotFoundException(__('Unauthorized access'));
        $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) {
                throw new NotFoundException(__('Unauthorized access'));
                $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) {
                throw new NotFoundException(__('Unauthorized access'));
                $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(!empty($this->request->data['referrer'])) {
                                $referrer = $this->request->data['referrer'];
                                $this->log(print_r($referrer,1),'activations');
                                $this->loadModel('ActivationCode');
                                $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;
                                }
                                $this->request->data['activated'] = 1;
                        }                               
                        if($updateRequired){
                            if ($this->User->save($this->request->data)) {
                                $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(){
                throw new NotFoundException(__('Unauthorized access'));
                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){
                throw new NotFoundException(__('Unauthorized access'));
                //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(){
                throw new NotFoundException(__('Unauthorized access'));
                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']);
                                if($this->NotificationCampaign->save($data)){
                                        $message['cid'] = $this->NotificationCampaign->getLastInsertId();
                                } else{
                                        debug($this->NotificationCampaign->validationErrors);
                                        $message['cid'] = $message['name'];
                                }
                                if($message['type'] == 'url' && !empty($message['url'])) {
                                        $url = $message['url'];
                                        $this->loadModel('Store');
                                        $store = $this->Store->getByUrl($url);                                  
                                }                               
                                $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);
                                }
                        }
                }
        }

        private function send_push_notification($registatoin_ids, $message, $user_id) {
                throw new NotFoundException(__('Unauthorized access'));
                $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');
                $data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$user_id,'status'=>$res['success']);
                $this->Pushnotification->create();
                $this->Pushnotification->save($data);
                // Close connection
                curl_close($ch);
                $this->log("For $user_id ".$registatoin_ids[0]." ".print_r($result,1),'pushnotifications');
        }

        public function admin_index() {         
                throw new NotFoundException(__('Unauthorized access'));
                $this->User->recursive = 0;
                $options = array('limit'=>100,'order'=>array('id'=>'desc'));
                $this->Paginator->settings = $options;
                $users = $this->Paginator->paginate();
                $groups = $this->User->Group->find('list');
                $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() {
                throw new NotFoundException(__('Unauthorized access'));
                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) {
                throw new NotFoundException(__('Unauthorized access'));
                $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) {
                throw new NotFoundException(__('Unauthorized access'));
                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 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() {
                throw new NotFoundException(__('Unauthorized access'));
                $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() {
                throw new NotFoundException(__('Unauthorized access'));
                $this->layout = 'auth';
                $this->set('title_for_layout','Activate your copublish.in account');
                $this->SignMeUp->activate();
        }

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

        public function login() {
                $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'));            
                    if ($user['User']['group_id'] == 2 || $user['User']['group_id'] == 6 || $user['User']['group_id'] == 99) {
                                $this->redirect(array('controller' => 'administration', 'action' => 'dashboard'));
                                exit();
                    }
                        if ($user['User']['group_id'] == 1) {
                                $this->redirect(array('controller' => 'deals', 'action' => 'mine?user_id='.$user['User']['id']));
                                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() {
                $this->Session->setFlash(__('You have been logged out now'),'success_message');
                $this->redirect($this->Auth->logout());
        }

        public function updatetimezone() {
                throw new NotFoundException(__('Unauthorized access'));
                $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() {
                throw new NotFoundException(__('Unauthorized access'));
                $this->layout = 'innerpages';
        }

        public function getdial2verifynumber() {
                throw new NotFoundException(__('Unauthorized access'));
                $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() { 
                throw new NotFoundException(__('Unauthorized access'));
                $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() {
                throw new NotFoundException(__('Unauthorized access'));
                $this->Session->write('skipmobileverification',1);
                $this->redirect(array('controller'=>'store_products','action'=>'mine',"?" => array( "user_id" => $this->Auth->User('id'))));
        }

        public function reauthenticate($userId) {
                throw new NotFoundException(__('Unauthorized access'));
                $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 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)'=>'');                       
                }       
                
                $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' => 'appacls',
                        'alias' => 'Appacl',
                        'type' => 'LEFT',
                        'conditions' => array(
                            'Appacl.user_id = User.id',
                        )
                    )
            );
                $this->Paginator->settings = $options;
                $users = $this->Paginator->paginate();          
                

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

        public function getDateInstallsBy($date, $user_id){
                
                $this->autoRender = false;      
                $this->request->onlyAllow('ajax');
                $url = $this->apihost.'appUserBatchDateDrillDown/'.$user_id.'/'.$date;
                $getApp = $this->make_request($url,null);
                return json_encode($getApp);    
        }

    public function admin_backlog()
    {
        
    }
    
    public function admin_by($userId = null) {
    
        $this->loadModel('UserAddress');
        $postOfficeQuery="select pincode,state from postoffices group by pincode";
        $postOfficeResult=$this->UserAddress->query($postOfficeQuery);
        $postOffice=array();
        foreach($postOfficeResult as $value){
                $postOffice[$value['postoffices']['pincode']]=$value['postoffices']['state'];
        }
    
        $retailerAddress="SELECT r.title,r.address, r.city,r.state,r.pin from retaileraddresses r join retailerlinks rl on r.retailer_id=rl.retailer_id where rl.user_id=$userId";
        $new_address=$this->UserAddress->query($retailerAddress);
    
        $retailerAddress="SELECT title,address,city,state,pin from retailers r join retailerlinks rl on r.id=rl.retailer_id where rl.user_id=$userId";
        $retailer_address=$this->UserAddress->query($retailerAddress);
    
        $retailerAddress="SELECT ua.store_name,ua.address,ua.city,ua.state,ua.pincode from user_addresses ua join users u on ua.user_id=u.id where ua.user_id=$userId";
        $user_update_address=$this->UserAddress->query($retailerAddress);
    
        $retailerAddress="SELECT concat(' ', address_line_1,address_line_2) as address,city,state,pincode from users where id=$userId";
        $user_address=$this->UserAddress->query($retailerAddress);
        if($user_address[0]['users']['state']==null){
                if($user_address[0]['users']['pincode']==null){
    
                }else{
                        $user_address[0]['users']['state']=$postOffice[$user_address[0]['users']['pincode']];
                }
        }
    
        if(empty($new_address)){
    
        }else{
                if(empty($new_address[0]['r']['state'])){
                        $new_address[0]['r']['state']=$postOffice[$new_address[0]['r']['pin']];
                }
        }
        if(empty($retailer_address)){
    
        }else{
                if(empty($retailer_address[0]['r']['state'])){
                        $retailer_address[0]['r']['state']=$postOffice[$retailer_address[0]['r']['pin']];
                }
        }
        if(empty($user_update_address)){
    
        }else{
                if(empty($user_update_address[0]['ua']['state'])){
                        $user_update_address[0]['ua']['state']=$postOffice[$user_update_address[0]['ua']['pincode']];
                }
        }
        $this->set('newaddress', $new_address);
        $this->set('retaileraddress', $retailer_address);
        $this->set('userupdateaddress', $user_update_address);
        $this->set('useraddress', $user_address);
    }
    
    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_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);
                        
                        $this->log(print_r($users,1),'demo');
                        
                        foreach ($users as $ukey => $uvalue){
                                $rquery = "select * from retaileraddresses where retailer_id =".$uvalue['Retailer']['id']." order by id desc limit 1";
                                $rresp = $this->User->query($rquery);
                                foreach ($rresp as $rakey => $ravalue){
                                        $users[$ukey]['Retailer']['title'] = $ravalue['retaileraddresses']['title'];
                                        $users[$ukey]['Retailer']['address'] = $ravalue['retaileraddresses']['address'];
                                        $users[$ukey]['Retailer']['pin'] = $ravalue['retaileraddresses']['pin'];
                                        $users[$ukey]['Retailer']['city'] = $ravalue['retaileraddresses']['city'];
                                        $users[$ukey]['Retailer']['state'] = $ravalue['retaileraddresses']['state'];
                                }
                        }
                        
                        $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){
        $agentid = Configure::read('agentid'); 
        $this->autoRender = false;
        $this->request->onlyAllow('ajax');
        $url = $this->apihost."getDtrLink/".$agentid."/fresh/".$id;
        $response = $this->make_request($url,null);
    
        return json_encode($response['result']);
    
    }
}